问:
Send a non-declared variable through HTML post method
I've been learning python's flask module to create websites/apis.
I was trying to make a site where I can create a user, log into that user and change the user's password.

Here's my code. I wanted to send a post request with the user's username and current password and new password from /cp_user/<username> to /cp_func

# environ and getenv have been imported from os module

def users():
    with open("users", "r") as usersfile:
        userslist = usersfile.read().splitlines()
    return userslist

@app.route("/cp_func", methods=["POST"])
def cp_func():
    username=request.form["username"].strip()
    password=request.form["password"].strip()
    new_password=request.form["new_password"].strip()
    if username == "":
        return """
username cannot be empty!

you have entered an empty username!

        Return to main site"""
    if password == "":
        return """
current password cannot be empty!

you have entered an empty current password!

        Return to main site"""
    if new_password == "":
        return """
new password cannot be empty!

you have entered an empty new password!

        Return to main site"""
    if username in users():
        if getenv(username+":PASS") == None:
            environ[username+":PASS"] = new_password
            success = True
        elif getenv(username+":PASS") == password:
            environ[username+":PASS"] = new_password
            success = True
        else:
            success = False
        if success:
            return """<form action = "http://localhost:5000/home" method = "post">

Password changed!

Your password for account `{0}` was changed to `{1}`

            <input type = "submit" value = "Goto Home">
            Return to main site
            </form>""".format(username, new_password)
        else:
            return """<h>Access Denied

you wanted to change the password of `{0}` but failed miserably by entering the wrong password, and what you entered was `{1}`

            Return to main site""".format(username, password)
    else:
        return """
user not found

you wanted to change the password of `{0}` but failed miserably by specifying a non-existing user

        Return to main site""".format(username)

@app.route("/cp_user/<username>")
def cp_user(username):
    if username == "":
        return """
username cannot be empty!

you have entered an empty username!

        Return to main site"""
    if username in users():
        return """
        <form action="http://127.0.0.1:5000/cp_func" method="post">

Change Password

Changing username for {0}

Current Password
                <input type="password" name="password">

New Password
                <input type="password" name="new_password">

<input type="submit" value="Change">

Go back to the main site

        </form>
        """.format(username)
    else:
        return """
user not found

you wanted to change the password of `{0}` but failed miserably by specifying a non-existing user

        Return to main site""".format(username)
```
<p>here's the HTML separately, if you needed it</p>
<pre class="lang-html prettyprint-override"><code>        <form action="http://127.0.0.1:5000/cp_func" method="post">
            <table>
                <tr><td><h1>Change Password</h1></td></tr>
                <tr><td><h4>Changing username for {0}</h4></td></tr>
                <tr><td>Current Password</td>
                <td><input type="password" name="password"></td></tr>
                <tr><td>New Password</td>
                <td><input type="password" name="new_password"></td></tr>
                <tr><td><input type="submit" value="Change"></td></tr>
                <tr><td>Go back to the main site</td></tr>
            </table>
        </form>
</code>```

I'm still learning about HTML, and I've been searching for a solution for 5 hours straight but still couldn't find a solution to my problem.

Thanks in advance for helping me.

答:
The form needs an input field with the username. You can use a hidden input for this.</p>
```<code>    if username in users():
        return """
        <form action="http://127.0.0.1:5000/cp_func" method="post">
            <table>
                <tr><td><h1>Change Password</h1></td></tr>
                <tr><td><h4>Changing username for {0}</h4><input type="hidden" name="username" value="{1}"></td></tr>
                <tr><td>Current Password</td>
                <td><input type="password" name="password"></td></tr>
                <tr><td>New Password</td>
                <td><input type="password" name="new_password"></td></tr>
                <tr><td><input type="submit" value="Change"></td></tr>
                <tr><td><a href="http://127.0.0.1:5000/">Go back to the main site</a></td></tr>
            </table>
        </form>
        """.format(username, username)
</code>```

Body:
I've been learning python's flask module to create websites/apis.
I was trying to make a site where I can create a user, log into that user and change the user's password.

Here's my code. I wanted to send a post request with the user's username and current password and new password from /cp_user/<username> to /cp_func

# environ and getenv have been imported from os module

def users():
    with open("users", "r") as usersfile:
        userslist = usersfile.read().splitlines()
    return userslist

@app.route("/cp_func", methods=["POST"])
def cp_func():
    username=request.form["username"].strip()
    password=request.form["password"].strip()
    new_password=request.form["new_password"].strip()
    if username == "":
        return """
username cannot be empty!

you have entered an empty username!

        Return to main site"""
    if password == "":
        return """
current password cannot be empty!

you have entered an empty current password!

        Return to main site"""
    if new_password == "":
        return """
new password cannot be empty!

you have entered an empty new password!

        Return to main site"""
    if username in users():
        if getenv(username+":PASS") == None:
            environ[username+":PASS"] = new_password
            success = True
        elif getenv(username+":PASS") == password:
            environ[username+":PASS"] = new_password
            success = True
        else:
            success = False
        if success:
            return """<form action = "http://localhost:5000/home" method = "post">

Password changed!

Your password for account `{0}` was changed to `{1}`

            <input type = "submit" value = "Goto Home">
            Return to main site
            </form>""".format(username, new_password)
        else:
            return """<h>Access Denied

you wanted to change the password of `{0}` but failed miserably by entering the wrong password, and what you entered was `{1}`

            Return to main site""".format(username, password)
    else:
        return """
user not found

you wanted to change the password of `{0}` but failed miserably by specifying a non-existing user

        Return to main site""".format(username)

@app.route("/cp_user/<username>")
def cp_user(username):
    if username == "":
        return """
username cannot be empty!

you have entered an empty username!

        Return to main site"""
    if username in users():
        return """
        <form action="http://127.0.0.1:5000/cp_func" method="post">

Change Password

Changing username for {0}

Current Password
                <input type="password" name="password">

New Password
                <input type="password" name="new_password">

<input type="submit" value="Change">

Go back to the main site

        </form>
        """.format(username)
    else:
        return """
user not found

you wanted to change the password of `{0}` but failed miserably by specifying a non-existing user

        Return to main site""".format(username)

here's the HTML separately, if you needed it

        <form action="http://127.0.0.1:5000/cp_func" method="post">

Change Password

Changing username for {0}

Current Password
                <input type="password" name="password">

New Password
                <input type="password" name="new_password">

<input type="submit" value="Change">

Go back to the main site

        </form>

I'm still learning about HTML, and I've been searching for a solution for 5 hours straight but still couldn't find a solution to my problem.

Thanks in advance for helping me.

Body:
The form needs an input field with the username. You can use a hidden input for this.

    if username in users():
        return """
        <form action="http://127.0.0.1:5000/cp_func" method="post">
            <table>
                <tr><td><h1>Change Password</h1></td></tr>
                <tr><td><h4>Changing username for {0}</h4><input type="hidden" name="username" value="{1}"></td></tr>
                <tr><td>Current Password</td>
                <td><input type="password" name="password"></td></tr>
                <tr><td>New Password</td>
                <td><input type="password" name="new_password"></td></tr>
                <tr><td><input type="submit" value="Change"></td></tr>
                <tr><td><a href="http://127.0.0.1:5000/">Go back to the main site</a></td></tr>
            </table>
        </form>
        """.format(username, username)


来源: stackexchange

问:
Post data send in python using socket
I write a code who has to click a button on website, by sending a POST request. I use sockets to this. Here is my code:

```<code>import sys
import socket
import time
import socks

red = "\033[1;31m"
green = "\033[1;32m"
yellow = "\033[1;33m"
blue = "\033[1;34m"
defcol = "\033[0m"

s = socks.socksocket()
s.set_proxy(socks.SOCKS5, "209.33.198.133", 9999)
ipaddr = socket.gethostbyname('mclista.pl')
#ipaddr = 'mclista.pl'
s.connect(("149.202.218.96", 80))

header = ("""
POST /json/daj_diax/ HTTP/1.1
Host: www.mclista.pl
User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:63.0) Gecko/20100101 Firefox/63.0
Accept: application/json, text/javascript, */*; q=0.01
Accept-Language: pl,en-US;q=0.7,en;q=0.3
Accept-Encoding: gzip, deflate
Referer: https://www.google.com
Content-Type: application/x-www-form-urlencoded; charset=UTF-8
X-Requested-With: XMLHttpRequest
Content-Length: 68
Connection: keep-alive
Cookie: _ga=GA1.2.942145996.1539109230; _gid=GA1.2.1111512675.1541185659; csrf_mclista=65d10295bd238ea3c81f19b3e02d073c; ci_session=a%3A5%3A%7Bs%3A10%3A%22session_id%22%3Bs%3A32%3A%22d1e9deec40aa713329f98ddd11ce042f%22%3Bs%3A10%3A%22ip_address%22%3Bs%3A10%3A%225.184.63.6%22%3Bs%3A10%3A%22user_agent%22%3Bs%3A78%3A%22Mozilla%2F5.0+%28Windows+NT+10.0%3B+Win64%3B+x64%3B+rv%3A63.0%29+Gecko%2F20100101+Firefox%2F63.0%22%3Bs%3A13%3A%22last_activity%22%3Bi%3A1541242717%3Bs%3A9%3A%22user_data%22%3Bs%3A0%3A%22%22%3B%7D913ae0005d8fb07d1b6dc486b7fc9297; _gat=1
""")

print(yellow + header)
request = header
s.sendall(request.encode('utf-8'))
response = s.recv(4096)
time.sleep(2)
print('\n\n\n\n\n\n\n' + blue + str(response) + '\n')
s.close()
</code>```

My question is, why on send i getting it response:

```<code>HTTP/1.1 400 Bad Request
Date: Sat, 03 Nov 2018 11:20:02 GMT
Server: Apache
Content-Length: 226
Connection: close
Content-Type: text/html; charset=iso-8859-1

<!DOCTYPE HTML PUBLIC "-//IETF//DTD HTML 2.0//EN">
<html><head>
<title>400 Bad Request</title>
</head><body>
<h1>Bad Request</h1>
<p>Your browser sent a request that this server could not understand.<br />
</p>
</body></html>
</code>```

Anyone know, how to fix it? Header is good, i copy it from firefox network tools. I need to send POST request, not GET. Code written in python 3.7
On i send it post from firefox, i getting normal response:

```<code>status: "ok"
</code>```

答:
You may need to use CRLF \r\n:

header = ("POST /json/daj_diax/ HTTP/1.1\r\n"
          "Host: www.mclista.pl\r\n"
          "User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:63.0) Gecko/20100101 Firefox/63.0\r\n"
          "Accept: application/json, text/javascript, */*; q=0.01\r\n"
          "Accept-Language: pl,en-US;q=0.7,en;q=0.3\r\n"
          "Accept-Encoding: gzip, deflate\r\n"
          "Referer: http://www.mclista.pl/42204\r\n"
          "Content-Type: application/x-www-form-urlencoded; charset=UTF-8\r\n"
          "X-Requested-With: XMLHttpRequest\r\n"
          "Content-Length: 68\r\n"
          "Connection: keep-alive\r\n"
          "Cookie: _ga=GA1.2.942145996.1539109230; _gid=GA1.2.1111512675.1541185659; csrf_mclista=8cb69323a6f12ff338c06d4bea489c7f; ci_session=a%3A5%3A%7Bs%3A10%3A%22session_id%22%3Bs%3A32%3A%22b3df7ad8aef06a7428e497f90361eaef%22%3Bs%3A10%3A%22ip_address%22%3Bs%3A10%3A%225.184.63.6%22%3Bs%3A10%3A%22user_agent%22%3Bs%3A78%3A%22Mozilla%2F5.0+%28Windows+NT+10.0%3B+Win64%3B+x64%3B+rv%3A63.0%29+Gecko%2F20100101+Firefox%2F63.0%22%3Bs%3A13%3A%22last_activity%22%3Bi%3A1541265085%3Bs%3A9%3A%22user_data%22%3Bs%3A0%3A%22%22%3B%7D14f5f5334fa1876215c215f1f81889c6; _gat=1\r\n\r\n")
```

ContentLicense: CC BY-SA 4.0

Title: Post data send in python using socket

Body:
I write a code who has to click a button on website, by sending a POST request. I use sockets to this. Here is my code:

import sys
import socket
import time
import socks

red = "\033[1;31m"
green = "\033[1;32m"
yellow = "\033[1;33m"
blue = "\033[1;34m"
defcol = "\033[0m"

s = socks.socksocket()
s.set_proxy(socks.SOCKS5, "209.33.198.133", 9999)
ipaddr = socket.gethostbyname('mclista.pl')
#ipaddr = 'mclista.pl'
s.connect(("149.202.218.96", 80))

header = ("""
POST /json/daj_diax/ HTTP/1.1
Host: www.mclista.pl
User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:63.0) Gecko/20100101 Firefox/63.0
Accept: application/json, text/javascript, */*; q=0.01
Accept-Language: pl,en-US;q=0.7,en;q=0.3
Accept-Encoding: gzip, deflate
Referer: https://www.google.com
Content-Type: application/x-www-form-urlencoded; charset=UTF-8
X-Requested-With: XMLHttpRequest
Content-Length: 68
Connection: keep-alive
Cookie: _ga=GA1.2.942145996.1539109230; _gid=GA1.2.1111512675.1541185659; csrf_mclista=65d10295bd238ea3c81f19b3e02d073c; ci_session=a%3A5%3A%7Bs%3A10%3A%22session_id%22%3Bs%3A32%3A%22d1e9deec40aa713329f98ddd11ce042f%22%3Bs%3A10%3A%22ip_address%22%3Bs%3A10%3A%225.184.63.6%22%3Bs%3A10%3A%22user_agent%22%3Bs%3A78%3A%22Mozilla%2F5.0+%28Windows+NT+10.0%3B+Win64%3B+x64%3B+rv%3A63.0%29+Gecko%2F20100101+Firefox%2F63.0%22%3Bs%3A13%3A%22last_activity%22%3Bi%3A1541242717%3Bs%3A9%3A%22user_data%22%3Bs%3A0%3A%22%22%3B%7D913ae0005d8fb07d1b6dc486b7fc9297; _gat=1
""")

print(yellow + header)
request = header
s.sendall(request.encode('utf-8'))
response = s.recv(4096)
time.sleep(2)
print('\n\n\n\n\n\n\n' + blue + str(response) + '\n')
s.close()

My question is, why on send i getting it response:

HTTP/1.1 400 Bad Request
Date: Sat, 03 Nov 2018 11:20:02 GMT
Server: Apache
Content-Length: 226
Connection: close
Content-Type: text/html; charset=iso-8859-1

<!DOCTYPE HTML PUBLIC "-//IETF//DTD HTML 2.0//EN">

<title>400 Bad Request</title>

Bad Request

Your browser sent a request that this server could not understand.

Anyone know, how to fix it? Header is good, i copy it from firefox network tools. I need to send POST request, not GET. Code written in python 3.7
On i send it post from firefox, i getting normal response:

status: "ok"


问:
Download File on Webpage via Windows CMD/Power Shell
just as the title states, I'd like to download a file from the internet, specifically the download on this webpage. I have looked into using Invoke-WebRequest, curl, and certutil. All of these options download the HTML of the site. The specific URL of the download looks like this: https://bluetoothinstaller.com/bluetooth-command-line-tools/BluetoothCLTools-1.2.0.56.exe.

Calling things like the following just downloads the HTML:

```<code>Invoke-WebRequest -Uri 'https://bluetoothinstaller.com/bluetooth-command-line-tools/BluetoothCLTools-1.2.0.56.exe' -OutFile 'test.exe'
</code>```

Alternatively, if anyone knows how to download the link via the HTML, please do share.

I'd prefer it if the solution did not require any additional software, but am flexible.

Thanks!

答:
The following worked for me, note the OutFile comment. You might find something useful on the Network tab of your browser's dev-tools.

$params = @{
    UseBasicParsing = $true
    Uri = "https://bluetoothinstaller.com/bluetooth-command-line-tools/BluetoothCLTools-1.2.0.56.exe"
    Headers = @{
        Referer = "https://bluetoothinstaller.com/bluetooth-command-line-tools/download.html"
    }
    OutFile = 'path/to/download.exe' # Change this
}
Invoke-RestMethod @params
```

Body:
just as the title states, I'd like to download a file from the internet, specifically the download on this webpage. I have looked into using Invoke-WebRequest, curl, and certutil. All of these options download the HTML of the site. The specific URL of the download looks like this: https://bluetoothinstaller.com/bluetooth-command-line-tools/BluetoothCLTools-1.2.0.56.exe.

Calling things like the following just downloads the HTML:

Invoke-WebRequest -Uri 'https://bluetoothinstaller.com/bluetooth-command-line-tools/BluetoothCLTools-1.2.0.56.exe' -OutFile 'test.exe'

Alternatively, if anyone knows how to download the link via the HTML, please do share.

I'd prefer it if the solution did not require any additional software, but am flexible.

Thanks!


问:
HTML5 application cache on iPad offline app - not working if server is unavailable?
I'm developing a small HTML5 web application for iPad that is intended to work in fullscreen mode (ie. it has the proprietary Apple meta tag, it is added to Home Screen):

```<code><meta name="apple-mobile-web-app-capable" content="yes" />
</code>```

The application basically fetches some data via AJAX and presents it to the user. The AJAX data are external (from a different domain, different server). I have the system setup for cross-origin requests, they work in online mode. In other words: the static data lie on server A, the dynamic data - on server B.

I created a proper cache manifest file, listing all static content of the site (HTML, CSS, images, JS) and then having the NETWORK: * section at the end - this way all the dynamic content (AJAX) is always retrieved from the network. The application fails "gracefully" if the requests fail, by displaying some fake content.

With the above setup, the following happens:

If I run the application while online, everything works ;)

If I disable the WiFi on iPad (pure offline mode), everything works as expected - the application falls back to the offline content

If I connect to the network again, but take the static-content server offline (the one that has everything cached), the application won't start; after spending a while in splash-screen, it shows me the a popup with <app> could not be opened because it could not connect to the server.; I can either choose Close or Retry.

The point 3 of the above is the one that drives me crazy because it was the only reason I started fiddling with application cache. Why doesn't the iPad web app fall back to cached content if the manifest file is not reachable? (not 404, the server is offline)

Is the answer to HTML5 iphone offline webapp completely incorrect? If not, how can I achieve this behavior on iPad?

答:
Point 2 and 3 are completely different scenarios, so we cannot expect the same behavior.

In point 3, the device cannot fall back to the cached content when in online mode because if it do so, there will be no way to know for the user whether he is connected to the server or not.

I mean, in offline mode, the user knows it, and knows that he is with cached data. But in online mode, he expects to get the stuff from the server. If the server is not available, the user should be aware  of this. If the server is not available and he is sent directly to cached data, the server error will be hidden to him, thinking that he is connected when he is actually not.

For example, web browsers can cache pages to be seen in offline mode. But if we are in online mode and try to open an unavailable page, we expect to see the error message, not a cached version of the page without any warning. We can go to offline mode to see the cached page if we want, but the correct behavior is to show the error to the user.

ContentLicense: CC BY-SA 3.0

Body:
I'm developing a small HTML5 web application for iPad that is intended to work in fullscreen mode (ie. it has the proprietary Apple meta tag, it is added to Home Screen):

<meta name="apple-mobile-web-app-capable" content="yes" />

The application basically fetches some data via AJAX and presents it to the user. The AJAX data are external (from a different domain, different server). I have the system setup for cross-origin requests, they work in online mode. In other words: the static data lie on server A, the dynamic data - on server B.

I created a proper cache manifest file, listing all static content of the site (HTML, CSS, images, JS) and then having the NETWORK: * section at the end - this way all the dynamic content (AJAX) is always retrieved from the network. The application fails "gracefully" if the requests fail, by displaying some fake content.

With the above setup, the following happens:

If I run the application while online, everything works ;)

If I disable the WiFi on iPad (pure offline mode), everything works as expected - the application falls back to the offline content

If I connect to the network again, but take the static-content server offline (the one that has everything cached), the application won't start; after spending a while in splash-screen, it shows me the a popup with <app> could not be opened because it could not connect to the server.; I can either choose Close or Retry.

The point 3 of the above is the one that drives me crazy because it was the only reason I started fiddling with application cache. Why doesn't the iPad web app fall back to cached content if the manifest file is not reachable? (not 404, the server is offline)

Is the answer to HTML5 iphone offline webapp completely incorrect? If not, how can I achieve this behavior on iPad?


问:
Python Flask session for multiple instances
How can I make a flask session work across multiple instances of containers using Kubernetes? Or does Kubernetes always maintain the same container for a given session?</p>

答:
Default Flask sessions are stored client-side (in the browser) as a cookie and cryptographically signed to prevent tampering. Every request to your Flask application is accompanied by this cookie. Therefore, if all running containers have the same app (at least the same secret key used for signing), then they should all have access to the same session data.

Note:

This is cryptographically signed, but it is not encrypted, so don't store sensitive information in the session

Flask-Session can be installed for server-side session support


问:
Unable to fit text within div bubble
this is my first post on stack. I am having trouble getting my about section to fit in its proper bubble. You can see in the image as to what I am talking about. This is still a work in progress obviously so it may not look correct on all displays.(if you have tips to adjust for screen resolution please let me know as well. Thank you :) )

* {
  margin: 0;
  padding: 0;
  box-sizing: border-box;
  font-family: 'Share Tech Mono', monospace;
  text-transform: uppercase;
}

main {
  min-height: 100vh;
  background: linear-gradient(to right, #43cea2, #185a9d);
  display: flex;
  align-items: center;
  justify-content: center;
}

.glass {
  background: white;
  min-height: 80vh;
  width: 60%;
  background: linear-gradient(to right bottom, rgba(255, 255, 255, 0.3), rgba(255, 255, 255, 0.1));
  border-radius: 2rem;
  display: flex;
}

.dashboard {
  flex: 1;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: space-evenly;
  text-align: center;
  background: linear-gradient(to right bottom, rgba(255, 255, 255, 0.2), rgba(255, 255, 255, 0.1));
  border-radius: 2rem;
}

ul {
  list-style: none;
  text-decoration: none;
}

.link {
  display: flex;
  margin: 2rem 0rem;
  padding: 1rem 5rem;
  align-items: center;
}

.link a {
  padding: 0rem 2rem;
  color: white;
  text-transform: uppercase;
  text-decoration: none;
  font-size: 25px;
  font-weight: 200px;
}

.bubble .link {
  display: block;
  background: linear-gradient(to right bottom, rgba(255, 255, 255, 0.2), rgba(255, 255, 255, 0.2));
  border-radius: 2rem;
  position: relative;
  color: white;
}

.bubble .link:hover {
  color: white;
  background: rgba(225, 255, 255, 0.2);
  letter-spacing: .2px;
}

.main {
  flex: 2;
}

.main h1 {
  color: white;
  text-transform: uppercase;
  opacity: 0.8;
  font-weight: 600;
  font-size: 40px;
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translateX(-20%) translateY(-50%);
}

.name {
  font-weight: bold;
  font-size: 40px;
  padding: 2rem;
  color: white;
}

.icons a {
  text-decoration: none;
}

.icons a:hover {
  color: white;
  opacity: 0.5;
}

.mainabout {
  flex: 2;
}

.about-bubble {
  background: white;
  min-height: 60vh;
  width: 100%;
  background: linear-gradient(to right bottom, rgba(255, 255, 255, 0.3), rgba(255, 255, 255, 0.1));
  border-radius: 2rem;
  display: flex;
  transform: translateX(5%) translateY(1%);
}

.mainabout p {
  font-size: 15px;
  color: white;
  position: relative;
  line-height: 20px;
  transform: translateX(2%) translateY(5%);
}

.mainabout h1 {
  color: white;
  padding: 2rem;
  font-size: 40px;
  position: relative;
  text-align: center;
  transform: translateY(10%);
}

.next-bttn {
  color: #34e89e;
  position: relative;
  transform: translateX(-70%) translateY(93%);
  border-radius: 5px;
}

.next-bttn button {
  color: #43cea2;
  position: relative;
  border-radius: 5px;
  padding: 10px 20px;
  opacity: 0.5;
  font-weight: bold;
  border: none;
  background-color: transparent;
}
```
<pre class="lang-html prettyprint-override"><code><body>
  <main>
    <section class=" glass">
      <div class=" dashboard">
        <div class="name" <h1>First Name Last Name</h1>
        </div>
        <div class="bubble">
          <ul>
            <div class="links">
              <div class="link">
                <li>about</li>
              </div>

              <div class="link">
                <li>work</li>
              </div>

              <div class="link">
                <li>skills</li>
              </div>

              <div class="link">
                <li>resume</li>
              </div>

              <div class="link">
                <li>contact</li>
              </div>

          </ul>
          </div>
          <div class="icons">

              <img src="32px.png" alt="" width="32" height="32" />

              <img src="32x32.png" alt="" width="32" height="32" />

              <img src="codepen.png" alt="" width="32" height="32" />
          </div>
        </div>
      </div>
      <div class="mainabout">
        <h1>About Me</h1>

        <div class="about-bubble">
          <p>Lorem ipsum dolor sit amet consectetur adipisicing elit. Quae odio non ipsa perspiciatis vel perferendis at obcaecati repellat molestiae, autem quas dolores nostrum totam corrupti quod beatae, accusamus commodi enim?</p>
        </div>
      </div>
      <div class="next-bttn">
        <form action="work.html">
          <button style="background: white;">Next</button>
        </form>
      </div>
    </section>
</code>```

webpage

答:
Add the following to that bubble div in its respective CSS:

replacethisforbubble {
    word-break: break-all;
}
```

Try this, if it doesn't work let me know.

Title: Unable to fit text within div bubble

Body:
this is my first post on stack. I am having trouble getting my about section to fit in its proper bubble. You can see in the image as to what I am talking about. This is still a work in progress obviously so it may not look correct on all displays.(if you have tips to adjust for screen resolution please let me know as well. Thank you :) )

* {
  margin: 0;
  padding: 0;
  box-sizing: border-box;
  font-family: 'Share Tech Mono', monospace;
  text-transform: uppercase;
}

main {
  min-height: 100vh;
  background: linear-gradient(to right, #43cea2, #185a9d);
  display: flex;
  align-items: center;
  justify-content: center;
}

.glass {
  background: white;
  min-height: 80vh;
  width: 60%;
  background: linear-gradient(to right bottom, rgba(255, 255, 255, 0.3), rgba(255, 255, 255, 0.1));
  border-radius: 2rem;
  display: flex;
}

.dashboard {
  flex: 1;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: space-evenly;
  text-align: center;
  background: linear-gradient(to right bottom, rgba(255, 255, 255, 0.2), rgba(255, 255, 255, 0.1));
  border-radius: 2rem;
}

ul {
  list-style: none;
  text-decoration: none;
}

.link {
  display: flex;
  margin: 2rem 0rem;
  padding: 1rem 5rem;
  align-items: center;
}

.link a {
  padding: 0rem 2rem;
  color: white;
  text-transform: uppercase;
  text-decoration: none;
  font-size: 25px;
  font-weight: 200px;
}

.bubble .link {
  display: block;
  background: linear-gradient(to right bottom, rgba(255, 255, 255, 0.2), rgba(255, 255, 255, 0.2));
  border-radius: 2rem;
  position: relative;
  color: white;
}

.bubble .link:hover {
  color: white;
  background: rgba(225, 255, 255, 0.2);
  letter-spacing: .2px;
}

.main {
  flex: 2;
}

.main h1 {
  color: white;
  text-transform: uppercase;
  opacity: 0.8;
  font-weight: 600;
  font-size: 40px;
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translateX(-20%) translateY(-50%);
}

.name {
  font-weight: bold;
  font-size: 40px;
  padding: 2rem;
  color: white;
}

.icons a {
  text-decoration: none;
}

.icons a:hover {
  color: white;
  opacity: 0.5;
}

.mainabout {
  flex: 2;
}

.about-bubble {
  background: white;
  min-height: 60vh;
  width: 100%;
  background: linear-gradient(to right bottom, rgba(255, 255, 255, 0.3), rgba(255, 255, 255, 0.1));
  border-radius: 2rem;
  display: flex;
  transform: translateX(5%) translateY(1%);
}

.mainabout p {
  font-size: 15px;
  color: white;
  position: relative;
  line-height: 20px;
  transform: translateX(2%) translateY(5%);
}

.mainabout h1 {
  color: white;
  padding: 2rem;
  font-size: 40px;
  position: relative;
  text-align: center;
  transform: translateY(10%);
}

.next-bttn {
  color: #34e89e;
  position: relative;
  transform: translateX(-70%) translateY(93%);
  border-radius: 5px;
}

.next-bttn button {
  color: #43cea2;
  position: relative;
  border-radius: 5px;
  padding: 10px 20px;
  opacity: 0.5;
  font-weight: bold;
  border: none;
  background-color: transparent;
}

        <div class="name"
First Name Last Name

about

work

skills

resume

contact

About Me

Lorem ipsum dolor sit amet consectetur adipisicing elit. Quae odio non ipsa perspiciatis vel perferendis at obcaecati repellat molestiae, autem quas dolores nostrum totam corrupti quod beatae, accusamus commodi enim?

        <form action="work.html">
          <button style="background: white;">Next</button>
        </form>

webpage

Body:
Add the following to that bubble div in its respective CSS:

replacethisforbubble {
    word-break: break-all;
}

Try this, if it doesn't work let me know.


问:
How to connect to MongoDB replicaset on Kubernetes
I have deployed bitnami's Mongodb helm chart in the replicaset mode on a K8s cluster, using this minimal config (for now):

```<code>  architecture: replicaset
  auth:
    enabled: false
</code>```

Now I have two replicas (one primary and one secondary, allegedly) and an arbiter (no data, just voting rights). Additionally, I got two services: appname-mongodb-headless, appname-mongodb-arbiter-headless. However, the MongoDB docs specify the connection string in case of replicaset installations as mongodb://mongodb0.example.com:27017,mongodb1.example.com:27017,mongodb2.example.com:27017/?replicaSet=myRepl.

I can use mongodb://appname-mongodb-headless:27017 to connect to the db, but is it the "real experience" (i.e. highly available, etc)?

Do I need to specify the replicaset name (as in the example) and how do I find out what it is?

If the current services are enough, do I need to include the arbiter in the connection string?

Or should I create separate services for each replica and build the recommended connection string?
```<code>externalAccess:
  enabled: true
  autoDiscovery:
    enabled: true
</code>```

I will eventually enable authentication after sorting out this part of the connection. What is this replicaSetKey ("Key used for authentication in the replicaset"), and where do I use it?

I found this similar question. It is for another chart, but it suggests me that some combination of the headless services should be enough. Nonetheless, it doesn't answer all aspects of my question.

答:
Adding to Marcos' answer, there is another URI format called DNS Seed List Connection Format from 3.6+ which you can use with a single host name of  your headless service and still take advantage of the replicaset.

mongodb+srv://server.example.com/

It is described here: https://docs.mongodb.com/manual/reference/connection-string/#dns-seed-list-connection-format

Body:
I have deployed bitnami's Mongodb helm chart in the replicaset mode on a K8s cluster, using this minimal config (for now):

  architecture: replicaset
  auth:
    enabled: false

Now I have two replicas (one primary and one secondary, allegedly) and an arbiter (no data, just voting rights). Additionally, I got two services: appname-mongodb-headless, appname-mongodb-arbiter-headless. However, the MongoDB docs specify the connection string in case of replicaset installations as mongodb://mongodb0.example.com:27017,mongodb1.example.com:27017,mongodb2.example.com:27017/?replicaSet=myRepl.

I can use mongodb://appname-mongodb-headless:27017 to connect to the db, but is it the "real experience" (i.e. highly available, etc)?

Do I need to specify the replicaset name (as in the example) and how do I find out what it is?

If the current services are enough, do I need to include the arbiter in the connection string?

Or should I create separate services for each replica and build the recommended connection string?

externalAccess:
  enabled: true
  autoDiscovery:
    enabled: true

I will eventually enable authentication after sorting out this part of the connection. What is this replicaSetKey ("Key used for authentication in the replicaset"), and where do I use it?

I found this similar question. It is for another chart, but it suggests me that some combination of the headless services should be enough. Nonetheless, it doesn't answer all aspects of my question.


问:
Jmeter assertions on random controller
Will there be a difference in results when we add response assertion, duration assertion to controllers instead of thread?</p>

答:
I don't know what "thread" is in your world, but Assertions obey JMeter Scoping Rules so you can apply one or more assertions to:

a single Sampler

several Samplers

all Samplers in the Thread Group

all Samplers in the Test Plan

Here is the image from the How to Use JMeter Assertions in Three Easy Steps article showing how do scoping rules work:

Title: Jmeter assertions on random controller


问:
Apple sign in get user data with access token
I have a question about apple sign in. I just implemented an apple sign in, and I found that I received an identity token, access token, and refresh token. It seems that the identity token has user information in the json web token. I am wondering how I can use the access symbol to receive user information? Facebook and also Google has own endpoint where if I send in that endpoint access token I retrieve user data. Does apple sign in has something similar?

Thanks for the information

答:
To get the user_data(email,name) I am using the following code:

```<code>if id_token:
            decoded = jwt.decode(id_token, "", verify=False)
            response_data.update(
                {"email": decoded["email"], "name": decoded["name"]}
            ) if "email" in decoded else None
            response_data.update({"uid": decoded["sub"]}) if "sub" in decoded else None
</code>```

Here, after successfully receiving id token from "https://appleid.apple.com/auth/token" just decode the id_token and get data from it using the appropiriate fields.
Hope this solves your problem of how to get user data from apple social login.

Body:
To get the user_data(email,name) I am using the following code:

if id_token:
            decoded = jwt.decode(id_token, "", verify=False)
            response_data.update(
                {"email": decoded["email"], "name": decoded["name"]}
            ) if "email" in decoded else None
            response_data.update({"uid": decoded["sub"]}) if "sub" in decoded else None

Here, after successfully receiving id token from "https://appleid.apple.com/auth/token" just decode the id_token and get data from it using the appropiriate fields.
Hope this solves your problem of how to get user data from apple social login.


问:
How to forward query parameters to external identity provider using Keycloak?
While creating an identity provider (IdP) in the Keycloak there is an option available to forward the query params to the external IdP. How can I use that?

I want to forward, say, launch parameter to the external IdP. I mentioned the launch in the Forwarded Query Parameters field in Keycloak configuration page. I'm using an app on my locahost:9090 protected by Keyclaok. When I access http://localhost:9090?launch=abc this param is not forwarding to the external IdP. I'm using keycloak-spring-boot-starter for our Spring Boot app.

Also from the code of Keycloak, I have seen that there is some prefix is attached to the forwarded parameter i.e. client_request_param_ so I tried using http://localhost:9090?client_request_param_launch=abc but no luck.

AuthorizationEndpoint.LOGIN_SESSION_NOTE_ADDITIONAL_REQ_PARAMS_PREFIX = client_request_param_

```<code>String forwardParameterConfig = getConfig().getForwardParameters() != null ? getConfig().getForwardParameters(): "";
List<String> forwardParameters = Arrays.asList(forwardParameterConfig.split("\\s*,\\s*"));
for(String forwardParameter: forwardParameters) {
    String name = AuthorizationEndpoint.LOGIN_SESSION_NOTE_ADDITIONAL_REQ_PARAMS_PREFIX + forwardParameter.trim();
    String parameter = request.getAuthenticationSession().getClientNote(name);
    if(parameter != null && !parameter.isEmpty()) {
        uriBuilder.queryParam(forwardParameter, parameter);
    }
}
</code>```

P.S: I'm using Keycloak 7.0.0.

答:
Just in case anyone encounter this. As implemented in the source code, there is a maximum limit of 5 additional query params (declared as constants: ADDITIONAL_REQ_PARAMS_MAX_MUMBER) for the processing of additional query params.

The additional query params are excluded from the subset of declared known req params (KNOWN_REQ_PARAMS declared here).

Example,

```<code>https://<domain>/openid-connect/auth?

scope=xx

&response_type=code

&client_id=xxx

&redirect_uri=xxx

&state=xxx

&addParam1=xx

&addParam2=xx

&addParam3=xx

&addParam4=xx

&addParam5=xx

&addParam6=xx (not processed)

&addParam7=xx (not processed)
</code>```

Referring to the source code, the extractAdditionalReqParams method will only process up to addParam5 and stop afterwards.

Body:
While creating an identity provider (IdP) in the Keycloak there is an option available to forward the query params to the external IdP. How can I use that?

I want to forward, say, launch parameter to the external IdP. I mentioned the launch in the Forwarded Query Parameters field in Keycloak configuration page. I'm using an app on my locahost:9090 protected by Keyclaok. When I access http://localhost:9090?launch=abc this param is not forwarding to the external IdP. I'm using keycloak-spring-boot-starter for our Spring Boot app.

Also from the code of Keycloak, I have seen that there is some prefix is attached to the forwarded parameter i.e. client_request_param_ so I tried using http://localhost:9090?client_request_param_launch=abc but no luck.

AuthorizationEndpoint.LOGIN_SESSION_NOTE_ADDITIONAL_REQ_PARAMS_PREFIX = client_request_param_

String forwardParameterConfig = getConfig().getForwardParameters() != null ? getConfig().getForwardParameters(): "";
List<String> forwardParameters = Arrays.asList(forwardParameterConfig.split("\\s*,\\s*"));
for(String forwardParameter: forwardParameters) {
    String name = AuthorizationEndpoint.LOGIN_SESSION_NOTE_ADDITIONAL_REQ_PARAMS_PREFIX + forwardParameter.trim();
    String parameter = request.getAuthenticationSession().getClientNote(name);
    if(parameter != null && !parameter.isEmpty()) {
        uriBuilder.queryParam(forwardParameter, parameter);
    }
}

P.S: I'm using Keycloak 7.0.0.

Body:
Just in case anyone encounter this. As implemented in the source code, there is a maximum limit of 5 additional query params (declared as constants: ADDITIONAL_REQ_PARAMS_MAX_MUMBER) for the processing of additional query params.

The additional query params are excluded from the subset of declared known req params (KNOWN_REQ_PARAMS declared here).

Example,

https://<domain>/openid-connect/auth?

scope=xx

&response_type=code

&client_id=xxx

&redirect_uri=xxx

&state=xxx

&addParam1=xx

&addParam2=xx

&addParam3=xx

&addParam4=xx

&addParam5=xx

&addParam6=xx (not processed)

&addParam7=xx (not processed)

Referring to the source code, the extractAdditionalReqParams method will only process up to addParam5 and stop afterwards.


问:
Unable to correctly scrape tables from webpage
I am trying to scrape data table for those 3 stages in the picture(stages marked in red).

unfortunately, the code I've written is getting first table only for some reason. I have already tired other way round by getting Xpath for those individual tables but that doesn't quite work as it gave similar problem there too. Thanks in advance for your help.

website link: https://mcchip-dkr.com/en/chiptuning-database?fid=3222&view=carselector#0

```<code>for i in range(0, len(stage_button)):
    print("pointer is ", pointer)
    print("CLick on next stage\n")
    time.sleep(2)
    stage_button[pointer].click()
    time.sleep(5)
    table_li_tag = driver.find_element(By.CSS_SELECTOR, "li.uk-active")

    table_pointer = table_li_tag.find_element(By.XPATH, "//table")
    print(table_pointer.get_attribute("outerHTML"))
    pointer = pointer + 1
    if pointer > len(stage_button):
        break

</code>```

答:
I have used Selenium and tried this way. It fetched me output:

```<code>driver.get("https://mcchip-dkr.com/en/chiptuning-database?fid=3222&view=carselector#0")
time.sleep(5)
for i in range(3):
    driver.find_element(By.XPATH, f"//div[@id='mcw_datasheet']//li[@data-index={i}]").click()
    time.sleep(2)
    stage = driver.find_element(By.XPATH, f"(//ul[@id='#switcher1']//table){str([i+1])}").text
    print(stage)
    print("\n")
</code>```

The only element left out is (I am not sure what the metric is): 3.999,00 € for each stage. I hope you can figure it out.

Here is the ouput:

```<code>Stock Optimized Diference
750 hp / 551 kW 780 hp / 574 kW 30 hp / 22 kW
690 Nm 725 Nm 35 Nm
350 Km/h 353 Km/h 3 Km/h

Stock Optimized Diference
750 hp / 551 kW 790 hp / 581 kW 40 hp / 29 kW
690 Nm 735 Nm 45 Nm

Stock Optimized Diference
750 hp / 551 kW 800 hp / 588 kW 50 hp / 37 kW
690 Nm 740 Nm 50 Nm

Process finished with exit code 0
</code>```

I have used just prints, but you may arrange to have the table stored in list and/or in pandas table if you like to do so.

Body:
I am trying to scrape data table for those 3 stages in the picture(stages marked in red).

unfortunately, the code I've written is getting first table only for some reason. I have already tired other way round by getting Xpath for those individual tables but that doesn't quite work as it gave similar problem there too. Thanks in advance for your help.

website link: https://mcchip-dkr.com/en/chiptuning-database?fid=3222&view=carselector#0

for i in range(0, len(stage_button)):
    print("pointer is ", pointer)
    print("CLick on next stage\n")
    time.sleep(2)
    stage_button[pointer].click()
    time.sleep(5)
    table_li_tag = driver.find_element(By.CSS_SELECTOR, "li.uk-active")

    table_pointer = table_li_tag.find_element(By.XPATH, "//table")
    print(table_pointer.get_attribute("outerHTML"))
    pointer = pointer + 1
    if pointer > len(stage_button):
        break

Body:
I have used Selenium and tried this way. It fetched me output:

driver.get("https://mcchip-dkr.com/en/chiptuning-database?fid=3222&view=carselector#0")
time.sleep(5)
for i in range(3):
    driver.find_element(By.XPATH, f"//div[@id='mcw_datasheet']//li[@data-index={i}]").click()
    time.sleep(2)
    stage = driver.find_element(By.XPATH, f"(//ul[@id='#switcher1']//table){str([i+1])}").text
    print(stage)
    print("\n")

The only element left out is (I am not sure what the metric is): 3.999,00 € for each stage. I hope you can figure it out.

Here is the ouput:

Stock Optimized Diference
750 hp / 551 kW 780 hp / 574 kW 30 hp / 22 kW
690 Nm 725 Nm 35 Nm
350 Km/h 353 Km/h 3 Km/h

Stock Optimized Diference
750 hp / 551 kW 790 hp / 581 kW 40 hp / 29 kW
690 Nm 735 Nm 45 Nm

Stock Optimized Diference
750 hp / 551 kW 800 hp / 588 kW 50 hp / 37 kW
690 Nm 740 Nm 50 Nm

Process finished with exit code 0

I have used just prints, but you may arrange to have the table stored in list and/or in pandas table if you like to do so.


问:
When do I need to worry about thread-safety in an iOS application?
When writing the usual view controller code, can I assume that this will only be called from a single event-loop thread? What kind of classes do I need to make thread-safe? What are the usual situations where multiple threads are involved?</p>

答:
The concurrency programming guide is good. Here are some super important things to keep in mind.

– You should only update UI from the main thread. This can get you in subtle ways...

– NSNotifications will be received in the thread from which they are fired. So if you launch a thread and subscribe to a NSNotification to trigger a UI action, you should check what thread you're on when you get it. If it's not on the main thread use NSObject's performSelectorOnMainThread: withObject:waitUntilDone: to get it on the main thread.

– If you're doing some drawing into a non-ui context, I believe core graphics is now thread safe. (I believe CATiledLayer does some clever things because of this)

– Generally for view controllers, the only event loop you should think about is the one on the main thread. Think twice before making your own event loop on another thread.


问:
define a generic property in non-generic base class
I dont think what I am trying to do is possible; is there a way to actually make this work?

There is a Base class from which a variety of different classes are derived. Derived classes can be generic or not; instances of the derived classes are added to a collection of type Base in WindowViewModel. The Base class has a collection of Options that are accessed by the WindowViewModel.

The issue is: the IOption interface declares a return type of Func<object, bool> MyFunc but the return type of MyFunc needs to be Func<T, bool> for the generic class method RunIt() and for the assignment in MyClass to work. I could make the IOption generic, but then the Base class would need to be generic, and then the WindowViewModel.ViewModels would also need to be redefined somehow. I dont want to make the Base generic as introducing generics there just makes everything else a real mess.

Question: is there a different way to declare MyFunc in IOption without using generics to allow assignment of Func<T,bool> in MyClass ?

```<code>public interface IOption
{
    public string Description {get; set;}
    public Expression<Func<object,bool>> MyFunc { get; set; }
}

public class Option : IOption
{
    public string Description {get; set;}
    public Expression<Func<object,bool>> MyFunc { get; set; }
}

public abstract class Base
{
    public abstract ObservableCollection<Option> Options { get; set; }
    public abstract Option SelectedOption { get; set; }

    public abstract void RunIt();
}

public class Generic<T> : Base
{
    private DBContext _context;

    public override ObservableCollection<Option> Options { get; set; }
    public override Option SelectedOption { get; set; }

    public Generic()
       : base()
    {
        Options = new ObservableCollection<Option>();
    }
    public override void RunIt()
    {
        var result = _context.Set<T>().Where(SelectedOption?.MyFunc);
        // process result
    }
}

public class MyClass : Generic<MyType>
{
    public MyClass
       : base()
    {
        Func<MyType,bool> expression = t => t.MyDescription = "Hello World";
        Options.Add(new Option("Hi", expression));  // fail to compile type mismatch
        SelectedOption = Options.First();
    }
}

public class Special : Base
{
// do something else
}

public class WindowViewModel
{
   public WindowViewModel ()
   {
     MyViewModels = new ObservableCollection<Base>();
     MyViewModels.Add(new Special());
     MyViewModels.Add(new MyClass());
   }

   public ObservableCollection<Base> MyViewModels {get; set;}
   public Base SelectedViewModel { get; set; }

   public void DoRunIt()
   {
      SelectedViewModel.RunIt();
   }
}
</code>```

one of the things I did try that compiles but throws runtime exception when used, is

```<code>Func<MyType,bool> expression = t => t.MyDescription = "Hello World";
MyFunc = t => expression((MyType)t);
</code>```

答:
Question: is there a different way to declare MyFunc in IOption without using generics to allow assignment of Func<T,bool> in MyClass ?

No, I don't believe that is possible. You can have generic methods in a non generic type, though.

However, there is an option that might work for you.
You state

I dont want to make the Base generic as introducing generics there just makes everything else a real mess.

How about having both?

```<code>public abstract class Base<T>
{
    public abstract ObservableCollection<Option<T>> Options { get; set; }
    public abstract Option<T> SelectedOption { get; set; }

    public abstract void RunIt();
}

public abstract class Base : Base<object> { }
</code>```

Body:
I dont think what I am trying to do is possible; is there a way to actually make this work?

There is a Base class from which a variety of different classes are derived. Derived classes can be generic or not; instances of the derived classes are added to a collection of type Base in WindowViewModel. The Base class has a collection of Options that are accessed by the WindowViewModel.

The issue is: the IOption interface declares a return type of Func<object, bool> MyFunc but the return type of MyFunc needs to be Func<T, bool> for the generic class method RunIt() and for the assignment in MyClass to work. I could make the IOption generic, but then the Base class would need to be generic, and then the WindowViewModel.ViewModels would also need to be redefined somehow. I dont want to make the Base generic as introducing generics there just makes everything else a real mess.

Question: is there a different way to declare MyFunc in IOption without using generics to allow assignment of Func<T,bool> in MyClass ?

public interface IOption
{
    public string Description {get; set;}
    public Expression<Func<object,bool>> MyFunc { get; set; }
}

public class Option : IOption
{
    public string Description {get; set;}
    public Expression<Func<object,bool>> MyFunc { get; set; }
}

public abstract class Base
{
    public abstract ObservableCollection<Option> Options { get; set; }
    public abstract Option SelectedOption { get; set; }

    public abstract void RunIt();
}

public class Generic<T> : Base
{
    private DBContext _context;

    public override ObservableCollection<Option> Options { get; set; }
    public override Option SelectedOption { get; set; }

    public Generic()
       : base()
    {
        Options = new ObservableCollection<Option>();
    }
    public override void RunIt()
    {
        var result = _context.Set<T>().Where(SelectedOption?.MyFunc);
        // process result
    }
}

public class MyClass : Generic<MyType>
{
    public MyClass
       : base()
    {
        Func<MyType,bool> expression = t => t.MyDescription = "Hello World";
        Options.Add(new Option("Hi", expression));  // fail to compile type mismatch
        SelectedOption = Options.First();
    }
}

public class Special : Base
{
// do something else
}

public class WindowViewModel
{
   public WindowViewModel ()
   {
     MyViewModels = new ObservableCollection<Base>();
     MyViewModels.Add(new Special());
     MyViewModels.Add(new MyClass());
   }

   public ObservableCollection<Base> MyViewModels {get; set;}
   public Base SelectedViewModel { get; set; }

   public void DoRunIt()
   {
      SelectedViewModel.RunIt();
   }
}

one of the things I did try that compiles but throws runtime exception when used, is

Func<MyType,bool> expression = t => t.MyDescription = "Hello World";
MyFunc = t => expression((MyType)t);

Body:
Question: is there a different way to declare MyFunc in IOption without using generics to allow assignment of Func<T,bool> in MyClass ?

No, I don't believe that is possible. You can have generic methods in a non generic type, though.

However, there is an option that might work for you.
You state

I dont want to make the Base generic as introducing generics there just makes everything else a real mess.

How about having both?

public abstract class Base<T>
{
    public abstract ObservableCollection<Option<T>> Options { get; set; }
    public abstract Option<T> SelectedOption { get; set; }

    public abstract void RunIt();
}

public abstract class Base : Base<object> { }


问:
How do I use react router with relay?
I am struggling with react-router and relay integration.

As of now, I stick to this example

It uses the useLazyLoadQuery hook, and although everything seems to work just fine, I also see another way of doing this: usePreloadedQuery.

The docs say that the useLazyLoadQuery hook

can trigger multiple nested or waterfalling round trips if used without caution and waits until render to start a data fetch (when it can usually start a lot sooner than render), thereby degrading performance. Instead, prefer usePreloadedQuery.

However, it is not clear how to integrate this with react-router and obviously, I do not want to reinvent my own router...

Another thing I noticed is that usePreloadedQuery should be used in conjunction with
useQueryLoader;
At the same time in docs they load it directly by just calling loadQuery();

So I am not sure which way is preferred.

I ended up with a wrapper like this:

```<code>const WrappedHomePage = () => {
  const [queryRef, loadQuery] = useQueryLoader(HomePageQuery);

  // does calling it like this make any sense at all?
  useMemo(() => {
    loadQuery();
  }, [loadQuery]);

  return <HomePage queryRef={queryRef} />;
};

const HomePage = ({ queryRef }) => {
  const query = usePreloadedQuery(
    graphql`
      query HomePageQuery {
        ...HomePageContainer_repository
      }
    `,
    queryRef
  );

  return (
    <div>
      <HomePageContainer fragmentRef={query} />
    </div>
  );
};
</code>```

答:
According to the Relay docs:

The component-based approach of React Router v4 does not readily allow for aggregating the data requirements for nested routes, and as such does not readily permit an approach that will avoid request waterfalls from nesting QueryRenderer components.

So basically using react-router with Relay is out :(

Relay recommends using Found as an alternative router, which is similar to react-router. Found integrates well with Relay using the found-relay package.

Title: How do I use react router with relay?

Body:
I am struggling with react-router and relay integration.

As of now, I stick to this example

It uses the useLazyLoadQuery hook, and although everything seems to work just fine, I also see another way of doing this: usePreloadedQuery.

The docs say that the useLazyLoadQuery hook

can trigger multiple nested or waterfalling round trips if used without caution and waits until render to start a data fetch (when it can usually start a lot sooner than render), thereby degrading performance. Instead, prefer usePreloadedQuery.

However, it is not clear how to integrate this with react-router and obviously, I do not want to reinvent my own router...

Another thing I noticed is that usePreloadedQuery should be used in conjunction with
useQueryLoader;
At the same time in docs they load it directly by just calling loadQuery();

So I am not sure which way is preferred.

I ended up with a wrapper like this:

const WrappedHomePage = () => {
  const [queryRef, loadQuery] = useQueryLoader(HomePageQuery);

  // does calling it like this make any sense at all?
  useMemo(() => {
    loadQuery();
  }, [loadQuery]);

  return <HomePage queryRef={queryRef} />;
};

const HomePage = ({ queryRef }) => {
  const query = usePreloadedQuery(
    graphql`
      query HomePageQuery {
        ...HomePageContainer_repository
      }
    `,
    queryRef
  );

  return (

      <HomePageContainer fragmentRef={query} />

  );
};


问:
Make LaTeX left-aligned in css like everthing else when exporting from org-mode
I would like to left-align the LaTeX equation when exporting from org-mode using org-html-export-to-html, as it looks a tad out-of-place in the setup below.

In case the stylesheet itself is required: https://github.com/shadowrylander/settings/blob/main/src/styles/primary/syvl.css

Unfortunately, I'm not sure how to give a minimal, reproducible example here.

答:
From 13.9.10 Math formatting in HTML export:

```<code>#+HTML_MATHJAX: align: left
</code>```

Found when analyzing the top half of the html file and finding the following:

```

Body:
From 13.9.10 Math formatting in HTML export:

#+HTML_MATHJAX: align: left

Found when analyzing the top half of the html file and finding the following:

<script type="text/x-mathjax-config">
    MathJax.Hub.Config({
        displayAlign: "left",
        displayIndent: "0em",

        "HTML-CSS": { scale: 100,
                        linebreaks: { automatic: "false" },
                        webFont: "TeX"
                       },
        SVG: {scale: 100,
              linebreaks: { automatic: "false" },
              font: "TeX"},
        NativeMML: {scale: 100},
        TeX: { equationNumbers: {autoNumber: "AMS"},
               MultLineWidth: "85%",
               TagSide: "right",
               TagIndent: ".8em"
             }
});
</script>


问:
can someone explain how split("(?<=\\G.{" + 2 + "})") in java splits the spring in 2 characters each?
```<code>    String s = "()[]{}";
    String[] array = s.split("(?<=\\G.{" + 2 + "})");

    for(int i = 0; i< array.length; i++){
        System.out.println(array[i]);
    }
</code>```

Output:
()
[]
{}

I just don't understand the regex.

答:
Let's break it down:

"(?<=\\G.{" + 2 + "})" is just a silly way to write "(?<=\\G.{2})".

.{2} is 'any 2 characters'. . is 'any character', and {2} is 'the thing before this, exactly twice.

Now for the fancypants features here: \\G is 'the end of the previous match, which is a thing that only makes sense in the context of repeatedly calling find() on a matcher.. and split. Thus, \\G.{2} matches exactly 2 characters that immediately follow the previous match.

The regexp you pass to split actually identifies the separator. Whatever you match will not be part of the result: "a,b,c".split(",") ends up not returning any commas, so .split("\\G.{2}") would eat up everything and end up returning a few empty strings. Which is why there's one more thing we didn't cover:

?<= is so-called 'positive lookbehind'.

To explain that, we first need to delve into how regexes work. Regexes consist of a series of 'nodes'. Each node does 2 utterly unrelated things: It either matches or it doesn't, and it 'moves the pointer' some slots to the right. The regexp "a" consists of a single node, which matches if the thing 'at the pointer' is, exactly, the character "a", and will fail to match if there's anything else there. If it matches, it moves the cursor one to the right.

Some nodes don't move the cursor. They match or fail but don't 'consume' anything. For example, ^ matches if you're at the start of a string and fails otherwise, but it doesn't consume anything ('start of the string' is not a consumable concept, that has no width. There is no 'start' character). \\b (word break) is similar.

lookahead and lookbehind are tools to make your own non-consuming nodes. They consist of two things:

Which lookX you want. There are 4 types: Positive/Negative Lookahead/Lookbehind.

A regexp to match.

negative means: It fails if the regexp is there (positive means: it fails if the regexp is not there). lookahead means that the regexp needs to match at the cursor looking to the right, and lookbehind means that the regexp needs to match at the cursor looking left.

?<= selects positive lookbehind, the rest is therefore the regexp to look for - it no longer consumes.

Now you can put it all together:

This regexp 'matches' (consumes) nothing, because it's entirely a positive lookbehind construction. That explains why all the characters are returned (your array variable) - remember, in the more usual "a,b,c".split(",") style mode, stuff disappears (the commas).

Instead, this regexp matches the space in between every 2 characters.

For what its worth, this is stupidly convoluted. This is a horrible, horrible way to separate a string into consecutive character pairs. I think someone is trying to show off, or this is some sort of 'ha! Check out what regexes can do!' puzzler thing. Fair enough.

Body:
    String s = "()[]{}";
    String[] array = s.split("(?<=\\G.{" + 2 + "})");

    for(int i = 0; i< array.length; i++){
        System.out.println(array[i]);
    }

Output:
()
[]
{}

I just don't understand the regex.


问:
SQL - Return The Greater of a Partition
I have the following table -

My goal is to return the Company/ID row with the highest "count" respective to a partition done by the ID.

So the expected output should look like this :

My current code returns a count partitioned on all ids. I just want it to return the one with the highest count.

Current code -

```<code>select distinct Company, Id, count(*) over (partition by ID)
from table1
where company in ("Facebook","Apple")
</code>```

My output:

答:
We can use ROW_NUMBER here along with an aggregation query:

WITH cte AS (
    SELECT Company, ID, COUNT(*) AS Count,
           ROW_NUMBER() OVER (PARTITION BY Company ORDER BY COUNT(*) DESC) rn
    FROM table1
    GROUP BY Company, ID
)

SELECT Company, ID, Count
FROM cte
WHERE rn = 1;
```

Here is a running demo for MySQL.

Title: SQL - Return The Greater of a Partition

Body:
I have the following table -

My goal is to return the Company/ID row with the highest "count" respective to a partition done by the ID.

So the expected output should look like this :

My current code returns a count partitioned on all ids. I just want it to return the one with the highest count.

Current code -

select distinct Company, Id, count(*) over (partition by ID)
from table1
where company in ("Facebook","Apple")

My output:

Body:
We can use ROW_NUMBER here along with an aggregation query:

WITH cte AS (
    SELECT Company, ID, COUNT(*) AS Count,
           ROW_NUMBER() OVER (PARTITION BY Company ORDER BY COUNT(*) DESC) rn
    FROM table1
    GROUP BY Company, ID
)

SELECT Company, ID, Count
FROM cte
WHERE rn = 1;

Here is a running demo for MySQL.


问:
Error: wsl.exe exited with code 4294967295 on Installing Rancher Desktop
I am getting the below error when installing the latest stable Rancher Desktop in my Virtual Machine.

Could someone please help?

Error:

Error: wsl.exe exited with code 4294967295

Command:

```<code>wsl --distribution rancher-desktop --exec mkdir -p /mnt/wsl/rancher-desktop/run/data
</code>```

Logs:

2022-02-02T09:58:39.490Z: Running command wsl --distribution
rancher-desktop --exec wslpath -a -u
C:\Users\VIVEK~1.NUN\AppData\Local\Temp\rd-distro-gGd3SG\distro.tar...
2022-02-02T09:58:40.641Z: Running command wsl --distribution
rancher-desktop --exec tar -cf
/mnt/c/Users/VIVEK~1.NUN/AppData/Local/Temp/rd-distro-gGd3SG/distro.tar
-C / /bin/busybox /bin/mount /bin/sh /lib /etc/wsl.conf /etc/passwd /etc/rancher /var/lib... 2022-02-02T09:58:42.628Z: Running command wsl
--import rancher-desktop-data C:\Users\Vivek.Nuna\AppData\Local\rancher-desktop\distro-data
C:\Users\VIVEK~1.NUN\AppData\Local\Temp\rd-distro-gGd3SG\distro.tar
--version 2... 2022-02-02T09:58:44.025Z: Running command wsl --distribution rancher-desktop-data --exec /bin/busybox [ ! -d /etc/rancher ]... 2022-02-02T09:58:44.025Z: Running command wsl
--distribution rancher-desktop-data --exec /bin/busybox [ ! -d /var/lib ]... 2022-02-02T10:03:54.533Z: Running command wsl
--terminate rancher-desktop... 2022-02-02T10:03:54.534Z: Running command wsl --terminate rancher-desktop-data...
2022-02-02T10:03:54.971Z: Running command wsl --distribution
rancher-desktop --exec mkdir -p /mnt/wsl/rancher-desktop/run/data...
2022-02-02T10:04:03.418Z: WSL: executing: mkdir -p
/mnt/wsl/rancher-desktop/run/data: Error: wsl.exe exited with code
4294967295

答:
Right click Rancher Desktop Icon in Task bar, And Select "Quit Rancher Desktop"

Done below in cmd.exe or powershell

```<code>> wsl --unregister rancher-desktop
> wsl --unregister rancher-desktop-data
</code>```

Body:
I am getting the below error when installing the latest stable Rancher Desktop in my Virtual Machine.

Could someone please help?

Error:

Error: wsl.exe exited with code 4294967295

Command:

wsl --distribution rancher-desktop --exec mkdir -p /mnt/wsl/rancher-desktop/run/data

Logs:

2022-02-02T09:58:39.490Z: Running command wsl --distribution
rancher-desktop --exec wslpath -a -u
C:\Users\VIVEK~1.NUN\AppData\Local\Temp\rd-distro-gGd3SG\distro.tar...
2022-02-02T09:58:40.641Z: Running command wsl --distribution
rancher-desktop --exec tar -cf
/mnt/c/Users/VIVEK~1.NUN/AppData/Local/Temp/rd-distro-gGd3SG/distro.tar
-C / /bin/busybox /bin/mount /bin/sh /lib /etc/wsl.conf /etc/passwd /etc/rancher /var/lib... 2022-02-02T09:58:42.628Z: Running command wsl
--import rancher-desktop-data C:\Users\Vivek.Nuna\AppData\Local\rancher-desktop\distro-data
C:\Users\VIVEK~1.NUN\AppData\Local\Temp\rd-distro-gGd3SG\distro.tar
--version 2... 2022-02-02T09:58:44.025Z: Running command wsl --distribution rancher-desktop-data --exec /bin/busybox [ ! -d /etc/rancher ]... 2022-02-02T09:58:44.025Z: Running command wsl
--distribution rancher-desktop-data --exec /bin/busybox [ ! -d /var/lib ]... 2022-02-02T10:03:54.533Z: Running command wsl
--terminate rancher-desktop... 2022-02-02T10:03:54.534Z: Running command wsl --terminate rancher-desktop-data...
2022-02-02T10:03:54.971Z: Running command wsl --distribution
rancher-desktop --exec mkdir -p /mnt/wsl/rancher-desktop/run/data...
2022-02-02T10:04:03.418Z: WSL: executing: mkdir -p
/mnt/wsl/rancher-desktop/run/data: Error: wsl.exe exited with code
4294967295

Body:
Right click Rancher Desktop Icon in Task bar, And Select "Quit Rancher Desktop"

Done below in cmd.exe or powershell

> wsl --unregister rancher-desktop
> wsl --unregister rancher-desktop-data


问:
trying to have a different color my login form
hi i have decided to face my fears of frontend development and I am having a little bit of trouble here so I am trying to put a 50 px which is a rough estimate around my login form and I wanna change the color of it so the back ground is #423075 but I want the back of the actual login section tobe #300C94 what is the best way todo this with my code

index.html

```<code><html>
<header>
    <title>Login-1</title>

    <link rel="stylesheet" href="assets/css/styles.css" >

</header>

<body>

    <form class="form" >
              <div class="form-back" name="form-back" >
        <input  name="username" type="text" placeholder="username" required>
        <br>
        <input  name="password" type="password" placeholder="password" required>
        <br>
        <input  name="confirm_password" type="password" placeholder="Confirm Password" required>
        <br>
        <input  name="submit" type="submit">
</div>
    </form>

</body>

</html>
</code>```

styles.css

```<code>body{

    margin-top: 300px;
    text-align: center;
    background-color: #423075;

}

form{
    display: inline-block;

}

div{

    border-radius: 10px;
     border-radius: 30px;
    background: #300C94;
}

input[type=submit] {
    width: 100%;

}
</code>```

any suggestions would be great

答:
```<code>background-color: #300C94;
</code>```

try to put every element which you differentiate in background or any of the CSS style put it in different division.`

```<code><div></div>
</code>```

then use the CSS

```<code>.div {background-color: #300C94;}
</code>```

it will provide you the flexibility to change the color of different section you can also use the section html element which is also similar to div.

Body:
hi i have decided to face my fears of frontend development and I am having a little bit of trouble here so I am trying to put a 50 px which is a rough estimate around my login form and I wanna change the color of it so the back ground is #423075 but I want the back of the actual login section tobe #300C94 what is the best way todo this with my code

index.html

    <title>Login-1</title>

    <link rel="stylesheet" href="assets/css/styles.css" >

    <form class="form" >

        <input  name="username" type="text" placeholder="username" required>

        <input  name="password" type="password" placeholder="password" required>

        <input  name="confirm_password" type="password" placeholder="Confirm Password" required>

        <input  name="submit" type="submit">

    </form>

styles.css

body{

    margin-top: 300px;
    text-align: center;
    background-color: #423075;

}

form{
    display: inline-block;

}

div{

    border-radius: 10px;
     border-radius: 30px;
    background: #300C94;
}

input[type=submit] {
    width: 100%;

}

any suggestions would be great

Body:
background-color: #300C94;

try to put every element which you differentiate in background or any of the CSS style put it in different division.`

<div></div>

then use the CSS

.div {background-color: #300C94;}

it will provide you the flexibility to change the color of different section you can also use the section html element which is also similar to div.


问:
REQUEST_DENIED when using the Google Places API
I'm trying to make a request to the Google Places API, using the following url: https://maps.googleapis.com/maps/api/place/search/xml?location=37.77264,-122.409915&radius=500&types=educational%20services&name=everest%20college%20san%20francisco&sensor=false&key=YourApiKey

This is the response I get:

```<code><PlaceSearchResponse>
  <status>REQUEST_DENIED</status>
</PlaceSearchResponse>
</code>```

Any idea what could be wrong with the above URL?

答:
To find the actual error, run the api query in the browser directly or map the error to your object.</p>
```<code>{
   "error_message" : "You must enable Billing on the Google Cloud Project at https://console.cloud.google.com/project/_/billing/enable Learn more at https://developers.google.com/maps/gmp-get-started",
   "html_attributions" : [],
   "results" : [],
   "status" : "REQUEST_DENIED"
}
</code>```

Body:
I'm trying to make a request to the Google Places API, using the following url: https://maps.googleapis.com/maps/api/place/search/xml?location=37.77264,-122.409915&radius=500&types=educational%20services&name=everest%20college%20san%20francisco&sensor=false&key=YourApiKey

This is the response I get:

<PlaceSearchResponse>
  <status>REQUEST_DENIED</status>
</PlaceSearchResponse>

Any idea what could be wrong with the above URL?

Body:
To find the actual error, run the api query in the browser directly or map the error to your object.

{
   "error_message" : "You must enable Billing on the Google Cloud Project at https://console.cloud.google.com/project/_/billing/enable Learn more at https://developers.google.com/maps/gmp-get-started",
   "html_attributions" : [],
   "results" : [],
   "status" : "REQUEST_DENIED"
}


问:
Why it is said I can not use hello() to run this code?
This is my code and I want to use Hello() function to run this code. I tested and they said

hello()
TypeError: 'NoneType' object is not callable

What should I do then?

def announce(f):
    def wrapper():
        print ("About to run the function...")
        f()
        print("Done with the function.")
        return

@announce
def hello():
    print("Hello, world!")

hello()
```

答:
you need to return your wrapper ...</p>
```<code>def announce(func):
    def wrapper(*args,**kwargs):
        print(f"About to run {func.__name__}")
        result = func(*args,**kwargs)
        print(f"Done running {func.__name__}")
        return result
    # announce returns the wrapper...
    return wrapper

@announce
def hello():
    print("Hello world!")

hello()
</code>```

Body:
you need to return your wrapper ...

def announce(func):
    def wrapper(*args,**kwargs):
        print(f"About to run {func.__name__}")
        result = func(*args,**kwargs)
        print(f"Done running {func.__name__}")
        return result
    # announce returns the wrapper...
    return wrapper

@announce
def hello():
    print("Hello world!")

hello()


问:
Flutter: right overflowed by 23 pixels ("add task" button)
so basically i'm making a button "add task" for my to-do list app and it shows "right overflowed by 23 pixels"

Here's my "home_page.dart" code for the "add task" button

```<code>_addTaskBar(){
  return Container(
   margin: const EdgeInsets.only(left:20, right:20, top:10),
        child: Row(
          mainAxisAlignment: MainAxisAlignment.spaceBetween,
          children: [
            Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  Text(DateFormat.yMMMMd().format(DateTime.now()),
                  style: subHeadingStyle,
                  ),
                  Text("Today",
                  style: headingStyle,
                  )
                ],
              ),
            MyButton(label: "+ Add Task", onTap: ()=>null)
          ],
        ),
    );
}
</code>```

And this is my "button.dart" code for the "add task" button as well

```<code> class MyButton extends StatelessWidget {
  final String label;
  final Function()? onTap;
  const MyButton({ Key? key, required this.label, required this.onTap}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return GestureDetector(
      onTap: onTap,
      child: Container(
        width: 120,
        height: 60,
        decoration: BoxDecoration(
          borderRadius: BorderRadius.circular(20),
          color: primaryClr
        ),
        child: Text(
          label,
          style: const TextStyle(
            color: Colors.white,
          ),
        ),
      ),
    );
  }
}
</code>```

The result of the code is this
enter image description here

I need help to anyone who can solve this issue of mine. Thank you

答:
You can wrap your  MyButton widget with SizedBox like this:

```<code>SizedBox(
height:70,
width:50,
child:MyButton(label: "+ Add Task", onTap: ()=>null)
)
</code>```

You can also give dynamic height and width using MediaQuery  class, you can get information about the current device size, as well as user preferences, and design your layout accordingly

Body:
so basically i'm making a button "add task" for my to-do list app and it shows "right overflowed by 23 pixels"

Here's my "home_page.dart" code for the "add task" button

_addTaskBar(){
  return Container(
   margin: const EdgeInsets.only(left:20, right:20, top:10),
        child: Row(
          mainAxisAlignment: MainAxisAlignment.spaceBetween,
          children: [
            Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  Text(DateFormat.yMMMMd().format(DateTime.now()),
                  style: subHeadingStyle,
                  ),
                  Text("Today",
                  style: headingStyle,
                  )
                ],
              ),
            MyButton(label: "+ Add Task", onTap: ()=>null)
          ],
        ),
    );
}

And this is my "button.dart" code for the "add task" button as well

 class MyButton extends StatelessWidget {
  final String label;
  final Function()? onTap;
  const MyButton({ Key? key, required this.label, required this.onTap}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return GestureDetector(
      onTap: onTap,
      child: Container(
        width: 120,
        height: 60,
        decoration: BoxDecoration(
          borderRadius: BorderRadius.circular(20),
          color: primaryClr
        ),
        child: Text(
          label,
          style: const TextStyle(
            color: Colors.white,
          ),
        ),
      ),
    );
  }
}

The result of the code is this
enter image description here

I need help to anyone who can solve this issue of mine. Thank you

Body:
You can wrap your  MyButton widget with SizedBox like this:

SizedBox(
height:70,
width:50,
child:MyButton(label: "+ Add Task", onTap: ()=>null)
)

You can also give dynamic height and width using MediaQuery  class, you can get information about the current device size, as well as user preferences, and design your layout accordingly


问:
Cannot resolve table "'xx"" in spring boot application
I'm trying to run a spring boot app, but intellij is showing me an error:

"Cannot resolve table TB_PRODUTO"

Intellij it's giving a tip to assign a datasource, but the list is empty

what could be the problem?

答: If you have recently added database objects then JPA may not be detecting them yet - use view - tool windows - database and click the refresh button.</p>


问:
How do I center images in a Java Script random image generator?
I am making a random image generator for a school assignment, how do I center the image?
I am new to java script and would like to know how to center the images made by the generator.
I have tried a few different ways of centering the code but haven't found any way of doing it.
If there are workarounds to get it centered that is alright as I just need to have it centered.
Here is the code;</p>
```<code>    <html>
<head>
<title>Display random images</title>
<style>
body {
margin-top: 30px;
}
</style>
</head>

<script>
function displayRandomImages()
{

   //array of images with image location, height, and width
   var imageArray = [
   {
     //address URL of the image
     src: "https://i.insider.com/5d8a4d172e22af08c029c929?width=750&format=jpeg&auto=webp",
     //size for the image to be display on webpage
     width: "650",
     height: "500",
   },
   {
     src: "https://static.stacker.com/s3fs-public/styles/slide_desktop/s3/editedWWIIMonopolySPYSCAPE2000xpngv1587097885.PNG",
     width: "650",
     height: "500",

   },
   {
     src: "https://images-na.ssl-images-amazon.com/images/I/71IbpNx-3oL._SL1000_.jpg",
     width: "650",
     height: "500",
   },
   {
     src: "https://cdn.vox-cdn.com/thumbor/wj2qaxojsQT3DrUbP78SVW1fpMs=/0x0:1500x1500/1200x800/filters:focal(630x630:870x870)/cdn.vox-cdn.com/uploads/chorus_image/image/65772083/81C985A22GL._SL1500_.0.jpg",
     width: "650",
     height: "500",
    } ];

    //find the length of the array of images
    var arrayLength = imageArray.length;
    var newArray = [];
    for (var i = 0; i < arrayLength; i++) {
        newArray[i] = new Image();
        newArray[i].src = imageArray[i].src;
        newArray[i].width = imageArray[i].width;
        newArray[i].height = imageArray[i].height;
    }

  // create random image number
  function getRandomNum(min, max)
  {
      // generate and return a random number for the image to be displayed
      imgNo = Math.floor(Math.random() * (max - min + 1)) + min;
      return newArray[imgNo];
  }

  // 0 is first image and (preBuffer.length - 1) is last image of the array
  var newImage = getRandomNum(0, newArray.length - 1);

  // remove the previous images
  var images = document.getElementsByTagName('img');
  var l = images.length;
  for (var p = 0; p < l; p++) {
     images[0].parentNode.removeChild(images[0]);
  }
  // display the new random image
  document.body.appendChild(newImage);
}

</script>

<body>
<div>
<center>
<h2 style="color:green"> Random Image Generator </h2>
<h4> Press the button to display and change the image </h4>
<button onclick="displayRandomImages();"> Display Images </button>
</center>

</div>
</body>
</html>
</code>```

答:
```<code><html>
<head>
<title>Display random images</title>
<style>
body {
margin-top: 30px;
}
img{
    display: block;
    margin-left: auto;
    margin-right: auto;
    width: 50%;
}
</style>
</head>

<script>
function displayRandomImages()
{

   //array of images with image location, height, and width
   var imageArray = [
   {
     //address URL of the image
     src: "https://i.insider.com/5d8a4d172e22af08c029c929?width=750&format=jpeg&auto=webp",
     //size for the image to be display on webpage
     width: "650",
     height: "500",
   },
   {
     src: "https://static.stacker.com/s3fs-public/styles/slide_desktop/s3/editedWWIIMonopolySPYSCAPE2000xpngv1587097885.PNG",
     width: "650",
     height: "500",

   },
   {
     src: "https://images-na.ssl-images-amazon.com/images/I/71IbpNx-3oL._SL1000_.jpg",
     width: "650",
     height: "500",
   },
   {
     src: "https://cdn.vox-cdn.com/thumbor/wj2qaxojsQT3DrUbP78SVW1fpMs=/0x0:1500x1500/1200x800/filters:focal(630x630:870x870)/cdn.vox-cdn.com/uploads/chorus_image/image/65772083/81C985A22GL._SL1500_.0.jpg",
     width: "650",
     height: "500",
    } ];

    //find the length of the array of images
    var arrayLength = imageArray.length;
    var newArray = [];
    for (var i = 0; i < arrayLength; i++) {
        newArray[i] = new Image();
        newArray[i].src = imageArray[i].src;
        newArray[i].width = imageArray[i].width;
        newArray[i].height = imageArray[i].height;
    }

  // create random image number
  function getRandomNum(min, max)
  {
      // generate and return a random number for the image to be displayed
      imgNo = Math.floor(Math.random() * (max - min + 1)) + min;
      return newArray[imgNo];
  }

  // 0 is first image and (preBuffer.length - 1) is last image of the array
  var newImage = getRandomNum(0, newArray.length - 1);

  // remove the previous images
  var images = document.getElementsByTagName('img');
  var l = images.length;
  for (var p = 0; p < l; p++) {
     images[0].parentNode.removeChild(images[0]);
  }
  // display the new random image
  document.body.appendChild(newImage);
}

</script>

<body>
<div>
<center>
<h2 style="color:green"> Random Image Generator </h2>
<h4> Press the button to display and change the image </h4>
<button onclick="displayRandomImages();"> Display Images </button>
</center>

</div>
</body>
</html>
</code>```

Body:
I am making a random image generator for a school assignment, how do I center the image?
I am new to java script and would like to know how to center the images made by the generator.
I have tried a few different ways of centering the code but haven't found any way of doing it.
If there are workarounds to get it centered that is alright as I just need to have it centered.
Here is the code;

<title>Display random images</title>

 Random Image Generator

 Press the button to display and change the image

<button onclick="displayRandomImages();"> Display Images </button>


问:
Simple rewrite from root domain to subdirectory IIS7
I know the basics of how to rewrite but cant seem to find a rule that works the way I want it too.

Any help would be greatly appreciated :o)

```<code>    <rule name="RedirectRule" stopProcessing="true" enabled="true">
      <match url="^(.*)$" />
      <conditions>
        <add input="{HTTP_HOST}" pattern="^(www\.)?blah.com$" />
      </conditions>
      <action type="Rewrite" url="blog/{R:1}" />
    </rule>
</code>```

Basically I want it to only rewrite:

www.blah.com --> www.blah.com/blog

blah.com --> www.blah.com/blog

www.blah.com/blog --> do nothing.

www.blah.com/any-thing-else --> do nothing.

答:
What about adding in a second condition to check PATH_INFO? Seeing as you only want to re-write when this is not specified...

```<code><add input="{PATH_INFO}" pattern="^$" negate="true" />
</code>```

The checks that PATH_INFO 'Does Not Match the Pattern' ^$ which is an empty string.

I'm not able to test this right now, so it might need tweaking...

Body:
I know the basics of how to rewrite but cant seem to find a rule that works the way I want it too.

Any help would be greatly appreciated :o)

    <rule name="RedirectRule" stopProcessing="true" enabled="true">
      <match url="^(.*)$" />
      <conditions>
        <add input="{HTTP_HOST}" pattern="^(www\.)?blah.com$" />
      </conditions>
      <action type="Rewrite" url="blog/{R:1}" />
    </rule>

Basically I want it to only rewrite:

www.blah.com --> www.blah.com/blog

blah.com --> www.blah.com/blog

www.blah.com/blog --> do nothing.

www.blah.com/any-thing-else --> do nothing.

Body:
What about adding in a second condition to check PATH_INFO? Seeing as you only want to re-write when this is not specified...

<add input="{PATH_INFO}" pattern="^$" negate="true" />

The checks that PATH_INFO 'Does Not Match the Pattern' ^$ which is an empty string.

I'm not able to test this right now, so it might need tweaking...


答:
You could try adding a class of img-el to each image in the array and then add this to your script:

img-el{
  display: block;
  margin-left: auto;
  margin-right: auto;
}
```

another option is to add those properties to each and every image in the array and assign them in the same for loop where you assign the width, src etc.

I'm not sure exactly what you want it to look like, but I would also suggest reading up on flex.

Title: How do I center images in a Java Script random image generator?

Body:
You could try adding a class of img-el to each image in the array and then add this to your script:

img-el{
  display: block;
  margin-left: auto;
  margin-right: auto;
}

another option is to add those properties to each and every image in the array and assign them in the same for loop where you assign the width, src etc.

I'm not sure exactly what you want it to look like, but I would also suggest reading up on flex.


答:
```<code>SELECT company, id, COUNT(*)
  FROM table1
 GROUP BY EMPNO, ENAME, JOB, MGR, HIREDATE, SAL, COMM, DEPTNO
HAVING COUNT(*) > 1;
</code>```

Title: SQL - Return The Greater of a Partition


答: You try here MediaQuery.of(context)(height&width) instead of hard quoted hight width and also try expanded or wrap with flexible widget.

Title: Flutter: right overflowed by 23 pixels ("add task" button)


问:
Powershell expensive parsing
Heres a little segment from a script Im writing;

```<code>Get-Content $tempDir\$todaysLog | Where-Object { $_ -match "" } |
    ForEach-Object -Process {
    $fields = [regex]::split($_,'@|\s+')
    Add-Content -Path $importSource2\$todaysLog -value ($($fields[0]) + "`t"  + $($fields[1]) + "`t" + $($fields[2]) + " " + $($fields[3])+ "`t" + "<*sender*@"+($($fields[5])) + "`t" + "<*recipient*@"+($($fields[7])))
    }
</code>```

Sorry about the wrapping, essentially it tokenises the elements of the file into an an array then writes out certain elements with some other text around it.  The purpose is to replace sentitive sender/recipient information with something meaningless.

heres a sample of the logfile I'm parsing;

10.197.71.28    SG  02012009 00:00:00      <['recip@kpmg.com.sg']>

Obviously Ive replaced the address info in my sample.  The above segment works just fine althgogh Im conscious its very expensive. Can anything think of something that would be less expensive, perhaps a select-string to replace the text rather than tokenising/rewriting it?

Cheers

答: You should avoid using Powershell as the engine for large file size log parsing. I would use logparser.exe (you have a space delimited entry that could be converted to a csv) and then use import-csv in Powershell to recreate a Powershell object.  From there you can strip and replace fields (on a per object basis).  Powershell is glue not fuel.  Using it to parse large logs of any size is not quite downright folly, but will be expensive for you and the CPU. Although, Lee Holmes has an excellent Convert-TextObject.ps1 from his book examples at http://examples.oreilly.com/9780596528492/ ,  you want a log parsing engine of some type to handle the heavy lifting.</p>

OwnerDisplayName: Andy Walker

ContentLicense: CC BY-SA 2.5

Title: Powershell expensive parsing

Body:
Heres a little segment from a script Im writing;

Get-Content $tempDir\$todaysLog | Where-Object { $_ -match "" } |
    ForEach-Object -Process {
    $fields = [regex]::split($_,'@|\s+')
    Add-Content -Path $importSource2\$todaysLog -value ($($fields[0]) + "`t"  + $($fields[1]) + "`t" + $($fields[2]) + " " + $($fields[3])+ "`t" + "<*sender*@"+($($fields[5])) + "`t" + "<*recipient*@"+($($fields[7])))
    }

Sorry about the wrapping, essentially it tokenises the elements of the file into an an array then writes out certain elements with some other text around it.  The purpose is to replace sentitive sender/recipient information with something meaningless.

heres a sample of the logfile I'm parsing;

10.197.71.28    SG  02012009 00:00:00      <['recip@kpmg.com.sg']>

Obviously Ive replaced the address info in my sample.  The above segment works just fine althgogh Im conscious its very expensive. Can anything think of something that would be less expensive, perhaps a select-string to replace the text rather than tokenising/rewriting it?

Cheers

LastEditorDisplayName: Nathan W

OwnerDisplayName: Ryan M Ferris


问:
How use postgresql's ANY to access multidimensional array in dynamic query
I call a postgres function with a  multidimensional array like so:

```<code>SELECT get_listings(ARRAY[['name:John','grade:1'],['id:5','year:2020']]);
</code>```

The postgresql function has the following signature:

```<code>CREATE FUNCTION get_listings(arr text[]) RETURNS TABLE
(
    id text,
    tagz text
)
</code>```

Inside the function I have constructed a statement in a loop:

```<code>select * from (select product_type_id, string_agg(tag, '','') as tags
from all_tags group by product_type_id) as a
where tags = any($1[0]) and tags = any($1[1])
</code>```

which is assigned to variable stmt;

Now I call

```<code>RETURN QUERY EXECUTE stmt using arrArgs;
</code>```

where arrArgs has earlier been assigned with arr;

I get this error:

```<code>ERROR: op ANY/ALL (array) requires array on right side
</code>```

How can I access the inner array in the any function call?

答:
PostgreSQL has the best and easy function unnest() for expanding array elements to a set of rows. For example:

```<code>SELECT unnest(array[['tagA','tagB'],['tagA','tagB']]);

Result:

 unnest
----------
|  tagA  |
|  tagB  |
|  tagC  |
|  tagD  |
</code>```

Then you can use any conditions on the where statement.

```<code>select main.* from
(
    SELECT unnest(array[['tagA','tagB'],['tagA','tagB']]) as array_data
) main
where main.array_data in ('tagA', 'tagD');

Result:

 array_data
--------------
|  tagA      |
|  tagD      |
</code>```

Body:
I call a postgres function with a  multidimensional array like so:

SELECT get_listings(ARRAY[['name:John','grade:1'],['id:5','year:2020']]);

The postgresql function has the following signature:

CREATE FUNCTION get_listings(arr text[]) RETURNS TABLE
(
    id text,
    tagz text
)

Inside the function I have constructed a statement in a loop:

select * from (select product_type_id, string_agg(tag, '','') as tags
from all_tags group by product_type_id) as a
where tags = any($1[0]) and tags = any($1[1])

which is assigned to variable stmt;

Now I call

RETURN QUERY EXECUTE stmt using arrArgs;

where arrArgs has earlier been assigned with arr;

I get this error:

ERROR: op ANY/ALL (array) requires array on right side

How can I access the inner array in the any function call?

Body:
PostgreSQL has the best and easy function unnest() for expanding array elements to a set of rows. For example:

SELECT unnest(array[['tagA','tagB'],['tagA','tagB']]);

Result:

 unnest
----------
|  tagA  |
|  tagB  |
|  tagC  |
|  tagD  |

Then you can use any conditions on the where statement.

select main.* from
(
    SELECT unnest(array[['tagA','tagB'],['tagA','tagB']]) as array_data
) main
where main.array_data in ('tagA', 'tagD');

Result:

 array_data
--------------
|  tagA      |
|  tagD      |


问:
How to get asdf's version to be the version
Explained in terminal, I have installed a version of nodejs using asdf, but the terminal only sees the other version:

```<code>> asdf list
nodejs
  12.18.3

> nodejs --version
v8.10.0

> asdf global nodejs 12.18.3

> nodejs --version
v8.10.0
</code>```

Have added the following to the top of .zshrc

```<code>. $HOME/.asdf/asdf.sh
export PATH=$HOME/.asdf/asdf.sh:$PATH
</code>```

Have reloaded .zshrc

```<code>> source ~/.zshrc
</code>```

There are no local files which are setting the local version to 8.10.0.

How do I get nodejs --version to give me the version that asdf acknowledges as the global version?

答:
If you want to install asdf with homebrew and zsh use this:

echo -e "\n. $(brew --prefix asdf)/libexec/asdf.sh" >> ${ZDOTDIR:-~}/.zshrc

This adds the asdf.sh properly to the .zshrc file.

Read about it here

Body:
Explained in terminal, I have installed a version of nodejs using asdf, but the terminal only sees the other version:

> asdf list
nodejs
  12.18.3

> nodejs --version
v8.10.0

> asdf global nodejs 12.18.3

> nodejs --version
v8.10.0

Have added the following to the top of .zshrc

. $HOME/.asdf/asdf.sh
export PATH=$HOME/.asdf/asdf.sh:$PATH

Have reloaded .zshrc

> source ~/.zshrc

There are no local files which are setting the local version to 8.10.0.

How do I get nodejs --version to give me the version that asdf acknowledges as the global version?


问:
Block Context in editor.BlockEdit filter
I’m trying to extend a core gutenberg block so that it has a couple of additional options only when it’s contained in a certain custom made block. I thought block context would make this a simple task — set the container block to providesContext and use the blocks.registerBlockType filter to add usesContext to the core block. In the editor.BlockEdit filter, I thought I’d be able to get context from the block’s props. However, context is not one of the props. To make sure I wasn’t doing anything wrong around context, I used the editor.BlockEdit filter on one of my custom blocks that I knew was receiving block context correctly. It doesn’t have context as one of its props either.

Does anyone know of a way to get block context into the editor.BlockEdit filter?

For reference, here is a snippet of the code so far:

```<code>    title: 'Card',
    icon: 'images-alt2',
    category: 'utdesign_system',
    description: '',
    attributes: {
        blockName: {
            type: 'string',
            default: 'card',
        }
    },
    providesContext: {
        'card/blockName': 'blockName',
    },
    edit,
    save,
} );

function addImageContext( settings ) {
    if( settings.name == 'core/image' ){
        settings.usesContext = Object.assign( ['card/blockName'] );
    }
    return settings;
}

addFilter(
    'blocks.registerBlockType',
    'gutenstrap/image-context',
    addImageContext
);

const addImageControls =  createHigherOrderComponent( ( BlockEdit ) => {
    return ( props ) => {

        const {
            name,
            attributes,
            setAttributes,
            context,
            isSelected,
        } = props;
        //do stuff with context
    };
}, "addImageControls" );

addFilter(
    'editor.BlockEdit',
    'gutenstrap/image-context',
    addImageControls
);```
```

答:
It is now documented https://developer.wordpress.org/block-editor/reference-guides/block-api/block-context/</p>
```<code>registerBlockType( 'my-plugin/record-title', {
    title: 'Record Title',
    category: 'widgets',

    usesContext: [ 'my-plugin/recordId' ],

    edit( { context } ) {
        return 'The record ID: ' + context[ 'my-plugin/recordId' ];
    },

    save() {
        return null;
    },
} );
</code>```

Body:
I’m trying to extend a core gutenberg block so that it has a couple of additional options only when it’s contained in a certain custom made block. I thought block context would make this a simple task — set the container block to providesContext and use the blocks.registerBlockType filter to add usesContext to the core block. In the editor.BlockEdit filter, I thought I’d be able to get context from the block’s props. However, context is not one of the props. To make sure I wasn’t doing anything wrong around context, I used the editor.BlockEdit filter on one of my custom blocks that I knew was receiving block context correctly. It doesn’t have context as one of its props either.

Does anyone know of a way to get block context into the editor.BlockEdit filter?

For reference, here is a snippet of the code so far:

    title: 'Card',
    icon: 'images-alt2',
    category: 'utdesign_system',
    description: '',
    attributes: {
        blockName: {
            type: 'string',
            default: 'card',
        }
    },
    providesContext: {
        'card/blockName': 'blockName',
    },
    edit,
    save,
} );

function addImageContext( settings ) {
    if( settings.name == 'core/image' ){
        settings.usesContext = Object.assign( ['card/blockName'] );
    }
    return settings;
}

addFilter(
    'blocks.registerBlockType',
    'gutenstrap/image-context',
    addImageContext
);

const addImageControls =  createHigherOrderComponent( ( BlockEdit ) => {
    return ( props ) => {

        const {
            name,
            attributes,
            setAttributes,
            context,
            isSelected,
        } = props;
        //do stuff with context
    };
}, "addImageControls" );

addFilter(
    'editor.BlockEdit',
    'gutenstrap/image-context',
    addImageControls
);```

Body:
It is now documented https://developer.wordpress.org/block-editor/reference-guides/block-api/block-context/

registerBlockType( 'my-plugin/record-title', {
    title: 'Record Title',
    category: 'widgets',

    usesContext: [ 'my-plugin/recordId' ],

    edit( { context } ) {
        return 'The record ID: ' + context[ 'my-plugin/recordId' ];
    },

    save() {
        return null;
    },
} );