问:
Printing out Words for a Python Word Game that uses Parallelism/Multiprocessing
I am working on a Multiprocessing Word game with Python. And I need some help with getting the program to print words to the screen. The original code, that i started out with, before I added code for Multiprocessing, was able to print words out from the screen. I'm using a dictionary, where each words is a 3 letter word. The goal of the game is to, ask "What is the 1st word" & "What is the 2nd word. And then, the program changes 1 letter at a time, until it reaches the 2nd word. I will include the original code, that is able to print words from the screen, somewhere in the comments, if i can.

Here is the link to the dictionary that I am using. But, u can also use a dictionary of ur choice. text

Below is the fist part of my code. vvvvvvvvvvvvvv

```<code>```python
from multiprocessing import Process, Queue

class node:
    def __init__(self, word):
        self._word = word
        self._neighbors = []
        self._status = 0
        self._discoveredby = 0

    def getWord(self):
        return self._word

    def getNeighbors(self):
        return self._neighbors

    def addNeighbor(self, neighbor_index):
        self._neighbors.append(neighbor_index)

    def isUnseen(self):
        if self._status == 0:
            return True
        else:
            return False

    def isSeen(self):
        if self._status == 1:
            return True
        else:
            return False

    def setUnseen(self):
        self._status = 0

    def setSeen(self):
        self._status = 1

    def discover(self, n):
        self._discoveredby = n

    def discovered(self):
        return self._discoveredby

#Get starting and ending word
word1 = input("What is the starting word? ")
word2 = input("What is the ending word? ")
```python
</code>```

Also, here is the second part of the code for the word Game. It does not have any errors as far as I know. But, what i'm wondering is.

Why does it not print out the words to the screen?

The Original code that I started out with, before modifying it to use Multiprocessing, was able to print words to the screen. I can include my original code, in the comments if u want to see it.

And here is the Dictionary again text

```<code>```python
if __name__ == '__main__':
    #Read in the words from a dictionary
    words = []
    dict = open("Word Game Text.txt", 'r')
    for line in dict:
        word = node(line.strip())
        words.append(word)

def findlinks(words, q, starti, endi):
    for i in range(starti, endi):
        for j in range(i + 1, len(words)):
            #compare word i and word j
            if compareWords(words[i].getWord(), words[j].getWord()):
                q.put((i, j))  #addLink(words, i, j)

    q = Queue()
    process_list = []
    for i in range(0,len(words)-100,100):
        p = Process(target=findlinks, args=(words,q, i, i+100))
        process_list.append(p)
    p = Process(target=findlinks, args=(words, q, i+100, len(words)))
    process_list.append(p)
    for p in process_list:
        p.start()
    while not q.empty():
        i, j = q.get()
        addLink(words, i, j)
    for p in process_list:
        p.join()

    while not q.empty():
        i, j = q.get()
        addLink(words, i, j)

    index1 = -1
    index2 = -1
    for i in range(len(words)):
        if words[i].getWord() == word1:
            index1 = i
        if words[i].getWord() == word2:
            index2 = i
    if index1 == -1:
        print(word1,"was not in the dictionary. Exiting.")
        exit(0)
    if index2 == -1:
        print(word2,"was not in the dictionary. Exiting.")
        exit(0)

    path = BFS(words, index1, index2)

    #Report the chain
    if path == []:
        print("There was no chain between those words, in my dictionary")
    else:
        for index in path:
            print(words[index].getWord())
            #print(words[index].getWord())
```python
</code>```

Body:
I am working on a Multiprocessing Word game with Python. And I need some help with getting the program to print words to the screen. The original code, that i started out with, before I added code for Multiprocessing, was able to print words out from the screen. I'm using a dictionary, where each words is a 3 letter word. The goal of the game is to, ask "What is the 1st word" & "What is the 2nd word. And then, the program changes 1 letter at a time, until it reaches the 2nd word. I will include the original code, that is able to print words from the screen, somewhere in the comments, if i can.

Here is the link to the dictionary that I am using. But, u can also use a dictionary of ur choice. text

Below is the fist part of my code. vvvvvvvvvvvvvv

```python
from multiprocessing import Process, Queue

class node:
    def __init__(self, word):
        self._word = word
        self._neighbors = []
        self._status = 0
        self._discoveredby = 0

    def getWord(self):
        return self._word

    def getNeighbors(self):
        return self._neighbors

    def addNeighbor(self, neighbor_index):
        self._neighbors.append(neighbor_index)

    def isUnseen(self):
        if self._status == 0:
            return True
        else:
            return False

    def isSeen(self):
        if self._status == 1:
            return True
        else:
            return False

    def setUnseen(self):
        self._status = 0

    def setSeen(self):
        self._status = 1

    def discover(self, n):
        self._discoveredby = n

    def discovered(self):
        return self._discoveredby

#Get starting and ending word
word1 = input("What is the starting word? ")
word2 = input("What is the ending word? ")
```python

Also, here is the second part of the code for the word Game. It does not have any errors as far as I know. But, what i'm wondering is.

Why does it not print out the words to the screen?

The Original code that I started out with, before modifying it to use Multiprocessing, was able to print words to the screen. I can include my original code, in the comments if u want to see it.

And here is the Dictionary again text

```python
if __name__ == '__main__':
    #Read in the words from a dictionary
    words = []
    dict = open("Word Game Text.txt", 'r')
    for line in dict:
        word = node(line.strip())
        words.append(word)

def findlinks(words, q, starti, endi):
    for i in range(starti, endi):
        for j in range(i + 1, len(words)):
            #compare word i and word j
            if compareWords(words[i].getWord(), words[j].getWord()):
                q.put((i, j))  #addLink(words, i, j)

    q = Queue()
    process_list = []
    for i in range(0,len(words)-100,100):
        p = Process(target=findlinks, args=(words,q, i, i+100))
        process_list.append(p)
    p = Process(target=findlinks, args=(words, q, i+100, len(words)))
    process_list.append(p)
    for p in process_list:
        p.start()
    while not q.empty():
        i, j = q.get()
        addLink(words, i, j)
    for p in process_list:
        p.join()

    while not q.empty():
        i, j = q.get()
        addLink(words, i, j)

    index1 = -1
    index2 = -1
    for i in range(len(words)):
        if words[i].getWord() == word1:
            index1 = i
        if words[i].getWord() == word2:
            index2 = i
    if index1 == -1:
        print(word1,"was not in the dictionary. Exiting.")
        exit(0)
    if index2 == -1:
        print(word2,"was not in the dictionary. Exiting.")
        exit(0)

    path = BFS(words, index1, index2)

    #Report the chain
    if path == []:
        print("There was no chain between those words, in my dictionary")
    else:
        for index in path:
            print(words[index].getWord())
            #print(words[index].getWord())
```python


来源: stackexchange

问:
Preventing connections to SQL Server from SSMS
I've heard it said many times that the Windows Authentication is preferred over SQL Server authentication when it comes to securing SQL Server, however, this has always struck me as counterintuitive since if a user's Windows Authentication requires them to be able to modify tables, then there's no way to prevent this activity should they log in using SSMS - bypassing the application logic.

I've used server triggers in the past to prevent this but I've also had a couple scenarios where this left us unable to log on to the SQL Server.  I also get that many people would argue that, for this reason, all updates to the database should be done via stored procedures - which isn't an option for us since many of our applications are COTS.

How have others handled this?  Am I the only one who sees this as a problem?

ContentLicense: CC BY-SA 4.0


问:
Call Logout On Browser Tab Close, Browser Close or Navigate To Some Other Website, Not On Reload- 2022

I tried solving this with beforeunload, unload, page visibility, etc event but nothing seems to work.

```<code>
  useEffect(() => {

    window.addEventListener("beforeunload", alertUser);

    return () => {
      window.removeEventListener("beforeunload", alertUser);
    };

  }, []);

  const alertUser = async (ev) => {
    if (
      isLoggedIn &&
      performance.getEntriesByType("navigation")[0].type !== "reload"
    ) {
      await logoutMethod();
    }
  };

</code>```

I tried to handle reload case with performance navigation, but it is giving inconsistent results. Any help is appreciated, Thanks in advance. I saw some related questions/answers but nothing seems to work with the current chrome version.

Tried eventlisteners, beacon api.

Body:
I tried solving this with beforeunload, unload, page visibility, etc event but nothing seems to work.

  useEffect(() => {

    window.addEventListener("beforeunload", alertUser);

    return () => {
      window.removeEventListener("beforeunload", alertUser);
    };

  }, []);

  const alertUser = async (ev) => {
    if (
      isLoggedIn &&
      performance.getEntriesByType("navigation")[0].type !== "reload"
    ) {
      await logoutMethod();
    }
  };

I tried to handle reload case with performance navigation, but it is giving inconsistent results. Any help is appreciated, Thanks in advance. I saw some related questions/answers but nothing seems to work with the current chrome version.

Tried eventlisteners, beacon api.


问:
How does one reinstall an opam package/proj using the absolute path to the project without relying on opam pin?
In the past I've used this command:

```<code>    opam reinstall --yes --switch ocaml-variants.4.07.1+flambda_coq-serapi.8.11.0+0.11.1 --keep-build-dir lf
</code>```

I think this command only worked because I also pinned the pkg e.g. (ran it from within python from unimportant reasons):

```<code>    command = (['opam', 'pin', '-y']
               + root_option()
               + ['--switch', switch]
               + [coq_package, coq_package_pin])
</code>```

How do I reinstall it using the path to the proj instead i.e. using coq_package_pin?

I think something like this should work:

```<code>    command: list = ['opam'] + ['reinstall'] + root_option() + ['--yes'] + ['--switch', switch] + \
                    ['--keep-build-dir', coq_project_path] + \
                    [coq_project_path]
</code>```

Note pining the package is giving me issues so I'd like to avoid it if possible.

related:

Is an opam pin project needed when one wants to install an opam project with opam reinstall or 'make'?

https://discuss.ocaml.org/t/how-does-one-reinstall-an-opam-package-proj-using-the-absolute-path-to-the-project-without-relying-on-opam-pin/10944

https://discuss.ocaml.org/t/what-is-the-difference-between-opam-pin-and-opam-install-when-to-use-one-vs-the-other/10942/5

Body:
In the past I've used this command:

    opam reinstall --yes --switch ocaml-variants.4.07.1+flambda_coq-serapi.8.11.0+0.11.1 --keep-build-dir lf

I think this command only worked because I also pinned the pkg e.g. (ran it from within python from unimportant reasons):

    command = (['opam', 'pin', '-y']
               + root_option()
               + ['--switch', switch]
               + [coq_package, coq_package_pin])

How do I reinstall it using the path to the proj instead i.e. using coq_package_pin?

I think something like this should work:

    command: list = ['opam'] + ['reinstall'] + root_option() + ['--yes'] + ['--switch', switch] + \
                    ['--keep-build-dir', coq_project_path] + \
                    [coq_project_path]

Note pining the package is giving me issues so I'd like to avoid it if possible.

related:

Is an opam pin project needed when one wants to install an opam project with opam reinstall or 'make'?

https://discuss.ocaml.org/t/how-does-one-reinstall-an-opam-package-proj-using-the-absolute-path-to-the-project-without-relying-on-opam-pin/10944

https://discuss.ocaml.org/t/what-is-the-difference-between-opam-pin-and-opam-install-when-to-use-one-vs-the-other/10942/5


问:
Is there any way to know how many bytes a client downloaded from a file on my server?
I'm looking for a way to get that information. I'm currently dealing with the problem of track how many seconds of an mp3 file were listened from the backend side. I've been working with  the "Content-Range" header but it doesn't provide the information that I need (considering the accuracy of it). So, I started thinking in this other way to track this information, does anyone has experience with this?

Thanks!

I tried to intercept "Partial Content" requests with success, but doesn't provide the level of accuracy that I need. For doing this I have a small node express app that does this:

```<code>app.get('/episodes/:filename', (req, res, next) => {
    console.log("HEADERS RANGE", req.headers.range);
    // res.send(req.params)
    next();
})
</code>```

I have a folder called episodes on my project public folder, so, before the server returns the file I'm intercepting it to log requested range values.

Again, this is working fine, but I'm searching for a more accurate solution which I think it's related to the problem that I described initially.

Body:
I'm looking for a way to get that information. I'm currently dealing with the problem of track how many seconds of an mp3 file were listened from the backend side. I've been working with  the "Content-Range" header but it doesn't provide the information that I need (considering the accuracy of it). So, I started thinking in this other way to track this information, does anyone has experience with this?

Thanks!

I tried to intercept "Partial Content" requests with success, but doesn't provide the level of accuracy that I need. For doing this I have a small node express app that does this:

app.get('/episodes/:filename', (req, res, next) => {
    console.log("HEADERS RANGE", req.headers.range);
    // res.send(req.params)
    next();
})

I have a folder called episodes on my project public folder, so, before the server returns the file I'm intercepting it to log requested range values.

Again, this is working fine, but I'm searching for a more accurate solution which I think it's related to the problem that I described initially.


问:
How to get more than 100 tweets by a search query using Tweepy? Cursor issues
I understand that using tweepy.Cursor is important for retrieving more than 100 texts, from the tutorials I have watched. The following is my code:

```<code>tweets=[]

for tweet in tweepy.Cursor(api.search_tweets,
                           q=query, lang='en', result_type='recent',
                           tweet_mode='extended', count=100).items(max_tweets):
    tweets.append(tweet)
</code>```

However, I get this error at the moment:

```<code>Forbidden: 403 Forbidden
195 - Missing or invalid url parameter.
</code>```

I can get up to 100 results without hassle. What am I doing wrong here? I'm going by this tutorial:

https://www.youtube.com/watch?v=FmbEhKSpR7M&t=170s

Body:
I understand that using tweepy.Cursor is important for retrieving more than 100 texts, from the tutorials I have watched. The following is my code:

tweets=[]

for tweet in tweepy.Cursor(api.search_tweets,
                           q=query, lang='en', result_type='recent',
                           tweet_mode='extended', count=100).items(max_tweets):
    tweets.append(tweet)

However, I get this error at the moment:

Forbidden: 403 Forbidden
195 - Missing or invalid url parameter.

I can get up to 100 results without hassle. What am I doing wrong here? I'm going by this tutorial:

https://www.youtube.com/watch?v=FmbEhKSpR7M&t=170s


问:
Metric is neither callable, nor a recognised string issue
i  am using UMAP method from the following link :metrix in UMAP

here is  code fragment :

```<code>import umap
embedding = umap.UMAP(n_components=2, metric='hellinger').fit(word_doc_matrix)
</code>```

where  word_doc_matrix is calculated using CountVectorizer command

```<code>vectorizer =CountVectorizer(min_df=5,stop_words='english')
word_doc_matrix =vectorizer.fit_transform(dataset.data)
</code>```

i have searched   about this issue and  saw  the following link :
information about issue

so how can i  fix it?

Body:
i  am using UMAP method from the following link :metrix in UMAP

here is  code fragment :

import umap
embedding = umap.UMAP(n_components=2, metric='hellinger').fit(word_doc_matrix)

where  word_doc_matrix is calculated using CountVectorizer command

vectorizer =CountVectorizer(min_df=5,stop_words='english')
word_doc_matrix =vectorizer.fit_transform(dataset.data)

i have searched   about this issue and  saw  the following link :
information about issue

so how can i  fix it?


问:
Sequelize and Mysql throw connect ETIMEDOUT error In production enviroment
I have a nodejs server with express and sequelize. When I was in development enviroment I didn't have any problem then in production enviroment sometimes the entire app throw this error in everyrequest
ConnectionError [SequelizeConnectionError]: connect ETIMEDOUT for a few minutes then the server starts to work normally.

In the server I use pm2 cluster mode(8 instances) to handle all the requests.

Is the first that I manage a server and a DB and I read some articles, I've tried changing mysql enviroment variables and the sequelize pool options but the problem persists.

I'm not sure if the problem is in the variables or the server specs or pm2 config. I hope someone can give a hint of the problem.

mysql variables

```<code>skip_name_resolve = 1

join_buffer_size = 50M

tmp_table_size = 2G

max_heap_table_size = 2G

thread_cache_size = 40

max_connections=1600

key_buffer_size=195k

innodb_buffer_pool_size = 4G

innodb_log_file_size = 512M

key_buffer_size = 1M

innodb_buffer_pool_instances = 4
</code>```

sequelize configuration

```<code>{
    host: config.bd_host,
    dialect: 'mysql',
    logging: false,
    pool: {
      max: 100,
      min: 0,
      acquire: 1000000,
      idle: 100000,
      evict: 2000,
    },
    dialectOptions: {
      decimalNumbers: true,
    },
  }
</code>```

Server specifications

64gb RAM

16 cores proccesor

ubuntu 18.04.5 lts

mysql version 14.14 Distrib 5.7.40, for Linux (x86_64) using  EditLine wrapper

express 4.17.1

sequelize 6.19.1

node version 14.17.2

Body:
I have a nodejs server with express and sequelize. When I was in development enviroment I didn't have any problem then in production enviroment sometimes the entire app throw this error in everyrequest
ConnectionError [SequelizeConnectionError]: connect ETIMEDOUT for a few minutes then the server starts to work normally.

In the server I use pm2 cluster mode(8 instances) to handle all the requests.

Is the first that I manage a server and a DB and I read some articles, I've tried changing mysql enviroment variables and the sequelize pool options but the problem persists.

I'm not sure if the problem is in the variables or the server specs or pm2 config. I hope someone can give a hint of the problem.

mysql variables

skip_name_resolve = 1

join_buffer_size = 50M

tmp_table_size = 2G

max_heap_table_size = 2G

thread_cache_size = 40

max_connections=1600

key_buffer_size=195k

innodb_buffer_pool_size = 4G

innodb_log_file_size = 512M

key_buffer_size = 1M

innodb_buffer_pool_instances = 4

sequelize configuration

{
    host: config.bd_host,
    dialect: 'mysql',
    logging: false,
    pool: {
      max: 100,
      min: 0,
      acquire: 1000000,
      idle: 100000,
      evict: 2000,
    },
    dialectOptions: {
      decimalNumbers: true,
    },
  }

Server specifications

64gb RAM

16 cores proccesor

ubuntu 18.04.5 lts

mysql version 14.14 Distrib 5.7.40, for Linux (x86_64) using  EditLine wrapper

express 4.17.1

sequelize 6.19.1

node version 14.17.2


问:
I need to print a 2D graph using Slashes and Pipe symbols " / \ | " in Python
Here is the instructions to print the 2D graph

The user will input a word.

For the alphabets a to z, numbers from 1 to 26 will be assigned for each alphabet starting from ‘a’ i.e,
(a=1,b=2,c=3,d=4,e=5,........,y=25,z=26)

If the input word is "aejz" then then the list that should be generated for the graph will look like this[1,5,10,26]

If the letter is a consonant then the line has to go up (using /) incrementing till it reaches its positional value(a=1,....,z=26) and
if it is vowel then the graph will come down (using ) decrementing
till it reaches its positional value.

If the previous letter and the current letter are consonants then there will be a gap created using two pipes(|), one above another. And
also if the previous letter and the current letter are both vowels
then there will also be a gap created using two pipes, one below
another.

Man like symbol will be created for the highest peak.

Sample Input and Output: Sample
1, Sample
2, Sample
3

Here is what I have done
I have tried to collect the word as input and converted it to the respective numbers i.e a=1, b=2,..z=26.

```<code>alpha=["a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z"]
usr_input=str(input("Enter the strings: "))
usr_input=usr_input.lower()
for l in usr_input:
    if l in alpha:
        num=(alpha.index(l)+1)
        data.append(num)
</code>```

And then for the purpose of check are the given numbers are vowels or not I have used a if condition

```<code>for i in data:
    if i==1 or i==5 or i==9 or i==15 or i==21:
        print("\\"*i)
    else:
       print("/"*i)
</code>```

And then I got stuck I can't able to print the result as in graph format and then I cannot able to fit the pipe(|) symbol when If the previous letter and the current letter are consonants and then printing the man symbol at the highest peak

Here is the code to print the man, but I don't know how to place it in the highest peak

```<code>print(' \u25cb',"\n/|\\\n< >")
</code>```

The whole progress I did after posting it to the SO

```<code>    #Getting words from users and coverting it to numbers
data=[]
alpha=["a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z"]
usr_input=str(input("Enter the strings: "))
usr_input=usr_input.lower()
for l in usr_input:
    if l in alpha:
        num=(alpha.index(l)+1)
        data.append(num)
vow=[1, 5, 9, 15, 21]
#operations
final=[]
max_column=sum(data)
for i in range(max_column):
    final.append([" "] * (max_column*2))
    final.append([" "] * (max_column*2))

def graph(data):
    x,y=0,0
    tmp=[]
    for i,j in enumerate(data):
        tmp.append(j)

        if j not in vow:
            for _ in range(j):
                final[x][y]="\\"
                x+=1
                y+=1

        else:

            for _ in range(j):
                x-=1
                final[x][y]="/"
                y+=1

graph(data)

for res in final:
    print("".join(res))
</code>```

Output: image

Body:
Here is the instructions to print the 2D graph

The user will input a word.

For the alphabets a to z, numbers from 1 to 26 will be assigned for each alphabet starting from ‘a’ i.e,
(a=1,b=2,c=3,d=4,e=5,........,y=25,z=26)

If the input word is "aejz" then then the list that should be generated for the graph will look like this[1,5,10,26]

If the letter is a consonant then the line has to go up (using /) incrementing till it reaches its positional value(a=1,....,z=26) and
if it is vowel then the graph will come down (using ) decrementing
till it reaches its positional value.

If the previous letter and the current letter are consonants then there will be a gap created using two pipes(|), one above another. And
also if the previous letter and the current letter are both vowels
then there will also be a gap created using two pipes, one below
another.

Man like symbol will be created for the highest peak.

Sample Input and Output: Sample
1, Sample
2, Sample
3

Here is what I have done
I have tried to collect the word as input and converted it to the respective numbers i.e a=1, b=2,..z=26.

alpha=["a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z"]
usr_input=str(input("Enter the strings: "))
usr_input=usr_input.lower()
for l in usr_input:
    if l in alpha:
        num=(alpha.index(l)+1)
        data.append(num)

And then for the purpose of check are the given numbers are vowels or not I have used a if condition

for i in data:
    if i==1 or i==5 or i==9 or i==15 or i==21:
        print("\\"*i)
    else:
       print("/"*i)

And then I got stuck I can't able to print the result as in graph format and then I cannot able to fit the pipe(|) symbol when If the previous letter and the current letter are consonants and then printing the man symbol at the highest peak

Here is the code to print the man, but I don't know how to place it in the highest peak

print(' \u25cb',"\n/|\\\n< >")

The whole progress I did after posting it to the SO

    #Getting words from users and coverting it to numbers
data=[]
alpha=["a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z"]
usr_input=str(input("Enter the strings: "))
usr_input=usr_input.lower()
for l in usr_input:
    if l in alpha:
        num=(alpha.index(l)+1)
        data.append(num)
vow=[1, 5, 9, 15, 21]
#operations
final=[]
max_column=sum(data)
for i in range(max_column):
    final.append([" "] * (max_column*2))
    final.append([" "] * (max_column*2))

def graph(data):
    x,y=0,0
    tmp=[]
    for i,j in enumerate(data):
        tmp.append(j)

        if j not in vow:
            for _ in range(j):
                final[x][y]="\\"
                x+=1
                y+=1

        else:

            for _ in range(j):
                x-=1
                final[x][y]="/"
                y+=1

graph(data)

for res in final:
    print("".join(res))

Output: image


问:
selenium.common.exceptions.WebDriverException: Message: unknown error: net::ERR_NAME_NOT_RESOLVED - Python
I'm trying to automate a few tests that my team runs. While not a big issue, I would like to handle an exception a little more gracefully.

I'm attempting to resolve a page that isn't resolvable and I would like to catch the exception and either return with a logging.critical or just a print statement.

The Exception Message:

```<code>selenium.common.exceptions.WebDriverException: Message: unknown error: net::ERR_NAME_NOT_RESOLVED
</code>```

The Code:

```<code>from selenium import webdriver # GRANTS ACCESS TO THE WEBDRIVERS
from selenium.webdriver.chrome.options import Options # ALLOWS CHROME OPTIONS
from selenium.webdriver.common.keys import Keys # GIVES PYTHON THE ABILITY TO SEND KEY STROKES
from selenium.webdriver.common.by import By # ALLOWS PYTHON TO SEARCH FOR ELEMENTS WITHIN THE DOCUMENT
from selenium.webdriver.support.wait import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.common.exceptions import WebDriverException
from selenium.common.exceptions import TimeoutException
from selenium.common.exceptions import UnexpectedAlertPresentException
import logging

import time
import pdb
import os
from dotenv import load_dotenv
load_dotenv()

def gui_login():
  url = "https://THISPAGEDOESNTEXIST.COM:5641/" # SANITIZED THE URL FOR THIS POST.
  print("----------")
  print("BEGIN RUN FOR GUI LOGIN")
  print("----------")
  options = webdriver.ChromeOptions()
  options.add_argument('ignore-certificate-errors')

  driver = webdriver.Chrome(options=options)

  try:
    driver.get(url)
    time.sleep(5)
    # uname = WebDriverWait(driver,15).until(EC.presence_of_element_located((By.XPATH, "/html/body/div[1]/div[3]/div[2]/div/div/div/div/div/form/div[1]/div[2]/div/div/input")))
    # uname.clear()
    # uname.send_keys(os.environ["IDENTITY"])
    # uname.send_keys(Keys.RETURN)
    # passw = WebDriverWait(driver,15).until(EC.presence_of_element_located((By.XPATH, "/html/body/div[1]/div[3]/div[2]/div/div/div/div/div/form/div[2]/div[2]/div/div/input")))
    # passw.clear()
    # passw.send_keys(os.environ["PASSWORD"])
    # passw.send_keys(Keys.RETURN)
    # time.sleep(10)

    # WebElementError = WebDriverWait(driver,3).until(EC.presence_of_element_located((By.XPATH, '//*[@id="main-message"]/p')))

########## TRY LOOKING FOR WEBELEMENT IN 404 PAGE ###########

    # if WebElementError:
    #   print("SANITIZED is not resolvable.")

#### TRY LOOKING FOR THE WEBDRIVER EXCEPTION

  except WebDriverException:
    print("Page Down")

  finally:
    #driver.quit()
    print()
</code>```

The Full Error:

```<code>self = <selenium.webdriver.remote.errorhandler.ErrorHandler object at 0x106098210>
response = {'status': 500, 'value': '{"value":{"error":"unknown error","message":"unknown error: net::ERR_NAME_NOT_RESOLVED\\n  (...ff80df254f4 _pthread_start + 125\\n27  libsystem_pthread.dylib             0x00007ff80df2100f thread_start + 15\\n"}}'}

def check_response(self, response: Dict[str, Any]) -> None:
    """
    Checks that a JSON response from the WebDriver does not have an error.

    :Args:
     - response - The JSON response from the WebDriver server as a dictionary
       object.

    :Raises: If the response contains an error message.
    """
    status = response.get("status", None)
    if not status or status == ErrorCode.SUCCESS:
        return
    value = None
    message = response.get("message", "")
    screen: str = response.get("screen", "")
    stacktrace = None
    if isinstance(status, int):
        value_json = response.get("value", None)
        if value_json and isinstance(value_json, str):
            import json

            try:
                value = json.loads(value_json)
                if len(value.keys()) == 1:
                    value = value["value"]
                status = value.get("error", None)
                if not status:
                    status = value.get("status", ErrorCode.UNKNOWN_ERROR)
                    message = value.get("value") or value.get("message")
                    if not isinstance(message, str):
                        value = message
                        message = message.get("message")
                else:
                    message = value.get("message", None)
            except ValueError:
                pass

    exception_class: Type[WebDriverException]
    if status in ErrorCode.NO_SUCH_ELEMENT:
        exception_class = NoSuchElementException
    elif status in ErrorCode.NO_SUCH_FRAME:
        exception_class = NoSuchFrameException
    elif status in ErrorCode.HOST_UNABLE_TO_RESOLVE:
        exception_class = HostUnableToResolveException
    elif status in ErrorCode.NO_SUCH_SHADOW_ROOT:
        exception_class = NoSuchShadowRootException
    elif status in ErrorCode.NO_SUCH_WINDOW:
        exception_class = NoSuchWindowException
    elif status in ErrorCode.STALE_ELEMENT_REFERENCE:
        exception_class = StaleElementReferenceException
    elif status in ErrorCode.ELEMENT_NOT_VISIBLE:
        exception_class = ElementNotVisibleException
    elif status in ErrorCode.INVALID_ELEMENT_STATE:
        exception_class = InvalidElementStateException
    elif (
        status in ErrorCode.INVALID_SELECTOR
        or status in ErrorCode.INVALID_XPATH_SELECTOR
        or status in ErrorCode.INVALID_XPATH_SELECTOR_RETURN_TYPER
    ):
        exception_class = InvalidSelectorException
    elif status in ErrorCode.ELEMENT_IS_NOT_SELECTABLE:
        exception_class = ElementNotSelectableException
    elif status in ErrorCode.ELEMENT_NOT_INTERACTABLE:
        exception_class = ElementNotInteractableException
    elif status in ErrorCode.INVALID_COOKIE_DOMAIN:
        exception_class = InvalidCookieDomainException
    elif status in ErrorCode.UNABLE_TO_SET_COOKIE:
        exception_class = UnableToSetCookieException
    elif status in ErrorCode.TIMEOUT:
        exception_class = TimeoutException
    elif status in ErrorCode.SCRIPT_TIMEOUT:
        exception_class = TimeoutException
    elif status in ErrorCode.UNKNOWN_ERROR:
        exception_class = WebDriverException
    elif status in ErrorCode.UNEXPECTED_ALERT_OPEN:
        exception_class = UnexpectedAlertPresentException
    elif status in ErrorCode.NO_ALERT_OPEN:
        exception_class = NoAlertPresentException
    elif status in ErrorCode.IME_NOT_AVAILABLE:
        exception_class = ImeNotAvailableException
    elif status in ErrorCode.IME_ENGINE_ACTIVATION_FAILED:
        exception_class = ImeActivationFailedException
    elif status in ErrorCode.MOVE_TARGET_OUT_OF_BOUNDS:
        exception_class = MoveTargetOutOfBoundsException
    elif status in ErrorCode.JAVASCRIPT_ERROR:
        exception_class = JavascriptException
    elif status in ErrorCode.SESSION_NOT_CREATED:
        exception_class = SessionNotCreatedException
    elif status in ErrorCode.INVALID_ARGUMENT:
        exception_class = InvalidArgumentException
    elif status in ErrorCode.NO_SUCH_COOKIE:
        exception_class = NoSuchCookieException
    elif status in ErrorCode.UNABLE_TO_CAPTURE_SCREEN:
        exception_class = ScreenshotException
    elif status in ErrorCode.ELEMENT_CLICK_INTERCEPTED:
        exception_class = ElementClickInterceptedException
    elif status in ErrorCode.INSECURE_CERTIFICATE:
        exception_class = InsecureCertificateException
    elif status in ErrorCode.INVALID_COORDINATES:
        exception_class = InvalidCoordinatesException
    elif status in ErrorCode.INVALID_SESSION_ID:
        exception_class = InvalidSessionIdException
    elif status in ErrorCode.UNKNOWN_METHOD:
        exception_class = UnknownMethodException
    else:
        exception_class = WebDriverException
    if not value:
        value = response["value"]
    if isinstance(value, str):
        raise exception_class(value)
    if message == "" and "message" in value:
        message = value["message"]

    screen = None  # type: ignore[assignment]
    if "screen" in value:
        screen = value["screen"]

    stacktrace = None
    st_value = value.get("stackTrace") or value.get("stacktrace")
    if st_value:
        if isinstance(st_value, str):
            stacktrace = st_value.split("\n")
        else:
            stacktrace = []
            try:
                for frame in st_value:
                    line = frame.get("lineNumber", "")
                    file = frame.get("fileName", "<anonymous>")
                    if line:
                        file = f"{file}:{line}"
                    meth = frame.get("methodName", "<anonymous>")
                    if "className" in frame:
                        meth = "{}.{}".format(frame["className"], meth)
                    msg = "    at %s (%s)"
                    msg = msg % (meth, file)
                    stacktrace.append(msg)
            except TypeError:
                pass
    if exception_class == UnexpectedAlertPresentException:
        alert_text = None
        if "data" in value:
            alert_text = value["data"].get("text")
        elif "alert" in value:
            alert_text = value["alert"].get("text")
        raise exception_class(alert_text,message, screen, stacktrace)  # type: ignore[call-arg]  # mypy is not smart enough here
</code>```

```<code>  raise exception_class(message)
</code>```

E       selenium.common.exceptions.WebDriverException: Message: unknown error: net::ERR_NAME_NOT_RESOLVED
E         (Session info: chrome=107.0.5304.110)

/Library/Frameworks/Python.framework/Versions/3.11/lib/python3.11/site-packages/selenium/webdriver/remote/errorhandler.py:252: WebDriverException
------------------------------------------------------------------------------------------ Captured stdout call -----------------------------------

I have also tried to grab the error and parse it, as well as look for the "unavailable" message from the html page, but so far no luck.

Any recommendations would be wonderful.

Body:
I'm trying to automate a few tests that my team runs. While not a big issue, I would like to handle an exception a little more gracefully.

I'm attempting to resolve a page that isn't resolvable and I would like to catch the exception and either return with a logging.critical or just a print statement.

The Exception Message:

selenium.common.exceptions.WebDriverException: Message: unknown error: net::ERR_NAME_NOT_RESOLVED

The Code:

from selenium import webdriver # GRANTS ACCESS TO THE WEBDRIVERS
from selenium.webdriver.chrome.options import Options # ALLOWS CHROME OPTIONS
from selenium.webdriver.common.keys import Keys # GIVES PYTHON THE ABILITY TO SEND KEY STROKES
from selenium.webdriver.common.by import By # ALLOWS PYTHON TO SEARCH FOR ELEMENTS WITHIN THE DOCUMENT
from selenium.webdriver.support.wait import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.common.exceptions import WebDriverException
from selenium.common.exceptions import TimeoutException
from selenium.common.exceptions import UnexpectedAlertPresentException
import logging

import time
import pdb
import os
from dotenv import load_dotenv
load_dotenv()

def gui_login():
  url = "https://THISPAGEDOESNTEXIST.COM:5641/" # SANITIZED THE URL FOR THIS POST.
  print("----------")
  print("BEGIN RUN FOR GUI LOGIN")
  print("----------")
  options = webdriver.ChromeOptions()
  options.add_argument('ignore-certificate-errors')

  driver = webdriver.Chrome(options=options)

  try:
    driver.get(url)
    time.sleep(5)
    # uname = WebDriverWait(driver,15).until(EC.presence_of_element_located((By.XPATH, "/html/body/div[1]/div[3]/div[2]/div/div/div/div/div/form/div[1]/div[2]/div/div/input")))
    # uname.clear()
    # uname.send_keys(os.environ["IDENTITY"])
    # uname.send_keys(Keys.RETURN)
    # passw = WebDriverWait(driver,15).until(EC.presence_of_element_located((By.XPATH, "/html/body/div[1]/div[3]/div[2]/div/div/div/div/div/form/div[2]/div[2]/div/div/input")))
    # passw.clear()
    # passw.send_keys(os.environ["PASSWORD"])
    # passw.send_keys(Keys.RETURN)
    # time.sleep(10)

    # WebElementError = WebDriverWait(driver,3).until(EC.presence_of_element_located((By.XPATH, '//*[@id="main-message"]/p')))

########## TRY LOOKING FOR WEBELEMENT IN 404 PAGE ###########

    # if WebElementError:
    #   print("SANITIZED is not resolvable.")

#### TRY LOOKING FOR THE WEBDRIVER EXCEPTION

  except WebDriverException:
    print("Page Down")

  finally:
    #driver.quit()
    print()

The Full Error:

self = <selenium.webdriver.remote.errorhandler.ErrorHandler object at 0x106098210>
response = {'status': 500, 'value': '{"value":{"error":"unknown error","message":"unknown error: net::ERR_NAME_NOT_RESOLVED\\n  (...ff80df254f4 _pthread_start + 125\\n27  libsystem_pthread.dylib             0x00007ff80df2100f thread_start + 15\\n"}}'}

def check_response(self, response: Dict[str, Any]) -> None:
    """
    Checks that a JSON response from the WebDriver does not have an error.

    :Args:
     - response - The JSON response from the WebDriver server as a dictionary
       object.

    :Raises: If the response contains an error message.
    """
    status = response.get("status", None)
    if not status or status == ErrorCode.SUCCESS:
        return
    value = None
    message = response.get("message", "")
    screen: str = response.get("screen", "")
    stacktrace = None
    if isinstance(status, int):
        value_json = response.get("value", None)
        if value_json and isinstance(value_json, str):
            import json

            try:
                value = json.loads(value_json)
                if len(value.keys()) == 1:
                    value = value["value"]
                status = value.get("error", None)
                if not status:
                    status = value.get("status", ErrorCode.UNKNOWN_ERROR)
                    message = value.get("value") or value.get("message")
                    if not isinstance(message, str):
                        value = message
                        message = message.get("message")
                else:
                    message = value.get("message", None)
            except ValueError:
                pass

    exception_class: Type[WebDriverException]
    if status in ErrorCode.NO_SUCH_ELEMENT:
        exception_class = NoSuchElementException
    elif status in ErrorCode.NO_SUCH_FRAME:
        exception_class = NoSuchFrameException
    elif status in ErrorCode.HOST_UNABLE_TO_RESOLVE:
        exception_class = HostUnableToResolveException
    elif status in ErrorCode.NO_SUCH_SHADOW_ROOT:
        exception_class = NoSuchShadowRootException
    elif status in ErrorCode.NO_SUCH_WINDOW:
        exception_class = NoSuchWindowException
    elif status in ErrorCode.STALE_ELEMENT_REFERENCE:
        exception_class = StaleElementReferenceException
    elif status in ErrorCode.ELEMENT_NOT_VISIBLE:
        exception_class = ElementNotVisibleException
    elif status in ErrorCode.INVALID_ELEMENT_STATE:
        exception_class = InvalidElementStateException
    elif (
        status in ErrorCode.INVALID_SELECTOR
        or status in ErrorCode.INVALID_XPATH_SELECTOR
        or status in ErrorCode.INVALID_XPATH_SELECTOR_RETURN_TYPER
    ):
        exception_class = InvalidSelectorException
    elif status in ErrorCode.ELEMENT_IS_NOT_SELECTABLE:
        exception_class = ElementNotSelectableException
    elif status in ErrorCode.ELEMENT_NOT_INTERACTABLE:
        exception_class = ElementNotInteractableException
    elif status in ErrorCode.INVALID_COOKIE_DOMAIN:
        exception_class = InvalidCookieDomainException
    elif status in ErrorCode.UNABLE_TO_SET_COOKIE:
        exception_class = UnableToSetCookieException
    elif status in ErrorCode.TIMEOUT:
        exception_class = TimeoutException
    elif status in ErrorCode.SCRIPT_TIMEOUT:
        exception_class = TimeoutException
    elif status in ErrorCode.UNKNOWN_ERROR:
        exception_class = WebDriverException
    elif status in ErrorCode.UNEXPECTED_ALERT_OPEN:
        exception_class = UnexpectedAlertPresentException
    elif status in ErrorCode.NO_ALERT_OPEN:
        exception_class = NoAlertPresentException
    elif status in ErrorCode.IME_NOT_AVAILABLE:
        exception_class = ImeNotAvailableException
    elif status in ErrorCode.IME_ENGINE_ACTIVATION_FAILED:
        exception_class = ImeActivationFailedException
    elif status in ErrorCode.MOVE_TARGET_OUT_OF_BOUNDS:
        exception_class = MoveTargetOutOfBoundsException
    elif status in ErrorCode.JAVASCRIPT_ERROR:
        exception_class = JavascriptException
    elif status in ErrorCode.SESSION_NOT_CREATED:
        exception_class = SessionNotCreatedException
    elif status in ErrorCode.INVALID_ARGUMENT:
        exception_class = InvalidArgumentException
    elif status in ErrorCode.NO_SUCH_COOKIE:
        exception_class = NoSuchCookieException
    elif status in ErrorCode.UNABLE_TO_CAPTURE_SCREEN:
        exception_class = ScreenshotException
    elif status in ErrorCode.ELEMENT_CLICK_INTERCEPTED:
        exception_class = ElementClickInterceptedException
    elif status in ErrorCode.INSECURE_CERTIFICATE:
        exception_class = InsecureCertificateException
    elif status in ErrorCode.INVALID_COORDINATES:
        exception_class = InvalidCoordinatesException
    elif status in ErrorCode.INVALID_SESSION_ID:
        exception_class = InvalidSessionIdException
    elif status in ErrorCode.UNKNOWN_METHOD:
        exception_class = UnknownMethodException
    else:
        exception_class = WebDriverException
    if not value:
        value = response["value"]
    if isinstance(value, str):
        raise exception_class(value)
    if message == "" and "message" in value:
        message = value["message"]

    screen = None  # type: ignore[assignment]
    if "screen" in value:
        screen = value["screen"]

    stacktrace = None
    st_value = value.get("stackTrace") or value.get("stacktrace")
    if st_value:
        if isinstance(st_value, str):
            stacktrace = st_value.split("\n")
        else:
            stacktrace = []
            try:
                for frame in st_value:
                    line = frame.get("lineNumber", "")
                    file = frame.get("fileName", "<anonymous>")
                    if line:
                        file = f"{file}:{line}"
                    meth = frame.get("methodName", "<anonymous>")
                    if "className" in frame:
                        meth = "{}.{}".format(frame["className"], meth)
                    msg = "    at %s (%s)"
                    msg = msg % (meth, file)
                    stacktrace.append(msg)
            except TypeError:
                pass
    if exception_class == UnexpectedAlertPresentException:
        alert_text = None
        if "data" in value:
            alert_text = value["data"].get("text")
        elif "alert" in value:
            alert_text = value["alert"].get("text")
        raise exception_class(alert_text,message, screen, stacktrace)  # type: ignore[call-arg]  # mypy is not smart enough here

  raise exception_class(message)

E       selenium.common.exceptions.WebDriverException: Message: unknown error: net::ERR_NAME_NOT_RESOLVED
E         (Session info: chrome=107.0.5304.110)

/Library/Frameworks/Python.framework/Versions/3.11/lib/python3.11/site-packages/selenium/webdriver/remote/errorhandler.py:252: WebDriverException
------------------------------------------------------------------------------------------ Captured stdout call -----------------------------------

I have also tried to grab the error and parse it, as well as look for the "unavailable" message from the html page, but so far no luck.

Any recommendations would be wonderful.


问:
Connect to iSeries database from docker windows container
How can I connect to iSeries database from a windows container? It requires client access to be installed on machine, obviously it's not installed on the base image I'm using (mcr.microsoft.com/dotnet/framework/aspnet:4.6.2-20221108-windowsservercore-ltsc2016).
Is there a way to achieve that without installation? Maybe copying some dll's would help?

I tried to copy dll's as mentioned in this answer Embedd cwbdc.dll from IBM i Client Access manually to console application but I could not find 320 dlls. And when copying for example 'cwbdc.dll' into project's bin folder I get BadImageFormatException


问:
Trying to change the organization in Adobe Analytics Connector for Power BI
I'm using Power BI for Desktop, trying to learn how to connect it with Adobe Analytics. So far it seems I can only connect to Adobe Analytics through the connector that Power BI has.

Screenshot of said connector

However, the first time I logged in, I chose a sandbox organization.

Now all my subsequent connections automatically default to that org. Even after I clear the Power BI permissions.

Is there any way to change the organization?


问:
Save Form submissions to google sheets
I am testing a simple form website that takes certain responses and does a typing speed test and stores the results to a google sheets link

here's the html code

`

```<code>!DOCTYPE html>
<html>
<head>
<title>Volunteer Recruitment Form</title>
<style>
    body {
      font-family: Arial, sans-serif;
      background-color: #f1f1f1;
    }

    h1 {
      text-align: center;
      color: #333;
    }

    form {
      max-width: 500px;
      margin: auto;
      padding: 20px;
      background-color: #fff;
      border: 1px solid #ddd;
    }

    p {
      margin-top: 10px;
    }

    input[type=text] {
      width: 100%;
      padding: 12px;
      box-sizing: border-box;
    }

    input[type=submit] {
      background-color: #4CAF50;
      color: white;
      padding: 12px 20px;
      border: none;
      cursor: pointer;
    }

    input[type=submit]:hover {
      background-color: #45a049;
    }
  </style>

</head>
<body>
<h1>Volunteer Recruitment Form</h1>

<img src="logo.png" alt="Logo" width="200" height="200">
<form onsubmit="return !!(saveFormResponses() & measureTypingSpeed());">
<p>1. Name: <input type="text" name="name"></p>
<p>2. Address: <input type="text" name="address"></p>
<p>3. Class: <input type="text" name="class"></p>
<p>4. Section: <input type="text" name="section"></p>
<p>5. Typing Speed Test:
<script>
    var sentences = [
      "The quick brown fox jumps over the lazy dog.",
      "She sells seashells by the seashore.",
      "The rain in Spain stays mainly in the plain.",
      "I saw Susie sitting in a shoe shine shop.",
      "How can a clam cram in a clean cream can?",
      "A proper copper coffee pot."
    ];

    var randomSentences = [];
    for (var i = 0; i < 6; i++) {
      // Generate a random number between 0 and the length of the sentences array
      var randomIndex = Math.floor(Math.random() * sentences.length);

      randomSentences.push(sentences[randomIndex]);
    }

    document.write(randomSentences.join("<br>"));
</script>
<input type="text" name="typing_test"></p>

<script>
    function measureTypingSpeed() {

  var inputElement = document.querySelector("input[name=typing_test]");

  // Get the text of the sentences the user needs to type
  var sentences = "The quick brown fox jumps over the lazy dog. She sells seashells by the seashore. The rain in Spain stays mainly in the plain. I saw Susie sitting in a shoe shine shop. How can a clam cram in a clean cream can? A proper copper coffee pot.";

  var startTime = Date.now();
  var endTime = Date.now();
  while (inputElement.value != sentences) {
    endTime = Date.now();
  }

  var elapsedTime = endTime - startTime;
  var words = sentences.split(" ").length;
  var typingSpeed = Math.round(words / (elapsedTime / 1000) * 60);

  alert("Your typing speed is: " + typingSpeed + " words per minute");
}

</script>

<input type="submit" value="Submit">
</form>

</body>
</html>

</code>```

`
and the code for the google sheets saving is

`

```<code>function saveFormResponses() {

  var formElement = document.querySelector("form");

  var formResponses = {};

    for (var i = 0; i < formElement.elements.length; i++) {
    var inputElement = formElement.elements[i];

    if (inputElement.type == "text") {
      formResponses[inputElement.name] = inputElement.value;
    }
  }

  const SPREADSHEET_URL = "https://docs.google.com/spreadsheets/d/1zVvU0_VzrjmcOl33E4BOKhlsGt26cQQVnpV8R4AJvSw/edit?usp=sharing";

  const sheets = GoogleSheetsAPI.initialize();

  // Append the form responses to the bottom of the sheet
  sheets.append(SPREADSHEET_URL, formResponses);
}

</code>```

`

Please help me solve the problem I am new to this and just learning through github hosting at the moment

I tried the given code but that doesnt seem to work

Title: Save Form submissions to google sheets

Body:
I am testing a simple form website that takes certain responses and does a typing speed test and stores the results to a google sheets link

here's the html code

`

!DOCTYPE html>

<title>Volunteer Recruitment Form</title>

Volunteer Recruitment Form

<form onsubmit="return !!(saveFormResponses() & measureTypingSpeed());">

1. Name: <input type="text" name="name">

2. Address: <input type="text" name="address">

3. Class: <input type="text" name="class">

4. Section: <input type="text" name="section">

5. Typing Speed Test:

<input type="text" name="typing_test">

<input type="submit" value="Submit">
</form>

`
and the code for the google sheets saving is

`

function saveFormResponses() {

  var formElement = document.querySelector("form");

  var formResponses = {};

    for (var i = 0; i < formElement.elements.length; i++) {
    var inputElement = formElement.elements[i];

    if (inputElement.type == "text") {
      formResponses[inputElement.name] = inputElement.value;
    }
  }

  const SPREADSHEET_URL = "https://docs.google.com/spreadsheets/d/1zVvU0_VzrjmcOl33E4BOKhlsGt26cQQVnpV8R4AJvSw/edit?usp=sharing";

  const sheets = GoogleSheetsAPI.initialize();

  // Append the form responses to the bottom of the sheet
  sheets.append(SPREADSHEET_URL, formResponses);
}

`

Please help me solve the problem I am new to this and just learning through github hosting at the moment

I tried the given code but that doesnt seem to work


问:
addPostFrameCallback vs scheduleFrameCallback
So, I was wondering, when to use WidgetsBinding.instance.addPostFrameCallback and WidgetsBinding.instance.scheduleFrameCallback for setState, as according to the documentation, the first one doesn't initiate a frame on its own, while if we asynchronously call setState then it might get called during the build of another widget, which can cause not to update the other widget, so for it, we add it as a "post frame" callback, but if it is called not during a build, then it will not initiate the next frame on its own, i.e we cannot always wrap async setState calls with it, as there is a good chance it might be called during not a build, that's when I found scheduleFrameCallback, and according to its documentation, I think it schedules the next frame and adds its as a callback to it, i.e it also initiates a frame. So is it always better to call setState inside it, or is it something else?


问:
How to pass system ENV vars to php in apache
I am trying to get an apache/php application to run in a container on ECS.  The app expects an ENV var named USER_DBHOSTNAME.  I have ECS configured to pass this into the container from an AWS Secret and make it available as an ENV var.

I can login to the running container and verify that the variable is being set in the container

```<code>$> echo $USER_DBHOSTNAME
$> xxxx.xxxxxx.xxxx #redacted for security
</code>```

However the php code is not seeing the variable

print(getenv('USER_DBHOSTNAME');
```
<p>outputs nothing</p>
<p>I know I need to add the variable to <code>/etc/apache2/envvars</code> to make this show up.  I can't figure out how to set an apache env var to be equal to the system env var.  I can set the var to a hardcoded value and it shows up</p>
```export USER_DBHOSTNAME=foobar
```
<p>but when I try something like</p>
```export USER_DBHOSTNAME=$(echo $USER_DBHOSTNAME)
```

the var in PHP is empty.  The variable exists but it has an empty value

Body:
I am trying to get an apache/php application to run in a container on ECS.  The app expects an ENV var named USER_DBHOSTNAME.  I have ECS configured to pass this into the container from an AWS Secret and make it available as an ENV var.

I can login to the running container and verify that the variable is being set in the container

$> echo $USER_DBHOSTNAME
$> xxxx.xxxxxx.xxxx #redacted for security

However the php code is not seeing the variable

print(getenv('USER_DBHOSTNAME');

outputs nothing

I know I need to add the variable to /etc/apache2/envvars to make this show up.  I can't figure out how to set an apache env var to be equal to the system env var.  I can set the var to a hardcoded value and it shows up

export USER_DBHOSTNAME=foobar

but when I try something like

export USER_DBHOSTNAME=$(echo $USER_DBHOSTNAME)

the var in PHP is empty.  The variable exists but it has an empty value


问:
Extracting 1 file from vmdk archive
so I have a .vmdk archive that is created by Memu (android emulator) , and I need to extract one file from it using command line.

I am able to do it using 7zip GUI drag and drop, but from the command line it does not work. Open for any other options besides 7zip!

Thank you!

Below is the output using the command-
7z.exe l D:\vms\MEmu\MEmu96-2022102700023FFF-disk2.vmdk

C:\Program Files\7-Zip>7z.exe l
D:\vms\MEmu\MEmu96-2022102700023FFF-disk2.vmdk

7-Zip 19.00 (x64) : Copyright (c) 1999-2018 Igor Pavlov : 2019-02-21

Scanning the drive for archives: 1 file, 3719291904 bytes (3547 MiB)

Listing archive: D:\vms\MEmu\MEmu96-2022102700023FFF-disk2.vmdk

-- Path = D:\vms\MEmu\MEmu96-2022102700023FFF-disk2.vmdk Open WARNING: Can not open the file as [VMDK] archive Type = VHD Physical Size =
3719291904 Offset = 0 Created = 2022-05-28 03:49:29 Cluster Size =
2097152 Method = Dynamic Total Physical Size = 3719291904 Creator
Application = vbox 6.1 Host OS = Windows Saved State = - ID =
19112220CCCCCCCCCCCC000000000000
---- Size = 68826850816 Packed Size = 3718250496 Created = 2022-05-28 03:49:29
-- Path = MEmu96-2022102700023FFF-disk2.mbr Type = MBR Physical Size = 68826850816

Date      Time    Attr         Size   Compressed  Name

```<code>                .....      1048576      1048576  0.img
                .....      1048576      1048576  1.img
                .....  68823705088  68823705088  2.img
</code>```

```<code>                       68825802240  68825802240  3 files
</code>```

Warnings: 1

Title: Extracting 1 file from vmdk archive

Body:
so I have a .vmdk archive that is created by Memu (android emulator) , and I need to extract one file from it using command line.

I am able to do it using 7zip GUI drag and drop, but from the command line it does not work. Open for any other options besides 7zip!

Thank you!

Below is the output using the command-
7z.exe l D:\vms\MEmu\MEmu96-2022102700023FFF-disk2.vmdk

C:\Program Files\7-Zip>7z.exe l
D:\vms\MEmu\MEmu96-2022102700023FFF-disk2.vmdk

7-Zip 19.00 (x64) : Copyright (c) 1999-2018 Igor Pavlov : 2019-02-21

Scanning the drive for archives: 1 file, 3719291904 bytes (3547 MiB)

Listing archive: D:\vms\MEmu\MEmu96-2022102700023FFF-disk2.vmdk

-- Path = D:\vms\MEmu\MEmu96-2022102700023FFF-disk2.vmdk Open WARNING: Can not open the file as [VMDK] archive Type = VHD Physical Size =
3719291904 Offset = 0 Created = 2022-05-28 03:49:29 Cluster Size =
2097152 Method = Dynamic Total Physical Size = 3719291904 Creator
Application = vbox 6.1 Host OS = Windows Saved State = - ID =
19112220CCCCCCCCCCCC000000000000
---- Size = 68826850816 Packed Size = 3718250496 Created = 2022-05-28 03:49:29
-- Path = MEmu96-2022102700023FFF-disk2.mbr Type = MBR Physical Size = 68826850816

Date      Time    Attr         Size   Compressed  Name

                .....      1048576      1048576  0.img
                .....      1048576      1048576  1.img
                .....  68823705088  68823705088  2.img

                       68825802240  68825802240  3 files

Warnings: 1


问:
How to connect Selenium and AdBlock?
`

```<code>public class CucumberHooks {
    public static void main(String[] args) {

    }
    protected static WebDriver driver;

    @Before
    public void setup() throws IOException {
        ChromeOptions options = new ChromeOptions();
        options.addExtensions(new File("extension_5_3_2_0.crx"));
        DesiredCapabilities capabilities = new DesiredCapabilities();
        capabilities.setCapability(ChromeOptions.CAPABILITY, options);
        String browser = ReadPropertyFileSingleton.getInstance().getProp("browser");
           driver = Util.setEnvironmentAndGetDriver(browser);
            assert driver != null;
            driver.manage().window().maximize();
            driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);

    }
    public static WebDriver getDriver() {
        return driver;
    }

    @After
    public void close() {
        driver.quit();
    }}
</code>```

The code where I added adblock extensions via crx file
When I run tests through a feature file, a regular browser without a blocker is launched
the browser is also launched already with a blocker, but it does not see the steps
what could be the problem and is it possible to use adblock this way?

Title: How to connect Selenium and AdBlock?

Body:
`

public class CucumberHooks {
    public static void main(String[] args) {

    }
    protected static WebDriver driver;

    @Before
    public void setup() throws IOException {
        ChromeOptions options = new ChromeOptions();
        options.addExtensions(new File("extension_5_3_2_0.crx"));
        DesiredCapabilities capabilities = new DesiredCapabilities();
        capabilities.setCapability(ChromeOptions.CAPABILITY, options);
        String browser = ReadPropertyFileSingleton.getInstance().getProp("browser");
           driver = Util.setEnvironmentAndGetDriver(browser);
            assert driver != null;
            driver.manage().window().maximize();
            driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);

    }
    public static WebDriver getDriver() {
        return driver;
    }

    @After
    public void close() {
        driver.quit();
    }}

The code where I added adblock extensions via crx file
When I run tests through a feature file, a regular browser without a blocker is launched
the browser is also launched already with a blocker, but it does not see the steps
what could be the problem and is it possible to use adblock this way?


问:
How to make spring-boot-maven-plugin use alpine linux
Running mvn spring-boot:build-image creates a fully functional image based on Ubuntu LTS.

How to configure spring-boot-maven-plugin to use Alpine Linux?


问:
Antd Segmented: Set tabindex=-1 to the internal Input component
I'm using the Segmented component by Ant Design. My application has some component like this:

...

import EmployeeCard from './EmployeeCard';
import ContractorCard from './ContractorCard';

function MyComponent() {

  const [cardType, setCardType] = useState('Employee');

  ...

  function changeCard(value) {
    setCardType(value);
  }

  return (

    ...

    <Segmented
      options={['Employee', 'Contractor']}
      onChange={changeCard)
      value={cardType}
      tabIndex={-1}
    />
    {cardType === 'Employee'
      ? <EmployeeCard />
      : <ContractorCard />
    }

    ...
  );
}```

The EmployeeCard and ContractorCard have some input components in them that I want to be part of the overall tab flow on the page. However, I don't want the Segmented buttons themselves to be part of it. I set tabIndex={-1} on the Segmented component in order to take it out of the tab-flow, but apparently, internally, that component includes an Input component, which still has the default tabIndex={0}. I cannot figure out how to reach that component in order to set its tab index to -1.

Body:
I'm using the Segmented component by Ant Design. My application has some component like this:

...

import EmployeeCard from './EmployeeCard';
import ContractorCard from './ContractorCard';

function MyComponent() {

  const [cardType, setCardType] = useState('Employee');

  ...

  function changeCard(value) {
    setCardType(value);
  }

  return (

    ...

    <Segmented
      options={['Employee', 'Contractor']}
      onChange={changeCard)
      value={cardType}
      tabIndex={-1}
    />
    {cardType === 'Employee'
      ? <EmployeeCard />
      : <ContractorCard />
    }

    ...
  );
}

The EmployeeCard and ContractorCard have some input components in them that I want to be part of the overall tab flow on the page. However, I don't want the Segmented buttons themselves to be part of it. I set tabIndex={-1} on the Segmented component in order to take it out of the tab-flow, but apparently, internally, that component includes an Input component, which still has the default tabIndex={0}. I cannot figure out how to reach that component in order to set its tab index to -1.


问:
How can I config my database connection on TypeORM?
I used to use this config, but connect and getConnectionManager are deprecated.

```<code>import { getConnectionManager } from "typeorm";

if (process.env.NODE_ENV === 'production' && process.env.DATABASE_URL.indexOf("sslmode=require") === -1) {
  process.env.DATABASE_URL += "?sslmode=require";
}

export default async function connect () {
  const connectionManager = await getConnectionManager();
  const connection = connectionManager.create({
    name: "default",
    type: "postgres",
    url: process.env.DATABASE_URL,
    entities: [`${process.env.NODE_ENV === 'production' ? 'dist' : 'src'}/entities/*.*`],
    ssl: process.env.NODE_ENV === 'production'
  });
  await connection.connect();
  return connection;
}
</code>```

I have tried to use this config, but when I try to made a request receive the error: DataSource is not set for this entity.

```<code>import { DataSource } from "typeorm";

if (process.env.NODE_ENV === 'production' && process.env.DATABASE_URL.indexOf("sslmode=require") === -1) {
    process.env.DATABASE_URL += "?sslmode=require";
}

export default async function connect () {
    const dataSource = new DataSource({
        name: "default",
        type: "postgres",
        url: process.env.DATABASE_URL,
        entities: [`${process.env.NODE_ENV === 'production' ? 'dist' : 'src'}/entities/*.*`],
        ssl: process.env.NODE_ENV === 'production'
    });
    const connection = await dataSource.initialize();
    return connection;
}
</code>```

Body:
I used to use this config, but connect and getConnectionManager are deprecated.

import { getConnectionManager } from "typeorm";

if (process.env.NODE_ENV === 'production' && process.env.DATABASE_URL.indexOf("sslmode=require") === -1) {
  process.env.DATABASE_URL += "?sslmode=require";
}

export default async function connect () {
  const connectionManager = await getConnectionManager();
  const connection = connectionManager.create({
    name: "default",
    type: "postgres",
    url: process.env.DATABASE_URL,
    entities: [`${process.env.NODE_ENV === 'production' ? 'dist' : 'src'}/entities/*.*`],
    ssl: process.env.NODE_ENV === 'production'
  });
  await connection.connect();
  return connection;
}

I have tried to use this config, but when I try to made a request receive the error: DataSource is not set for this entity.

import { DataSource } from "typeorm";

if (process.env.NODE_ENV === 'production' && process.env.DATABASE_URL.indexOf("sslmode=require") === -1) {
    process.env.DATABASE_URL += "?sslmode=require";
}

export default async function connect () {
    const dataSource = new DataSource({
        name: "default",
        type: "postgres",
        url: process.env.DATABASE_URL,
        entities: [`${process.env.NODE_ENV === 'production' ? 'dist' : 'src'}/entities/*.*`],
        ssl: process.env.NODE_ENV === 'production'
    });
    const connection = await dataSource.initialize();
    return connection;
}


问:
i have to calculate a matrix with biopython by aligning sequences taken from a protein
I have to calculate a matrix from the alignement of some sequences,which is the library from which I can import the function : MatrixInfo?

with the previous version of biopython (3.7) I have always being using "Bio.SubsMat" as function, now, with the new version (3.8), this function doesn't work anymore.

I tried to use Bio.Align, but the resulting matrices, with global and local values, are exactly the same and they should not.
how can I overcome the problem?


问:
setting up React store using Immer
I am trying to set up store in React using immer and borrowed the code from another project. However it doesn't work for me. Could be that immer version on borrowed project is lower than it is now.

Store looks like this:

```<code>const initialState: MyState = {
    search: "No results yet"
}

const useValue = () => useState(initialState);

const { Provider, useTrackedState, useUpdate: useSetState } = createContainer(
    useValue
);

const useSetDraft = () => {
    const setState = useSetState();
    return useCallback(
        (draftUpdater: MyState) => {
            setState(produce(draftUpdater));
        },
        [setState]
    );
};

export { Provider, useTrackedState, useSetDraft, initialState }
</code>```

and hook that i use to mutate state is:

```<code>const UseSetSearch = () => {
    const setDraft = useSetDraft();

    return useCallback((searchString: string) => {
        setDraft((draft: MyState) => {
            draft.search = searchString
            return draft
        })
    }, [setDraft]);
}
</code>```

With the store, I get error

Type 'MyState' provides no match for the signature '(state: WritableDraft): ValidRecipeReturnType'

and hook error is

Value of type '(draft: MyState) => MyState' has no properties in common with type 'MyState'. Did you mean to call it?

Store error is fixed when I do:

```<code>const useSetDraft = () => {
    const setState = useSetState();
    return useCallback(
        (draftUpdater: MyState) => {
            setState(produce(draftUpdater, draft => {

            }));
        },
        [setState]
    );
};
</code>```

but hook error remains. What am I missing?

Title: setting up React store using Immer

Body:
I am trying to set up store in React using immer and borrowed the code from another project. However it doesn't work for me. Could be that immer version on borrowed project is lower than it is now.

Store looks like this:

const initialState: MyState = {
    search: "No results yet"
}

const useValue = () => useState(initialState);

const { Provider, useTrackedState, useUpdate: useSetState } = createContainer(
    useValue
);

const useSetDraft = () => {
    const setState = useSetState();
    return useCallback(
        (draftUpdater: MyState) => {
            setState(produce(draftUpdater));
        },
        [setState]
    );
};

export { Provider, useTrackedState, useSetDraft, initialState }

and hook that i use to mutate state is:

const UseSetSearch = () => {
    const setDraft = useSetDraft();

    return useCallback((searchString: string) => {
        setDraft((draft: MyState) => {
            draft.search = searchString
            return draft
        })
    }, [setDraft]);
}

With the store, I get error

Type 'MyState' provides no match for the signature '(state: WritableDraft): ValidRecipeReturnType'

and hook error is

Value of type '(draft: MyState) => MyState' has no properties in common with type 'MyState'. Did you mean to call it?

Store error is fixed when I do:

const useSetDraft = () => {
    const setState = useSetState();
    return useCallback(
        (draftUpdater: MyState) => {
            setState(produce(draftUpdater, draft => {

            }));
        },
        [setState]
    );
};

but hook error remains. What am I missing?


问:
I am using ffmpeg.wasm library and I can compress all type of videos except mov files
I am using ffmpeg.wasm library and I can't compress mov files in the browser. I don't know if there is a way to solve it. If you try it in their official website it doesn't work either: https://ffmpegwasm.netlify.app/#demo.

How could I compress all videos in the browser without having any problem. I can't use the server because there are a lot of users and the server would have to do too much work.


问:
Swift: How can different types be used for a variable in a struct?
I have this TypeScript expression:

type ApexAxisChartSeries = {
  data:
    | (number | null)[]
    | {
        x: any;
        y: any;
      }[]
}[]
```
<p>I would convert it to Swift. How can <code>data</code> be expressed, that it can be either be array of objects, or array of numbers?</p>
<p>I get to here:</p>
<pre class="lang-swift prettyprint-override"><code>struct ApexData {
    var x: Float
    var y: Float
}

struct ApexAxisChartSeries {
    var data: [ApexData]
}
</code>```

Do I need an enum inside struct?

Body:
I have this TypeScript expression:

type ApexAxisChartSeries = {
  data:
    | (number | null)[]
    | {
        x: any;
        y: any;
      }[]
}[]

I would convert it to Swift. How can data be expressed, that it can be either be array of objects, or array of numbers?

I get to here:

struct ApexData {
    var x: Float
    var y: Float
}

struct ApexAxisChartSeries {
    var data: [ApexData]
}

Do I need an enum inside struct?


问:
How to validate an expression in Apache Calcite
I want to know how to validate a expression in Calcite. I create a schema and add my table into it, then I want to use Validator to validate a SqlNode which is from an expression. Here is the code.

```<code>public class DummyTable extends AbstractTable {

    private final String tableName;

    public DummyTable(String tableName) {
        this.tableName = tableName;
    }
    @Override
    public RelDataType getRowType(RelDataTypeFactory typeFactory) {
        RelDataTypeFactory.Builder builder = typeFactory.builder();
        builder.add("a", SqlTypeName.BIGINT);
        builder.add("b", SqlTypeName.BIGINT);
        return builder.build();
    }

    public String getTableName() {
        return tableName;
    }
}
</code>```
```<code>
public class ConditionValidator {
    private final String sql;

    private final SchemaPlus rootSchema;

    private final FrameworkConfig frameworkConfig;

    private final RelDataTypeFactory relDataTypeFactory;

    private final CalciteCatalogReader catalogReader;

    private final SqlOperatorTable sqlOperatorTable;

    private final SqlValidator validator;

    public ConditionValidator(String sql) {
        this.sql = sql;
        SchemaPlus rootSchema = Frameworks.createRootSchema(true);
        DummyTable testTable = new DummyTable("test_table");
        rootSchema.add(testTable.getTableName(), testTable);
        this.rootSchema = rootSchema;
        this.frameworkConfig =  Frameworks.newConfigBuilder()
                .parserConfig(SqlParser.config()
                        .withLex(Lex.MYSQL)
                        .withConformance(SqlConformanceEnum.DEFAULT))
                .defaultSchema(rootSchema)
                .operatorTable(SqlStdOperatorTable.instance())
                .build();
        this.relDataTypeFactory = new SqlTypeFactoryImpl(RelDataTypeSystem.DEFAULT);
        Properties properties = new Properties();
        properties.setProperty(CalciteConnectionProperty.CASE_SENSITIVE.camelName(), "true");
        this.catalogReader = new CalciteCatalogReader(
                CalciteSchema.from(rootSchema),
                CalciteSchema.from(rootSchema).path(rootSchema.getName()),
                relDataTypeFactory,
                new CalciteConnectionConfigImpl(properties));
        this.sqlOperatorTable = SqlOperatorTables.chain(frameworkConfig.getOperatorTable(), catalogReader);
        this.validator = SqlValidatorUtil.newValidator(sqlOperatorTable, catalogReader, relDataTypeFactory, frameworkConfig.getSqlValidatorConfig());
    }

    public SqlNode validate() {
        SqlParser sqlParser = SqlParser.create(sql, frameworkConfig.getParserConfig());
        SqlNode sqlNode;
        try {
            sqlNode = sqlParser.parseExpression();
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        SqlNode validate = validator.validate(sqlNode);
        return validate;
    }
}

</code>```

And now I can validate a SqlNode from a SQL query, for example, when input sql is "select a, b from test_table where a > 1 and b = 1", validation is ok (if validating a query, you should use the way below to parse the sql:

```<code>sqlNode = sqlParser.parseQuery(); // not 'sqlParser.parseExpression();
</code>```

).

However, when I validate an expression like "a > 1 and b = 1", such an exception occurs: "Column 'a' not found in any table". I assume there maybe something wrong with validate scope, but I can't find the solution. Can someone help me? Thanks a lot!

Body:
I want to know how to validate a expression in Calcite. I create a schema and add my table into it, then I want to use Validator to validate a SqlNode which is from an expression. Here is the code.

public class DummyTable extends AbstractTable {

    private final String tableName;

    public DummyTable(String tableName) {
        this.tableName = tableName;
    }
    @Override
    public RelDataType getRowType(RelDataTypeFactory typeFactory) {
        RelDataTypeFactory.Builder builder = typeFactory.builder();
        builder.add("a", SqlTypeName.BIGINT);
        builder.add("b", SqlTypeName.BIGINT);
        return builder.build();
    }

    public String getTableName() {
        return tableName;
    }
}

public class ConditionValidator {
    private final String sql;

    private final SchemaPlus rootSchema;

    private final FrameworkConfig frameworkConfig;

    private final RelDataTypeFactory relDataTypeFactory;

    private final CalciteCatalogReader catalogReader;

    private final SqlOperatorTable sqlOperatorTable;

    private final SqlValidator validator;

    public ConditionValidator(String sql) {
        this.sql = sql;
        SchemaPlus rootSchema = Frameworks.createRootSchema(true);
        DummyTable testTable = new DummyTable("test_table");
        rootSchema.add(testTable.getTableName(), testTable);
        this.rootSchema = rootSchema;
        this.frameworkConfig =  Frameworks.newConfigBuilder()
                .parserConfig(SqlParser.config()
                        .withLex(Lex.MYSQL)
                        .withConformance(SqlConformanceEnum.DEFAULT))
                .defaultSchema(rootSchema)
                .operatorTable(SqlStdOperatorTable.instance())
                .build();
        this.relDataTypeFactory = new SqlTypeFactoryImpl(RelDataTypeSystem.DEFAULT);
        Properties properties = new Properties();
        properties.setProperty(CalciteConnectionProperty.CASE_SENSITIVE.camelName(), "true");
        this.catalogReader = new CalciteCatalogReader(
                CalciteSchema.from(rootSchema),
                CalciteSchema.from(rootSchema).path(rootSchema.getName()),
                relDataTypeFactory,
                new CalciteConnectionConfigImpl(properties));
        this.sqlOperatorTable = SqlOperatorTables.chain(frameworkConfig.getOperatorTable(), catalogReader);
        this.validator = SqlValidatorUtil.newValidator(sqlOperatorTable, catalogReader, relDataTypeFactory, frameworkConfig.getSqlValidatorConfig());
    }

    public SqlNode validate() {
        SqlParser sqlParser = SqlParser.create(sql, frameworkConfig.getParserConfig());
        SqlNode sqlNode;
        try {
            sqlNode = sqlParser.parseExpression();
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        SqlNode validate = validator.validate(sqlNode);
        return validate;
    }
}

And now I can validate a SqlNode from a SQL query, for example, when input sql is "select a, b from test_table where a > 1 and b = 1", validation is ok (if validating a query, you should use the way below to parse the sql:

sqlNode = sqlParser.parseQuery(); // not 'sqlParser.parseExpression();

).

However, when I validate an expression like "a > 1 and b = 1", such an exception occurs: "Column 'a' not found in any table". I assume there maybe something wrong with validate scope, but I can't find the solution. Can someone help me? Thanks a lot!


问:
Why value remains borrowed even after its sope ends?
I am trying to break a text intro substrings.
However the Rust compiler issues E0505.

Here is a cut down version of the code:

```<code>struct N<'e> {
    name: &'e str,
}

struct BigState<'e> {
    text: &'e str,
    nm: Option<N<'e>>,
}

fn mod_text<'e>(s: &'e mut &'e str) -> N<'e> {
    let h = s.split_at(3).0;
    *s = s.split_at(3).1;
    return N { name: h };
}

fn print_and_destroy(bs: BigState) {
    println!("{:}", bs.text);
    println!("{:}", bs.nm.unwrap().name);
}

fn main() {
    let text = "12345789";
    let mut bs = BigState {
        text: text,
        nm: None,
    };
    {
        let fresh_nm = mod_text(&mut bs.text);
        bs.nm = Some(fresh_nm);
    }
    print_and_destroy(bs);
}
</code>```

I don't understand why is bs.text still borrowed after the function mod_text returns.

The expected result whould be:

```<code>456789
123
</code>```

What has to give so the code will compile?

Body:
I am trying to break a text intro substrings.
However the Rust compiler issues E0505.

Here is a cut down version of the code:

struct N<'e> {
    name: &'e str,
}

struct BigState<'e> {
    text: &'e str,
    nm: Option<N<'e>>,
}

fn mod_text<'e>(s: &'e mut &'e str) -> N<'e> {
    let h = s.split_at(3).0;
    *s = s.split_at(3).1;
    return N { name: h };
}

fn print_and_destroy(bs: BigState) {
    println!("{:}", bs.text);
    println!("{:}", bs.nm.unwrap().name);
}

fn main() {
    let text = "12345789";
    let mut bs = BigState {
        text: text,
        nm: None,
    };
    {
        let fresh_nm = mod_text(&mut bs.text);
        bs.nm = Some(fresh_nm);
    }
    print_and_destroy(bs);
}

I don't understand why is bs.text still borrowed after the function mod_text returns.

The expected result whould be:

456789
123

What has to give so the code will compile?


问:
How to get rid of one placeholder at a time when the user types on that line? (swiftUI)
I put "placeholders" in my TextEditor. I used .isEmpty but I soon learned that by typing in the TextEditor it gets rid of all placeholders. I only want it to get rid of the appropriate "placeholder" when the user types on that line but not get rid of them all at once. How might I achieve this?

I am starting to think .isEmpty is not the solution for this, but I'm not sure. Ideally I'd like to add a TextField INTO the TextEditor but I can't figure out how to do this.

Here is my .isEmpty code which gets rid of both "placeholders" when you type (or even press the space button):

```<code>ZStack (alignment: .leading){

            if test.isEmpty{
                VStack{

                    Text("Recipe Name")
                        .padding(.top,10)
                        .opacity(1)
                        .font(.system(size: 20))
                        .foregroundColor(.black)
                    Spacer()

                }
            }

            if test2.isEmpty{
                VStack{

                    Text("Recipe made by (link if applicable)")
                        .padding(.top, 50)
                        .opacity(1)
                        .font(.system(size: 20))
                        .foregroundColor(.black)

                    Spacer()

                }
            }

            VStack{
                TextEditor(text: $note.text)
                    .opacity(note.text.isEmpty ? 0.85 : 1)
                    .font(.custom("SanFrancisco", fixedSize: 20))
                    .onReceive(note.publisher(for: \.text), perform: setName)
                    .onReceive(
                        note.publisher(for: \.text)
                            .debounce(for: 0.5, scheduler: RunLoop.main)
                            .removeDuplicates()
                    ){ _ in
                        try? PersistenceController.shared.saveContext()
                    }
                    .navigationTitle(note.name)
            }
        }

    }
</code>```

Body:
I put "placeholders" in my TextEditor. I used .isEmpty but I soon learned that by typing in the TextEditor it gets rid of all placeholders. I only want it to get rid of the appropriate "placeholder" when the user types on that line but not get rid of them all at once. How might I achieve this?

I am starting to think .isEmpty is not the solution for this, but I'm not sure. Ideally I'd like to add a TextField INTO the TextEditor but I can't figure out how to do this.

Here is my .isEmpty code which gets rid of both "placeholders" when you type (or even press the space button):

ZStack (alignment: .leading){

            if test.isEmpty{
                VStack{

                    Text("Recipe Name")
                        .padding(.top,10)
                        .opacity(1)
                        .font(.system(size: 20))
                        .foregroundColor(.black)
                    Spacer()

                }
            }

            if test2.isEmpty{
                VStack{

                    Text("Recipe made by (link if applicable)")
                        .padding(.top, 50)
                        .opacity(1)
                        .font(.system(size: 20))
                        .foregroundColor(.black)

                    Spacer()

                }
            }

            VStack{
                TextEditor(text: $note.text)
                    .opacity(note.text.isEmpty ? 0.85 : 1)
                    .font(.custom("SanFrancisco", fixedSize: 20))
                    .onReceive(note.publisher(for: \.text), perform: setName)
                    .onReceive(
                        note.publisher(for: \.text)
                            .debounce(for: 0.5, scheduler: RunLoop.main)
                            .removeDuplicates()
                    ){ _ in
                        try? PersistenceController.shared.saveContext()
                    }
                    .navigationTitle(note.name)
            }
        }

    }


问:
Is there any command to produce a ven diagram from melt data
I have a dataset which contains users with a specific id who buy in specific time stamps a stock with a specific name.

Here is the stucture of the dataset:

```<code>data.frame(id = c(1,1,1,1,2,2,3,4,4,4), timestamp = c("2011-02-14 01:59:23","2011-08-06 23:24:15","2011-04-23 22:01:50","2011-08-07 00:04:25","2011-02-09 17:26:22","2011-03-09 00:26:41","2010-11-03 03:58:28","2011-02-28 14:03:57","2011-02-17 21:21:46","2011-02-02 02:05:42"), stockname = c("google", "yahoo", "google", "amazon", "google", "google", "amazon", "yahoo", "amazon", "yahoo"))
</code>```

How is it possible to check if users' path buy channel of stocks? I mean if the tend to buy the same or other using a ven diagram like [![this][1]][1]

Body:
I have a dataset which contains users with a specific id who buy in specific time stamps a stock with a specific name.

Here is the stucture of the dataset:

data.frame(id = c(1,1,1,1,2,2,3,4,4,4), timestamp = c("2011-02-14 01:59:23","2011-08-06 23:24:15","2011-04-23 22:01:50","2011-08-07 00:04:25","2011-02-09 17:26:22","2011-03-09 00:26:41","2010-11-03 03:58:28","2011-02-28 14:03:57","2011-02-17 21:21:46","2011-02-02 02:05:42"), stockname = c("google", "yahoo", "google", "amazon", "google", "google", "amazon", "yahoo", "amazon", "yahoo"))

How is it possible to check if users' path buy channel of stocks? I mean if the tend to buy the same or other using a ven diagram like [![this][1]][1]


问:
How can I type check uuid and date_time in an entity generated from sqlite by sea-orm-cli?
I'm using the sea-orm library to manage my database. The uuid() and date_time() types are part of the sea-orm migration syntax. When sea-orm generates the entities from the SQLite database, uuid() and date_time() get converted into String.

Should I change these types on the entities manually for some other type if I want them to be type-checked? How can I do that? What types can I use? Will I have to convert them back to String when importing data into the database? How can I do that?


问:
sub domain pointed to the wrong website folder
I have a linux server that run multiple different website on multiple different domain which are working fine.

But I created a sub domain for one of the domain which is demo.mywebsitedomain.com I did the configuration like it was a different domain which mean I created a specific nginx socket  / service / nginx config file for this subdomain

But when I go the my link demo.mywebsitedomain.com it run the website application of an other django application folder, it not the one who I have pointed in the socket and service file. I am verry confuse.

It should run the django application whos in the testdemo folder but instead it run a different folder application. Those are the file I created for the subdomain

sudo vim /etc/systemd/system/testdemo.socket

```<code>[Unit]
Description=gunicorn socket

[Socket]
ListenStream=/run/testdemo.sock

Environment="PATH=/usr/bin:/home/tiber/testdemo/env/bin"

[Install]
WantedBy=sockets.target

</code>```

sudo vim /etc/systemd/system/testdemo.service

```<code>[Unit]
Description=gunicorn daemon
Requires=testdemo.socket
After=network.target

[Service]
User=tiber
Group=www-data
WorkingDirectory=/home/tiber/testdemo
ExecStart=/home/tiber/testdemo/env/bin/gunicorn \
          --access-logfile - \
          --workers 3 \
          --bind unix:/run/testdemo.sock \
          mysite.wsgi:application

[Install]
WantedBy=multi-user.target

</code>```

sudo vim /etc/nginx/sites-available/testdemo

```<code>server {
    listen 80;
    server_name demo.mywebsitedomain.com;

    location = /favicon.ico { access_log off; log_not_found off; }
    location /static/ {
        root /var/www/testdemo;
    }

    location /media/ {
        root /var/www/testdemo;
    }

    location / {
        include proxy_params;
        proxy_pass http://unix:/run/testdemo.sock;
    }
}
</code>```

Body:
I have a linux server that run multiple different website on multiple different domain which are working fine.

But I created a sub domain for one of the domain which is demo.mywebsitedomain.com I did the configuration like it was a different domain which mean I created a specific nginx socket  / service / nginx config file for this subdomain

But when I go the my link demo.mywebsitedomain.com it run the website application of an other django application folder, it not the one who I have pointed in the socket and service file. I am verry confuse.

It should run the django application whos in the testdemo folder but instead it run a different folder application. Those are the file I created for the subdomain

sudo vim /etc/systemd/system/testdemo.socket

[Unit]
Description=gunicorn socket

[Socket]
ListenStream=/run/testdemo.sock

Environment="PATH=/usr/bin:/home/tiber/testdemo/env/bin"

[Install]
WantedBy=sockets.target

sudo vim /etc/systemd/system/testdemo.service

[Unit]
Description=gunicorn daemon
Requires=testdemo.socket
After=network.target

[Service]
User=tiber
Group=www-data
WorkingDirectory=/home/tiber/testdemo
ExecStart=/home/tiber/testdemo/env/bin/gunicorn \
          --access-logfile - \
          --workers 3 \
          --bind unix:/run/testdemo.sock \
          mysite.wsgi:application

[Install]
WantedBy=multi-user.target

sudo vim /etc/nginx/sites-available/testdemo

server {
    listen 80;
    server_name demo.mywebsitedomain.com;

    location = /favicon.ico { access_log off; log_not_found off; }
    location /static/ {
        root /var/www/testdemo;
    }

    location /media/ {
        root /var/www/testdemo;
    }

    location / {
        include proxy_params;
        proxy_pass http://unix:/run/testdemo.sock;
    }
}


问:
Adding dynamic script (code, not url) from NewRelic library does not work
I have to integrate NewRelic with script tag they have provided to me.

The fact is if I include it in the head, it works. But if I add it dinamically, creating a script element, append it to the head, etc, it does not work.

How do I identify if it works or not? Because that script triggers a fetch that gets another javascript in a request.

I'm trying to understand why. I found another way to implement it but Im very curious about it. No errors in console. I guess it is a minified version, and also probably compiled version (Not Es6), but it should work.


问:
$event.stopPropagation() doesn't seem to prevent a directive in a parent element from receiving the event [Angular][routerLink][Directive]
EDIT: found out what was wrong; read the solution below.

I wrote a directive to open the link in a new tab, and it's working wonderfully.

The problem is when I put it in a table that has a link in the entire row, and an event listener in a specific cell that should not activate the link and call a function, but it captures the event and activates the link even though I called $event.stopPropagation in said function.

In this example, clicking in the first row doesn't trigger routerLink, but the second triggers routing:

Hello

Hello

<router-outlet></router-outlet>
```
<p>Directive code:</p>
<pre class="lang-ts prettyprint-override"><code>import { Directive, HostListener, Input } from '@angular/core';
import { ActivatedRoute, Router } from '@angular/router';

@Directive({
  selector: '[appNewTab]',
})
export class NewTabDirective {
  @Input() appNewTab = '/';

  constructor(private router: Router, private route: ActivatedRoute) {}

  private get url(): string {
    return window.location.href + '/' + this.appNewTab;
  }

  @HostListener('mousedown', ['$event'])
  onClick($event: MouseEvent) {
    if ($event.ctrlKey || $event.metaKey || $event.button === 1) {
      window.open(this.url, '_blank');
    } else if ($event.button === 0) {
      this.router.navigate([this.appNewTab], { relativeTo: this.route });
    }
  }
}

</code>```

Run in stackblitz (updated with working example)

ps.: I'm also using $event.preventDefault(), but I don't think it matters in this specific case.

ps2.: I put both $event.preventDefault() and $event.stopPropagation() inside the directive's onClick method, but I don't think it matters too.

SOLUTION

The issue was that I was listening to the mousedown event, but the click event is different, so calling stopPropagation inside it wouldn't stop the propagation of the click event after the user released the mouse button.

I changed it from click to mousedown because the click event only fires with the left button mouse, and I needed to listen to the middle mouse button clicks.

The solution was to separate the HostListener in two:

import { Directive, HostListener, Input } from '@angular/core';
import { ActivatedRoute, Router } from '@angular/router';

@Directive({
  selector: '[appNewTab]',
})
export class NewTabDirective {
  @Input() appNewTab = '/';

  constructor(private router: Router, private route: ActivatedRoute) {}

  private get url(): string {
    return window.location.href + '/' + this.appNewTab;
  }

  @HostListener('click', ['$event'])
  onClick($event: MouseEvent) {
    $event.preventDefault();
    $event.stopPropagation();

    if ($event.ctrlKey || $event.metaKey) {
      window.open(this.url, '_blank');
    } else {
      this.router.navigate([this.appNewTab], { relativeTo: this.route });
    }
  }

  @HostListener('mousedown', ['$event'])
  onMouseDown($event: MouseEvent) {
    $event.preventDefault();
    $event.stopPropagation();

    if ($event.button === 1) {
      window.open(this.url, '_blank');
    }
  }
}
```

Body:
EDIT: found out what was wrong; read the solution below.

I wrote a directive to open the link in a new tab, and it's working wonderfully.

The problem is when I put it in a table that has a link in the entire row, and an event listener in a specific cell that should not activate the link and call a function, but it captures the event and activates the link even though I called $event.stopPropagation in said function.

In this example, clicking in the first row doesn't trigger routerLink, but the second triggers routing:

Hello

Hello

<router-outlet></router-outlet>

Directive code:

import { Directive, HostListener, Input } from '@angular/core';
import { ActivatedRoute, Router } from '@angular/router';

@Directive({
  selector: '[appNewTab]',
})
export class NewTabDirective {
  @Input() appNewTab = '/';

  constructor(private router: Router, private route: ActivatedRoute) {}

  private get url(): string {
    return window.location.href + '/' + this.appNewTab;
  }

  @HostListener('mousedown', ['$event'])
  onClick($event: MouseEvent) {
    if ($event.ctrlKey || $event.metaKey || $event.button === 1) {
      window.open(this.url, '_blank');
    } else if ($event.button === 0) {
      this.router.navigate([this.appNewTab], { relativeTo: this.route });
    }
  }
}

Run in stackblitz (updated with working example)

ps.: I'm also using $event.preventDefault(), but I don't think it matters in this specific case.

ps2.: I put both $event.preventDefault() and $event.stopPropagation() inside the directive's onClick method, but I don't think it matters too.

SOLUTION

The issue was that I was listening to the mousedown event, but the click event is different, so calling stopPropagation inside it wouldn't stop the propagation of the click event after the user released the mouse button.

I changed it from click to mousedown because the click event only fires with the left button mouse, and I needed to listen to the middle mouse button clicks.

The solution was to separate the HostListener in two:

import { Directive, HostListener, Input } from '@angular/core';
import { ActivatedRoute, Router } from '@angular/router';

@Directive({
  selector: '[appNewTab]',
})
export class NewTabDirective {
  @Input() appNewTab = '/';

  constructor(private router: Router, private route: ActivatedRoute) {}

  private get url(): string {
    return window.location.href + '/' + this.appNewTab;
  }

  @HostListener('click', ['$event'])
  onClick($event: MouseEvent) {
    $event.preventDefault();
    $event.stopPropagation();

    if ($event.ctrlKey || $event.metaKey) {
      window.open(this.url, '_blank');
    } else {
      this.router.navigate([this.appNewTab], { relativeTo: this.route });
    }
  }

  @HostListener('mousedown', ['$event'])
  onMouseDown($event: MouseEvent) {
    $event.preventDefault();
    $event.stopPropagation();

    if ($event.button === 1) {
      window.open(this.url, '_blank');
    }
  }
}