问:
css opacity transition on click
Is there some way I can get this image to fade in using the CSS transition defined?  Right now it's just popping to the full opacity.

var makeImage = function() {
    $('#image').remove();

    $(document.body).append('');

    var img = $('#image')[0];
    console.log(img.style);
    img.style["opacity"] = 1;
  };```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.fadeIn {
    opacity: 0;
    -moz-transition: opacity 5.5s ease 0.300s;
    -webkit-transition: opacity 5.5s ease 0.300s;
    -o-transition: opacity 5.5s ease 0.300s;
    transition: opacity 5.5s ease 0.300s;
  }</code>```

<title>Fade Example</title>
<input id="makeButton" type="button" value="Make and fade" onclick="makeImage()" ; />```

edit: I realize there is a fadeIn function provided by jquery.  I regret using jquery in this example as the point was to do it using the CSS transition properties.

答:
This will run once and forwards sets all values specified to the values given at 100%.

```<code>. fadeIn {
  animation: fade-in 0.8s cubic-bezier(0.250, 0.460, 0.450, 0.940) forwards;
}

@keyframes fade-in {
  0% {
    opacity: 0;
  100% {
    opacity: 1;
  }
</code>```

And is a pure CSS solution, like you asked for in your edit.

Title: css opacity transition on click

Body:
Is there some way I can get this image to fade in using the CSS transition defined?  Right now it's just popping to the full opacity.

var makeImage = function() {
    $('#image').remove();

    $(document.body).append('');

    var img = $('#image')[0];
    console.log(img.style);
    img.style["opacity"] = 1;
  };

.fadeIn {
    opacity: 0;
    -moz-transition: opacity 5.5s ease 0.300s;
    -webkit-transition: opacity 5.5s ease 0.300s;
    -o-transition: opacity 5.5s ease 0.300s;
    transition: opacity 5.5s ease 0.300s;
  }

<title>Fade Example</title>
<input id="makeButton" type="button" value="Make and fade" onclick="makeImage()" ; />

edit: I realize there is a fadeIn function provided by jquery.  I regret using jquery in this example as the point was to do it using the CSS transition properties.

Body:
This will run once and forwards sets all values specified to the values given at 100%.

. fadeIn {
  animation: fade-in 0.8s cubic-bezier(0.250, 0.460, 0.450, 0.940) forwards;
}

@keyframes fade-in {
  0% {
    opacity: 0;
  100% {
    opacity: 1;
  }

And is a pure CSS solution, like you asked for in your edit.


来源: stackexchange

问:
How to erase the dotting watermark from the image?
I want to automate the task of entering the faxed documents into the system with OCR. I tried using tesseract, but I found that the part that does not contain the watermark is recognized well, but the part that is watermarked is almost impossible to recognize.

I would like to remove the watermark using image processing. Unusually, the watermark of this image consists of 1x1 black pixels.

Is there a way to get rid of this watermark?

Example document (masked sensitive personal info):

Watermark (composed of 1x1 pixels):

Edit: Another answer marked as duplicate is simply a greyed-out watermark, but the image I want to process is a binary image, so the color of the image and watermark is black. So it can not be processed in the same way and it seems to have to be processed in a different way.

答:
You can use the morphological Closing operation.

Use the closing only on the ROI with the watermark.

Here is a MATLAB code sample:

I = rgb2gray(imread('kmyxE.png')); %Read the image and convert it to Grayscale.
J = I;

%Morphological closing with kernel size 3x3 (applyied only the area with the watermark).
J(720:1450, 480:1260) = imclose(I(720:1450, 480:1260), ones(3));
```

<p>I leave you the pleasure to implement it using OpenCV...  </p>

<p>Result:<br>
<img src="https://i.stack.imgur.com/GCxW9.png" alt="enter image description here"></p>

<hr>

<p>The following solution may be better:  </p>

<ol>
<li>Close in X direction using kernel 1x3</li>
<li>Close in Y direction using kernel 3x1</li>
<li>Take the minimum value of the the two images.  </li>
</ol>

<pre class="lang-matlab prettyprint-override"><code>I = rgb2gray(imread('kmyxE.png'));
J1 = I;
J2 = I;

%Morphological closing with kernel size 1x3 (applyied only the area with the watermark).
J1(720:1450, 480:1260) = imclose(I(720:1450, 480:1260), ones(1, 3));

%Morphological closing with kernel size 3x1
J2(720:1450, 480:1260) = imclose(I(720:1450, 480:1260), ones(3, 1));

%Keep the minimum of J1 and J2
J = min(J1, J2);
</code>```

Result:

ContentLicense: CC BY-SA 4.0

Body:
You can use the morphological Closing operation.

Use the closing only on the ROI with the watermark.

Here is a MATLAB code sample:

I = rgb2gray(imread('kmyxE.png')); %Read the image and convert it to Grayscale.
J = I;

%Morphological closing with kernel size 3x3 (applyied only the area with the watermark).
J(720:1450, 480:1260) = imclose(I(720:1450, 480:1260), ones(3));

I leave you the pleasure to implement it using OpenCV...

Result:

The following solution may be better:

Close in X direction using kernel 1x3

Close in Y direction using kernel 3x1

Take the minimum value of the the two images.

I = rgb2gray(imread('kmyxE.png'));
J1 = I;
J2 = I;

%Morphological closing with kernel size 1x3 (applyied only the area with the watermark).
J1(720:1450, 480:1260) = imclose(I(720:1450, 480:1260), ones(1, 3));

%Morphological closing with kernel size 3x1
J2(720:1450, 480:1260) = imclose(I(720:1450, 480:1260), ones(3, 1));

%Keep the minimum of J1 and J2
J = min(J1, J2);

Result:


问:
"Failed to decode response from marionette" message in Python/Firefox headless scraping script
Good Day, I've done a number of searches on here and google and yet to find a solution that address this problem.

The scenario is:

I have a Python script (2.7) that loops through an number of URLs (e.g. think Amazon pages, scraping reviews).  Each page has the same HTML layout, just scraping different information.  I use Selenium with a headless browser as these pages have javascript that needs to execute to grab the information.

I run this script on my local machine (OSX 10.10).  Firefox is the latest v59.  Selenium is version at 3.11.0 and using geckodriver v0.20.

This script locally has no issues, it can run through all the URLs and scrape the pages with no issue.

Now when I put the script on my server, the only difference is it is Ubuntu 16.04 (32 bit).  I use the appropriate geckodriver (still v0.20) but everything else is the same (Python 2.7, Selenium 3.11).  It appears to randomly crash the headless browser and then all of the browserObjt.get('url...') no longer work.

The error messages say:

Message: failed to decode response from marionette

Any further selenium requests for pages return the error:

Message: tried to run command without establishing a connection

To show some code:

When I create the driver:

```<code>    options = Options()
    options.set_headless(headless=True)

    driver = webdriver.Firefox(
        firefox_options=options,
        executable_path=config.GECKODRIVER
    )
</code>```

driver is passed to the script's function as a parameter browserObj which is then used to call specific pages and then once that loads it is passed to BeautifulSoup for parsing:

```<code>browserObj.get(url)

soup = BeautifulSoup(browserObj.page_source, 'lxml')
</code>```

The error might be pointing to the BeautifulSoup line which is crashing the browser.

What is likely causing this, and what can I do to resolve the issue?

Edit: Adding stack trace which points to the same thing:

```<code>Traceback (most recent call last):
  File "main.py", line 164, in <module>
    getLeague
  File "/home/ps/dataparsing/XXX/yyy.py", line 48, in BBB
    soup = BeautifulSoup(browserObj.page_source, 'lxml')
  File "/home/ps/AAA/projenv/local/lib/python2.7/site-packages/selenium/webdriver/remote/webdriver.py", line 670, in page_source
    return self.execute(Command.GET_PAGE_SOURCE)['value']
  File "/home/ps/AAA/projenv/local/lib/python2.7/site-packages/selenium/webdriver/remote/webdriver.py", line 312, in execute
    self.error_handler.check_response(response)
  File "/home/ps/AAA/projenv/local/lib/python2.7/site-packages/selenium/webdriver/remote/errorhandler.py", line 242, in check_response
    raise exception_class(message, screen, stacktrace)
WebDriverException: Message: Failed to decode response from marionette
</code>```

Note: This script used to work with Chrome.  Because the server is a 32bit server, I can only use chromedriver v0.33, which only supports Chrome v60-62.  Currently Chrome is v65 and on DigitalOcean I don't seem to have an easy way to revert back to an old version - which is why I am stuck with Firefox.

答: The problem is that you do not close the driver. I made the same mistake. Whit htop in Linux, I have noticed that I occupy all the 26 GB of my pc whit firefox unclosed process.</p>

ContentLicense: CC BY-SA 3.0

Body:
Good Day, I've done a number of searches on here and google and yet to find a solution that address this problem.

The scenario is:

I have a Python script (2.7) that loops through an number of URLs (e.g. think Amazon pages, scraping reviews).  Each page has the same HTML layout, just scraping different information.  I use Selenium with a headless browser as these pages have javascript that needs to execute to grab the information.

I run this script on my local machine (OSX 10.10).  Firefox is the latest v59.  Selenium is version at 3.11.0 and using geckodriver v0.20.

This script locally has no issues, it can run through all the URLs and scrape the pages with no issue.

Now when I put the script on my server, the only difference is it is Ubuntu 16.04 (32 bit).  I use the appropriate geckodriver (still v0.20) but everything else is the same (Python 2.7, Selenium 3.11).  It appears to randomly crash the headless browser and then all of the browserObjt.get('url...') no longer work.

The error messages say:

Message: failed to decode response from marionette

Any further selenium requests for pages return the error:

Message: tried to run command without establishing a connection

To show some code:

When I create the driver:

    options = Options()
    options.set_headless(headless=True)

    driver = webdriver.Firefox(
        firefox_options=options,
        executable_path=config.GECKODRIVER
    )

driver is passed to the script's function as a parameter browserObj which is then used to call specific pages and then once that loads it is passed to BeautifulSoup for parsing:

browserObj.get(url)

soup = BeautifulSoup(browserObj.page_source, 'lxml')

The error might be pointing to the BeautifulSoup line which is crashing the browser.

What is likely causing this, and what can I do to resolve the issue?

Edit: Adding stack trace which points to the same thing:

Traceback (most recent call last):
  File "main.py", line 164, in <module>
    getLeague
  File "/home/ps/dataparsing/XXX/yyy.py", line 48, in BBB
    soup = BeautifulSoup(browserObj.page_source, 'lxml')
  File "/home/ps/AAA/projenv/local/lib/python2.7/site-packages/selenium/webdriver/remote/webdriver.py", line 670, in page_source
    return self.execute(Command.GET_PAGE_SOURCE)['value']
  File "/home/ps/AAA/projenv/local/lib/python2.7/site-packages/selenium/webdriver/remote/webdriver.py", line 312, in execute
    self.error_handler.check_response(response)
  File "/home/ps/AAA/projenv/local/lib/python2.7/site-packages/selenium/webdriver/remote/errorhandler.py", line 242, in check_response
    raise exception_class(message, screen, stacktrace)
WebDriverException: Message: Failed to decode response from marionette

Note: This script used to work with Chrome.  Because the server is a 32bit server, I can only use chromedriver v0.33, which only supports Chrome v60-62.  Currently Chrome is v65 and on DigitalOcean I don't seem to have an easy way to revert back to an old version - which is why I am stuck with Firefox.


问:
Sum up duplicate rows in mysql table

Mysql refuses to sum up duplicate row values

i have seen this query statement on a website but when i tried it mysql returns to me exactly what i have in my table without summing them up.ie.duplicate agent name and corresponding advance amount. Agent name and advance amount is a column. Agent_name has two records hitman and hitman. advance amount has two amount 40 and 20 for each Agent.

```<code>SELECT agent_name,
SUM (advance_amount)
FROM orders
GROUP BY agent_name;
</code>```

答:
hoping the the same agent_name is based on different id  you could try using group by id </p>

```<code>SELECT agent_name,
SUM (advance_amount)
FROM orders
GROUP BY agent_id;
</code>```

Title: Sum up duplicate rows in mysql table

Body:
Mysql refuses to sum up duplicate row values

i have seen this query statement on a website but when i tried it mysql returns to me exactly what i have in my table without summing them up.ie.duplicate agent name and corresponding advance amount. Agent name and advance amount is a column. Agent_name has two records hitman and hitman. advance amount has two amount 40 and 20 for each Agent.

SELECT agent_name,
SUM (advance_amount)
FROM orders
GROUP BY agent_name;

Body:
hoping the the same agent_name is based on different id  you could try using group by id

SELECT agent_name,
SUM (advance_amount)
FROM orders
GROUP BY agent_id;


问:
Odoo ERP java API Client with jersey Library
Java API Client for Odoo API not working while adding session_id in the header.

My code is here.
I am using Java jersey Library

```<code>ClientConfig clientConfig = new DefaultClientConfig();
clientConfig.getFeatures().put(JSONConfiguration.FEATURE_POJO_MAPPING, Boolean.TRUE);
Client client = Client.create();
WebResource webResource = client.resource(getUrl);ClientResponse response = webResource.accept("application/json")
                .header("session_id", "615a0000df586b9dbbea4c06f91fb1454dbf1525").type("application/json")
                .post(ClientResponse.class, jsonReq);
String output = response.getEntity(String.class);
</code>```

---------------------------- out put ---------------

```<code>com.sun.jersey.api.client.ClientHandlerException: java.net.ConnectException: Connection refused: connect
at com.sun.jersey.client.urlconnection.URLConnectionClientHandler.handle(URLConnectionClientHandler.java:149)
at com.sun.jersey.api.client.Client.handle(Client.java:648)
at com.sun.jersey.api.client.WebResource.handle(WebResource.java:670)
at com.sun.jersey.api.client.WebResource.access$200(WebResource.java:74)
at com.sun.jersey.api.client.WebResource$Builder.post(WebResource.java:563)
at com.peapi.zbz.sarmix.restclient.JerseyClientPost.getList1(JerseyClientPost.java:154)
at com.peapi.zbz.sarmix.restclient.JerseyClientPost.main(JerseyClientPost.java:39)
</code>```

Caused by: java.net.ConnectException: Connection refused: connect

i need add the session id in my post request using jersey java rest client

答:
yes I got the solution </p>

```<code>String sessionId = "ee5c5b33590ce7c1ebb3ea55ce1bbed37b11614a";
        final String urlAuth = "http://testsssssxxx.com/web/dataset/call";
        Client client = Client.create();
        WebResource webResource = client.resource(urlAuth);
        final String input = "{\"jsonrpc\": \"2.0\", \"params\": { \"model\": \"auto.wbr.conf\", \"method\": \"api_get_supp_trans\", \"args\": [{\"wbr_sequence\": \"1234\",\"factory_id\":\"1\"}] } }";
        ClientResponse response =webResource.type("application/json").header("cookie", "session_id="+sessionId).post(ClientResponse.class,input);
        if (response.getStatus() != 200) {
            throw new RuntimeException("Failed : HTTP error code : " + response.getStatus());
        }

        System.out.println("Output from Server .... \n");
        String output = response.getEntity(String.class);
        System.out.println(output);
</code>```

Body:
Java API Client for Odoo API not working while adding session_id in the header.

My code is here.
I am using Java jersey Library

ClientConfig clientConfig = new DefaultClientConfig();
clientConfig.getFeatures().put(JSONConfiguration.FEATURE_POJO_MAPPING, Boolean.TRUE);
Client client = Client.create();
WebResource webResource = client.resource(getUrl);ClientResponse response = webResource.accept("application/json")
                .header("session_id", "615a0000df586b9dbbea4c06f91fb1454dbf1525").type("application/json")
                .post(ClientResponse.class, jsonReq);
String output = response.getEntity(String.class);

---------------------------- out put ---------------

com.sun.jersey.api.client.ClientHandlerException: java.net.ConnectException: Connection refused: connect
at com.sun.jersey.client.urlconnection.URLConnectionClientHandler.handle(URLConnectionClientHandler.java:149)
at com.sun.jersey.api.client.Client.handle(Client.java:648)
at com.sun.jersey.api.client.WebResource.handle(WebResource.java:670)
at com.sun.jersey.api.client.WebResource.access$200(WebResource.java:74)
at com.sun.jersey.api.client.WebResource$Builder.post(WebResource.java:563)
at com.peapi.zbz.sarmix.restclient.JerseyClientPost.getList1(JerseyClientPost.java:154)
at com.peapi.zbz.sarmix.restclient.JerseyClientPost.main(JerseyClientPost.java:39)

Caused by: java.net.ConnectException: Connection refused: connect

i need add the session id in my post request using jersey java rest client

Body:
yes I got the solution

String sessionId = "ee5c5b33590ce7c1ebb3ea55ce1bbed37b11614a";
        final String urlAuth = "http://testsssssxxx.com/web/dataset/call";
        Client client = Client.create();
        WebResource webResource = client.resource(urlAuth);
        final String input = "{\"jsonrpc\": \"2.0\", \"params\": { \"model\": \"auto.wbr.conf\", \"method\": \"api_get_supp_trans\", \"args\": [{\"wbr_sequence\": \"1234\",\"factory_id\":\"1\"}] } }";
        ClientResponse response =webResource.type("application/json").header("cookie", "session_id="+sessionId).post(ClientResponse.class,input);
        if (response.getStatus() != 200) {
            throw new RuntimeException("Failed : HTTP error code : " + response.getStatus());
        }

        System.out.println("Output from Server .... \n");
        String output = response.getEntity(String.class);
        System.out.println(output);


问:
centos iptables at windows network
I've got a machine, running Centos and it's connected to a windows network. When I try to view the network I'm getting the error "unable to connect share list from server". Once I turned iptables off everything works fine. How ca I fix this problem. My current iptables configuration is</p>

```<code># Generated by iptables-save v1.4.7 on Sat Nov 16 11:06:35 2013
*filter
:INPUT ACCEPT [0:0]
:FORWARD ACCEPT [0:0]
:OUTPUT ACCEPT [6:360]
-A INPUT -p tcp -m tcp --dport 80 -j ACCEPT
-A INPUT -m state --state RELATED,ESTABLISHED -j ACCEPT
-A INPUT -p icmp -j ACCEPT
-A INPUT -i lo -j ACCEPT
-A INPUT -p tcp -m state --state NEW -m tcp --dport 22 -j ACCEPT
-A INPUT -s 192.168.2.0/24 -m state --state NEW -m tcp -p tcp --dport 445 -j ACCEPT
-A INPUT -s 192.168.2.0/24 -m state --state NEW -m udp -p udp --dport 445 -j ACCEPT
-A INPUT -s 192.168.2.0/24 -m state --state NEW -m udp -p udp --dport 137 -j ACCEPT
-A INPUT -s 192.168.2.0/24 -m state --state NEW -m udp -p udp --dport 138 -j ACCEPT
-A INPUT -s 192.168.2.0/24 -m state --state NEW -m tcp -p tcp --dport 139 -j ACCEPT
-A INPUT -j REJECT --reject-with icmp-host-prohibited
-A FORWARD -j REJECT --reject-with icmp-host-prohibited
  COMMIT
# Completed on Sat Nov 16 11:06:35 2013
</code>```

答:
a] First log the dropped ip tables for example like this

```<code>#----------
# Logs to messages.log
#----------
-A INPUT -m limit --limit 5/min -j LOG --log-prefix "iptables denied: INPUT " --log-level 4
-A OUTPUT -m limit --limit 5/min -j LOG --log-prefix "iptables denied: OUTPUT " --log-level 4
-A FORWARD -m limit --limit 5/min -j LOG --log-prefix "iptables denied: FORWARD " --log-level 4
</code>```

b] tail dropped tables from messages

```<code>tomas@raspirarium:~ $ tail -f /var/log/messages |grep "iptables denied"
</code>```

c] write ip tables rules beyond the denied rules in message.log on the fly as is the example bottom

```<code>#----------
# Windows Samba
#----------
# incoming request
-A INPUT -i eth0 -p tcp -s 192.168.79.0/24 -m multiport --dports 139,445 -m state --state NEW,ESTABLISHED -j ACCEPT
-A OUTPUT -o eth0 -p tcp -d 192.168.79.0/24 -m multiport --sports 1024:65535 -m state --state ESTABLISHED -j ACCEPT
# outgoing laso handler
-A OUTPUT -o eth0 -p tcp -s 192.168.79.0/24 -m multiport --dports 139,445 -m state --state NEW,ESTABLISHED -j ACCEPT
-A INPUT -i eth0 -p tcp -s 192.168.79.0/24 -m multiport --sports 1024:65535 -m state --state ESTABLISHED -j ACCEPT
</code>```

Title: centos iptables at windows network

Body:
I've got a machine, running Centos and it's connected to a windows network. When I try to view the network I'm getting the error "unable to connect share list from server". Once I turned iptables off everything works fine. How ca I fix this problem. My current iptables configuration is

# Generated by iptables-save v1.4.7 on Sat Nov 16 11:06:35 2013
*filter
:INPUT ACCEPT [0:0]
:FORWARD ACCEPT [0:0]
:OUTPUT ACCEPT [6:360]
-A INPUT -p tcp -m tcp --dport 80 -j ACCEPT
-A INPUT -m state --state RELATED,ESTABLISHED -j ACCEPT
-A INPUT -p icmp -j ACCEPT
-A INPUT -i lo -j ACCEPT
-A INPUT -p tcp -m state --state NEW -m tcp --dport 22 -j ACCEPT
-A INPUT -s 192.168.2.0/24 -m state --state NEW -m tcp -p tcp --dport 445 -j ACCEPT
-A INPUT -s 192.168.2.0/24 -m state --state NEW -m udp -p udp --dport 445 -j ACCEPT
-A INPUT -s 192.168.2.0/24 -m state --state NEW -m udp -p udp --dport 137 -j ACCEPT
-A INPUT -s 192.168.2.0/24 -m state --state NEW -m udp -p udp --dport 138 -j ACCEPT
-A INPUT -s 192.168.2.0/24 -m state --state NEW -m tcp -p tcp --dport 139 -j ACCEPT
-A INPUT -j REJECT --reject-with icmp-host-prohibited
-A FORWARD -j REJECT --reject-with icmp-host-prohibited
  COMMIT
# Completed on Sat Nov 16 11:06:35 2013

Body:
a] First log the dropped ip tables for example like this

#----------
# Logs to messages.log
#----------
-A INPUT -m limit --limit 5/min -j LOG --log-prefix "iptables denied: INPUT " --log-level 4
-A OUTPUT -m limit --limit 5/min -j LOG --log-prefix "iptables denied: OUTPUT " --log-level 4
-A FORWARD -m limit --limit 5/min -j LOG --log-prefix "iptables denied: FORWARD " --log-level 4

b] tail dropped tables from messages

tomas@raspirarium:~ $ tail -f /var/log/messages |grep "iptables denied"

c] write ip tables rules beyond the denied rules in message.log on the fly as is the example bottom

#----------
# Windows Samba
#----------
# incoming request
-A INPUT -i eth0 -p tcp -s 192.168.79.0/24 -m multiport --dports 139,445 -m state --state NEW,ESTABLISHED -j ACCEPT
-A OUTPUT -o eth0 -p tcp -d 192.168.79.0/24 -m multiport --sports 1024:65535 -m state --state ESTABLISHED -j ACCEPT
# outgoing laso handler
-A OUTPUT -o eth0 -p tcp -s 192.168.79.0/24 -m multiport --dports 139,445 -m state --state NEW,ESTABLISHED -j ACCEPT
-A INPUT -i eth0 -p tcp -s 192.168.79.0/24 -m multiport --sports 1024:65535 -m state --state ESTABLISHED -j ACCEPT


问:
Change variable with tkinter button
I got some kind of problem with the structure with my code. I am using Tkinter and building a GUI. My idea is as follows: there is a field that takes the path to a file and when you click Start, Python opens the path and loads the file as a csv. Then it stores the file in a dict with some more information and returns the dict that will be passed around to other functions. However, how can this work? The Button can only run a function but not return something, right?

So I can enter the (partially filled) dict as an argument of this input function, however, it is never returned. My solution until now was to declare it a global, so when it is changed within the function, it is also changed outside. However, now I restructure the code and want to reuse code (since files are imported at several stages in the process). Now, when I want to use the same function again, the global solution seems problematic. Any ideas how I can do this without them? Thanks a lot.

Update1:

```<code>class Topclass:
    def changer(x):
        x += 1

class Subclass(Topclass):
    def __init__(self):
        self.b = 2

obb = Subclass()
print(obb.b)
Topclass.changer(obb.b)
print(obb.b)
</code>```

答:
@Martineau's advice is correct, there is much to learn from @BryanOakley's Best way to structure a tkinter application's answer.

Using a DataTransfer specialized object is a technique that you can use to pass variables, or data around, with frameworks that do not return values like tkinter, or when you need your data to cross an encapsulation barrier, without tightly coupling the objects involved:

Here is a simple example to illustrate how that works:

```<code>class DataTransfer:
    """mutable object that is used to transfer data
    """
    def __init__(self, value: int) -> None:
        self.value = value

    def add_one(self) -> None:
        self.value += 1

    def __str__(self) -> str:
        return f'{self.value}'

class Topclass:
    def changer(x: DataTransfer) -> None:
        x.add_one()

class Subclass(Topclass):
    def __init__(self) -> None:
        self.b = DataTransfer(2)

obb = Subclass()
print(obb.b)
Topclass.changer(obb.b)
print(obb.b)
</code>```

Title: Change variable with tkinter button

Body:
I got some kind of problem with the structure with my code. I am using Tkinter and building a GUI. My idea is as follows: there is a field that takes the path to a file and when you click Start, Python opens the path and loads the file as a csv. Then it stores the file in a dict with some more information and returns the dict that will be passed around to other functions. However, how can this work? The Button can only run a function but not return something, right?

So I can enter the (partially filled) dict as an argument of this input function, however, it is never returned. My solution until now was to declare it a global, so when it is changed within the function, it is also changed outside. However, now I restructure the code and want to reuse code (since files are imported at several stages in the process). Now, when I want to use the same function again, the global solution seems problematic. Any ideas how I can do this without them? Thanks a lot.

Update1:

class Topclass:
    def changer(x):
        x += 1

class Subclass(Topclass):
    def __init__(self):
        self.b = 2

obb = Subclass()
print(obb.b)
Topclass.changer(obb.b)
print(obb.b)

Body:
@Martineau's advice is correct, there is much to learn from @BryanOakley's Best way to structure a tkinter application's answer.

Using a DataTransfer specialized object is a technique that you can use to pass variables, or data around, with frameworks that do not return values like tkinter, or when you need your data to cross an encapsulation barrier, without tightly coupling the objects involved:

Here is a simple example to illustrate how that works:

class DataTransfer:
    """mutable object that is used to transfer data
    """
    def __init__(self, value: int) -> None:
        self.value = value

    def add_one(self) -> None:
        self.value += 1

    def __str__(self) -> str:
        return f'{self.value}'

class Topclass:
    def changer(x: DataTransfer) -> None:
        x.add_one()

class Subclass(Topclass):
    def __init__(self) -> None:
        self.b = DataTransfer(2)

obb = Subclass()
print(obb.b)
Topclass.changer(obb.b)
print(obb.b)


问:
JVM performance tuning for large applications
The default JVM parameters are not optimal for running large applications. Any insights from people who have tuned it on a real application would be helpful. We are running the application on a 32-bit windows machine, where the client JVM is used by default. We have added -server and changed the NewRatio to 1:3 (A larger young generation).

Any other parameters/tuning which you have tried and found useful?

[Update] The specific type of application I'm talking about is a server application that are rarely shutdown, taking at least -Xmx1024m. Also assume that the application is profiled already. I'm looking for general guidelines in terms of JVM performance only.

答:
There are great quantities of that information around.

First, profile the code before tuning the JVM.

Second, read the JVM documentation carefully; there are a lot of sort of "urban legends" around.  For example, the -server flag only helps if the JVM is staying resident and running for some time; -server "turns up" the JIT/HotSpot, and that needs to have many passes through the same path to get turned up.  -server, on the other hand, slows initial execution of the JVM, as there's more setup time.

There are several good books and websites around. See, for example, http://www.javaperformancetuning.com/

ContentLicense: CC BY-SA 2.5

OwnerDisplayName: Charlie Martin


问:
why does spring security give empty password to password encoder?
I am using spring security with BCrypt Password encoder for authentication. when i want to login, Spring security fetchs user data with JPA correctly but for checking raw password with encoded password it gives null string as encoded password to password encoder.

spring security config :

```<code>@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    @Qualifier("userDetailsServiceImpl")
    private UserDetailsService userDetailsService;

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

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception{
        auth.userDetailsService(userDetailsService)
        .passwordEncoder(passwordEncoder());
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests()
                .antMatchers("/").hasAuthority("USER")
                .antMatchers("/css/**","/font/**","/js/**","/image/**").permitAll()
                .antMatchers("/register").permitAll()
                .and().formLogin().loginPage("/login").successForwardUrl("/").permitAll()
                .and().logout().logoutSuccessUrl("/login");
    }
}
</code>```

userDetailsServise :

```<code>@Service
public class UserDetailsServiceImpl implements UserDetailsService {

    private UserRepository userRepo;

    @Autowired
    public UserDetailsServiceImpl(UserRepository userRepo){
        this.userRepo = userRepo;
    }

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
         User user = userRepo.findByUsername(username);
         if(user != null) {
             System.out.println(user.toString());
             return user;
         }
         throw new UsernameNotFoundException("User "+ username +" not found");
    }
}
</code>```

user entity:

```<code>@Entity
@Table(name = "users")
public class User implements UserDetails {

    @Id
    @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "user_seq")
    @SequenceGenerator(name = "user_seq", sequenceName = "users_id_seq",allocationSize = 1)
    private long id;

    @NotEmpty
    @Column(nullable = false, unique=true)
    private String username;

    @Email
    @Column(nullable = false, updatable = false, unique = true)
    private String email;

    @Column(nullable = false)
    private String password;

    @Column(nullable = false)
    private boolean enabled;

    @CreationTimestamp
    @Column(name = "creation_time")
    private Timestamp creationTime;

    @ElementCollection(fetch = FetchType.EAGER)
    @CollectionTable(joinColumns = @JoinColumn(name="user_id"))
    private List<Authority> authorities;
...
</code>```

logs:

```<code>2019-05-31 19:51:58.888 DEBUG 7181 --- [nio-8080-exec-3] w.a.UsernamePasswordAuthenticationFilter : Request is to process authentication
2019-05-31 19:51:58.889 DEBUG 7181 --- [nio-8080-exec-3] o.s.s.authentication.ProviderManager     : Authentication attempt using org.springframework.security.authentication.dao.DaoAuthenticationProvider
2019-05-31 19:51:59.245 DEBUG 7181 --- [nio-8080-exec-3] tor$SharedEntityManagerInvocationHandler : Creating new EntityManager for shared EntityManager invocation
2019-05-31 19:51:59.388  INFO 7181 --- [nio-8080-exec-3] o.h.h.i.QueryTranslatorFactoryInitiator  : HHH000397: Using ASTQueryTranslatorFactory
Hibernate: select user0_.id as id1_1_, user0_.creation_time as creation2_1_, user0_.email as email3_1_, user0_.enabled as enabled4_1_, user0_.password as password5_1_, user0_.username as username6_1_ from users user0_ where user0_.username=?
Hibernate: select authoritie0_.user_id as user_id1_0_0_, authoritie0_.authorities as authorit2_0_0_ from user_authorities authoritie0_ where authoritie0_.user_id=?
User{
id=8
, username='username'
, email='mail@example.com'
, password='$2a$10$TyQ8x0KUP9Nrtzo2ljfNfei4S3h1kFpYEb5/CDs2lKSDzMJECQ./q'
, enabled=true
, creationTime=2019-05-31 19:32:12.948
, authorities=[USER]}
2019-05-31 19:51:59.758  WARN 7181 --- [nio-8080-exec-3] o.s.s.c.bcrypt.BCryptPasswordEncoder     : Empty encoded password
2019-05-31 19:51:59.758 DEBUG 7181 --- [nio-8080-exec-3] o.s.s.a.dao.DaoAuthenticationProvider    : Authentication failed: password does not match stored value
2019-05-31 19:51:59.773 DEBUG 7181 --- [nio-8080-exec-3] w.a.UsernamePasswordAuthenticationFilter : Authentication request failed: org.springframework.security.authentication.BadCredentialsException: Bad credentials
</code>```

I create following password encoder and I figure out that spring security gives a null string as encoded password to password encoder.

```<code>@Component
public class MyPasswordEncoder implements PasswordEncoder {

    BCryptPasswordEncoder encoder = new BCryptPasswordEncoder();

    @Override
    public String encode(CharSequence rawPassword) {
        return encoder.encode(rawPassword);
    }

    @Override
    public boolean matches(CharSequence rawPassword, String encodedPassword) {

        System.out.println("raw password: " + rawPassword + "\t encoded passwod: "+ encodedPassword);

        return encoder.matches(rawPassword,encodedPassword);
    }
}
</code>```

logs with custom password encoder:

```<code>2019-06-01 03:19:52.759 DEBUG 7870 --- [nio-8080-exec-5] w.a.UsernamePasswordAuthenticationFilter : Request is to process authentication
2019-06-01 03:19:52.759 DEBUG 7870 --- [nio-8080-exec-5] o.s.s.authentication.ProviderManager     : Authentication attempt using org.springframework.security.authentication.dao.DaoAuthenticationProvider
2019-06-01 03:19:53.036 DEBUG 7870 --- [nio-8080-exec-5] tor$SharedEntityManagerInvocationHandler : Creating new EntityManager for shared EntityManager invocation
2019-06-01 03:19:53.095  INFO 7870 --- [nio-8080-exec-5] o.h.h.i.QueryTranslatorFactoryInitiator  : HHH000397: Using ASTQueryTranslatorFactory
Hibernate: select user0_.id as id1_1_, user0_.creation_time as creation2_1_, user0_.email as email3_1_, user0_.enabled as enabled4_1_, user0_.password as password5_1_, user0_.username as username6_1_ from users user0_ where user0_.username=?
Hibernate: select authoritie0_.user_id as user_id1_0_0_, authoritie0_.authorities as authorit2_0_0_ from user_authorities authoritie0_ where authoritie0_.user_id=?
User{
id=8
, username='username'
, email='mail@example.com'
, password='$2a$10$TyQ8x0KUP9Nrtzo2ljfNfei4S3h1kFpYEb5/CDs2lKSDzMJECQ./q'
, enabled=true
, creationTime=2019-05-31 19:32:12.948
, authorities=[USER]}
raw password: password   encoded passwod: null
2019-06-01 03:19:53.413  WARN 7870 --- [nio-8080-exec-5] o.s.s.c.bcrypt.BCryptPasswordEncoder     : Empty encoded password
2019-06-01 03:19:53.413 DEBUG 7870 --- [nio-8080-exec-5] o.s.s.a.dao.DaoAuthenticationProvider    : Authentication failed: password does not match stored value
2019-06-01 03:19:53.415 DEBUG 7870 --- [nio-8080-exec-5] w.a.UsernamePasswordAuthenticationFilter : Authentication request failed: org.springframework.security.authentication.BadCredentialsException: Bad credentials
</code>```

full source on github : https://github.com/yrostami/spring_sample

答:
BCryptPasswordEncoder will compare the password from the loaded user with the password entered from the login form to see if they match. If the former is null , it will give Empty encoded password warning.

So by looking at how you load the users  , it turns out that your UserDetailsService will always return an User with a null password because you hardcode it in getPassword() (Btw, getUsername() also has the same problem). So change to following should fix it :

```<code>@Override
public String getPassword() {
    return this.password;
}

@Override
public String getUsername() {
    return this.username;
}
</code>```

Body:
I am using spring security with BCrypt Password encoder for authentication. when i want to login, Spring security fetchs user data with JPA correctly but for checking raw password with encoded password it gives null string as encoded password to password encoder.

spring security config :

@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    @Qualifier("userDetailsServiceImpl")
    private UserDetailsService userDetailsService;

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

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception{
        auth.userDetailsService(userDetailsService)
        .passwordEncoder(passwordEncoder());
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests()
                .antMatchers("/").hasAuthority("USER")
                .antMatchers("/css/**","/font/**","/js/**","/image/**").permitAll()
                .antMatchers("/register").permitAll()
                .and().formLogin().loginPage("/login").successForwardUrl("/").permitAll()
                .and().logout().logoutSuccessUrl("/login");
    }
}

userDetailsServise :

@Service
public class UserDetailsServiceImpl implements UserDetailsService {

    private UserRepository userRepo;

    @Autowired
    public UserDetailsServiceImpl(UserRepository userRepo){
        this.userRepo = userRepo;
    }

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
         User user = userRepo.findByUsername(username);
         if(user != null) {
             System.out.println(user.toString());
             return user;
         }
         throw new UsernameNotFoundException("User "+ username +" not found");
    }
}

user entity:

@Entity
@Table(name = "users")
public class User implements UserDetails {

    @Id
    @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "user_seq")
    @SequenceGenerator(name = "user_seq", sequenceName = "users_id_seq",allocationSize = 1)
    private long id;

    @NotEmpty
    @Column(nullable = false, unique=true)
    private String username;

    @Email
    @Column(nullable = false, updatable = false, unique = true)
    private String email;

    @Column(nullable = false)
    private String password;

    @Column(nullable = false)
    private boolean enabled;

    @CreationTimestamp
    @Column(name = "creation_time")
    private Timestamp creationTime;

    @ElementCollection(fetch = FetchType.EAGER)
    @CollectionTable(joinColumns = @JoinColumn(name="user_id"))
    private List<Authority> authorities;
...

logs:

2019-05-31 19:51:58.888 DEBUG 7181 --- [nio-8080-exec-3] w.a.UsernamePasswordAuthenticationFilter : Request is to process authentication
2019-05-31 19:51:58.889 DEBUG 7181 --- [nio-8080-exec-3] o.s.s.authentication.ProviderManager     : Authentication attempt using org.springframework.security.authentication.dao.DaoAuthenticationProvider
2019-05-31 19:51:59.245 DEBUG 7181 --- [nio-8080-exec-3] tor$SharedEntityManagerInvocationHandler : Creating new EntityManager for shared EntityManager invocation
2019-05-31 19:51:59.388  INFO 7181 --- [nio-8080-exec-3] o.h.h.i.QueryTranslatorFactoryInitiator  : HHH000397: Using ASTQueryTranslatorFactory
Hibernate: select user0_.id as id1_1_, user0_.creation_time as creation2_1_, user0_.email as email3_1_, user0_.enabled as enabled4_1_, user0_.password as password5_1_, user0_.username as username6_1_ from users user0_ where user0_.username=?
Hibernate: select authoritie0_.user_id as user_id1_0_0_, authoritie0_.authorities as authorit2_0_0_ from user_authorities authoritie0_ where authoritie0_.user_id=?
User{
id=8
, username='username'
, email='mail@example.com'
, password='$2a$10$TyQ8x0KUP9Nrtzo2ljfNfei4S3h1kFpYEb5/CDs2lKSDzMJECQ./q'
, enabled=true
, creationTime=2019-05-31 19:32:12.948
, authorities=[USER]}
2019-05-31 19:51:59.758  WARN 7181 --- [nio-8080-exec-3] o.s.s.c.bcrypt.BCryptPasswordEncoder     : Empty encoded password
2019-05-31 19:51:59.758 DEBUG 7181 --- [nio-8080-exec-3] o.s.s.a.dao.DaoAuthenticationProvider    : Authentication failed: password does not match stored value
2019-05-31 19:51:59.773 DEBUG 7181 --- [nio-8080-exec-3] w.a.UsernamePasswordAuthenticationFilter : Authentication request failed: org.springframework.security.authentication.BadCredentialsException: Bad credentials

I create following password encoder and I figure out that spring security gives a null string as encoded password to password encoder.

@Component
public class MyPasswordEncoder implements PasswordEncoder {

    BCryptPasswordEncoder encoder = new BCryptPasswordEncoder();

    @Override
    public String encode(CharSequence rawPassword) {
        return encoder.encode(rawPassword);
    }

    @Override
    public boolean matches(CharSequence rawPassword, String encodedPassword) {

        System.out.println("raw password: " + rawPassword + "\t encoded passwod: "+ encodedPassword);

        return encoder.matches(rawPassword,encodedPassword);
    }
}

logs with custom password encoder:

2019-06-01 03:19:52.759 DEBUG 7870 --- [nio-8080-exec-5] w.a.UsernamePasswordAuthenticationFilter : Request is to process authentication
2019-06-01 03:19:52.759 DEBUG 7870 --- [nio-8080-exec-5] o.s.s.authentication.ProviderManager     : Authentication attempt using org.springframework.security.authentication.dao.DaoAuthenticationProvider
2019-06-01 03:19:53.036 DEBUG 7870 --- [nio-8080-exec-5] tor$SharedEntityManagerInvocationHandler : Creating new EntityManager for shared EntityManager invocation
2019-06-01 03:19:53.095  INFO 7870 --- [nio-8080-exec-5] o.h.h.i.QueryTranslatorFactoryInitiator  : HHH000397: Using ASTQueryTranslatorFactory
Hibernate: select user0_.id as id1_1_, user0_.creation_time as creation2_1_, user0_.email as email3_1_, user0_.enabled as enabled4_1_, user0_.password as password5_1_, user0_.username as username6_1_ from users user0_ where user0_.username=?
Hibernate: select authoritie0_.user_id as user_id1_0_0_, authoritie0_.authorities as authorit2_0_0_ from user_authorities authoritie0_ where authoritie0_.user_id=?
User{
id=8
, username='username'
, email='mail@example.com'
, password='$2a$10$TyQ8x0KUP9Nrtzo2ljfNfei4S3h1kFpYEb5/CDs2lKSDzMJECQ./q'
, enabled=true
, creationTime=2019-05-31 19:32:12.948
, authorities=[USER]}
raw password: password   encoded passwod: null
2019-06-01 03:19:53.413  WARN 7870 --- [nio-8080-exec-5] o.s.s.c.bcrypt.BCryptPasswordEncoder     : Empty encoded password
2019-06-01 03:19:53.413 DEBUG 7870 --- [nio-8080-exec-5] o.s.s.a.dao.DaoAuthenticationProvider    : Authentication failed: password does not match stored value
2019-06-01 03:19:53.415 DEBUG 7870 --- [nio-8080-exec-5] w.a.UsernamePasswordAuthenticationFilter : Authentication request failed: org.springframework.security.authentication.BadCredentialsException: Bad credentials

full source on github : https://github.com/yrostami/spring_sample

Body:
BCryptPasswordEncoder will compare the password from the loaded user with the password entered from the login form to see if they match. If the former is null , it will give Empty encoded password warning.

So by looking at how you load the users  , it turns out that your UserDetailsService will always return an User with a null password because you hardcode it in getPassword() (Btw, getUsername() also has the same problem). So change to following should fix it :

@Override
public String getPassword() {
    return this.password;
}

@Override
public String getUsername() {
    return this.username;
}


问:
how to access a table where my table name is a variable
I want to access a table, but the name of the table is stored in a variable.

How do i use this variable to read the table?

Example :

```<code>DATA1 <- data.frame(SR = c(1:10), VALUE = seq(1,100,10))   #### has 10 rows
DATA2<- data.frame(SR = c(1:11), VALUE = seq(1,110,10))  #### has 11 rows
DATA3<- data.frame(SR = c(1:12), VALUE = seq(1,120,10))  #### has 12 rows

##### ---- list of data table
DATA_TABLE_LIST <- list(DATA1,DATA2,DATA3)

#### ----- given names to elements of list
names(DATA_TABLE_LIST) <- c("DATA1","DATA2","DATA3"  )

#### ---- identify element of list which has minimum rows
TABLE_NAME <- names(DATA_TABLE_LIST)[which(  sapply(DATA_TABLE_LIST,nrow) == min(sapply(DATA_TABLE_LIST,nrow)))]

####   ---- 'TABLE_NAME' stores the name of a datatable which has the minimum rows ( in this case it is DATA1)
</code>```

How do i access the data table with the name stored in 'TABLE_NAME' ?

答:
While I would recommend you work in a list, you can always use

```<code>> get(TABLE_NAME)
   SR VALUE
1   1     1
2   2    11
3   3    21
4   4    31
5   5    41
6   6    51
7   7    61
8   8    71
9   9    81
10 10    91
</code>```

To use a list, you would do

```<code>> DATA_TABLE_LIST[TABLE_NAME]
$DATA1
   SR VALUE
1   1     1
2   2    11
3   3    21
4   4    31
5   5    41
6   6    51
7   7    61
8   8    71
9   9    81
10 10    91
</code>```

Body:
I want to access a table, but the name of the table is stored in a variable.

How do i use this variable to read the table?

Example :

DATA1 <- data.frame(SR = c(1:10), VALUE = seq(1,100,10))   #### has 10 rows
DATA2<- data.frame(SR = c(1:11), VALUE = seq(1,110,10))  #### has 11 rows
DATA3<- data.frame(SR = c(1:12), VALUE = seq(1,120,10))  #### has 12 rows

##### ---- list of data table
DATA_TABLE_LIST <- list(DATA1,DATA2,DATA3)

#### ----- given names to elements of list
names(DATA_TABLE_LIST) <- c("DATA1","DATA2","DATA3"  )

#### ---- identify element of list which has minimum rows
TABLE_NAME <- names(DATA_TABLE_LIST)[which(  sapply(DATA_TABLE_LIST,nrow) == min(sapply(DATA_TABLE_LIST,nrow)))]

####   ---- 'TABLE_NAME' stores the name of a datatable which has the minimum rows ( in this case it is DATA1)

How do i access the data table with the name stored in 'TABLE_NAME' ?

Body:
While I would recommend you work in a list, you can always use

> get(TABLE_NAME)
   SR VALUE
1   1     1
2   2    11
3   3    21
4   4    31
5   5    41
6   6    51
7   7    61
8   8    71
9   9    81
10 10    91

To use a list, you would do

> DATA_TABLE_LIST[TABLE_NAME]
$DATA1
   SR VALUE
1   1     1
2   2    11
3   3    21
4   4    31
5   5    41
6   6    51
7   7    61
8   8    71
9   9    81
10 10    91


问:
How to draw matplotlib graph in eclipse?
I can draw matplotlib graph in command line(shell) environment, but I find that I could not draw the same graph inside the eclipse IDE. such as plot([1,2,3]) not show in eclipse, I writed show() in the end but still not show anything

my matplotlib use GTKAgg as backend, I use Pydev as plugin of eclipse to develop python.

答:
```
import matplotlib.pyplot as mp
mp.ion()
mp.plot(x,y)
mp.show()
```


问:
MySQL SELECT row based on prefix
Im attempting to do a SELECT on data in a table that contains prefixes, and I have the "keyword".

So unlike a normal search where the prefix/keyword is contained in the row data, and that the prefix/keyword is shorter (or contained in) a possible row of data.

This is the opposite. If have prefixes in rows and I want to find the best matching row based on the (longer) word/phase.

```<code>CREATE TABLE table1 (id INT NOT NULL AUTO_INCREMENT, keyCode VARCHAR(45) NULL, Username VARCHAR(45) NULL, PRIMARY KEY (id));

INSERT INTO table1(keyCode,Username)VALUES('123','Peter')
INSERT INTO table1(keyCode,Username)VALUES('456','Paul')
INSERT INTO table1(keyCode,Username)VALUES('1234','John')

</code>```

Now let's say the phrase I have been given is longer than the prefix in the data.

Like this:

```<code>SELECT * FROM table1 WHERE keyCode LIKE '123456%';
</code>```

I know this will not work, but I would like to return the Row with User 'John'.

How?
(I can use stored procedures)

答:
You can check for the existence of the keyCode prefix at the beginning of your string using LOCATE().  For example:

```<code>SELECT *
FROM table1
WHERE LOCATE(keyCode,'123456') = 1;
</code>```

Title: MySQL SELECT row based on prefix

Body:
Im attempting to do a SELECT on data in a table that contains prefixes, and I have the "keyword".

So unlike a normal search where the prefix/keyword is contained in the row data, and that the prefix/keyword is shorter (or contained in) a possible row of data.

This is the opposite. If have prefixes in rows and I want to find the best matching row based on the (longer) word/phase.

CREATE TABLE table1 (id INT NOT NULL AUTO_INCREMENT, keyCode VARCHAR(45) NULL, Username VARCHAR(45) NULL, PRIMARY KEY (id));

INSERT INTO table1(keyCode,Username)VALUES('123','Peter')
INSERT INTO table1(keyCode,Username)VALUES('456','Paul')
INSERT INTO table1(keyCode,Username)VALUES('1234','John')

Now let's say the phrase I have been given is longer than the prefix in the data.

Like this:

SELECT * FROM table1 WHERE keyCode LIKE '123456%';

I know this will not work, but I would like to return the Row with User 'John'.

How?
(I can use stored procedures)

Body:
You can check for the existence of the keyCode prefix at the beginning of your string using LOCATE().  For example:

SELECT *
FROM table1
WHERE LOCATE(keyCode,'123456') = 1;


问:
Problem with special characters in request header in Tomcat 9
After a recent upgrade to Tomcat 9 from Tomcat 8, I got issues with the request header that has special characters, for my case "<" and ">" characters. Error says "Invalid character found in the request target. The valid characters are defined in RFC 7230 and RFC 3986"

I tried to search around for a way and stumbled upon a solution which says I can add "relaxedQueryChars="<,>" into my server's server.xml but the problem with this solution is that we're not allowed to edit anything in the server as it is managed by puppet so it just gets overwritten every time.

Is there a way to add relaxedQueryChars="<,>" on my application instead of adding it in the server? Somewhere like in context.xml or web.xml, I don't really know.

Error message:

```<code>java.lang.IllegalArgumentException: Invalid character found in the request target. The valid characters are defined in RFC 7230 and RFC 3986
    org.apache.coyote.http11.Http11InputBuffer.parseRequestLine(Http11InputBuffer.java:467)
    org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:294)
    org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:66)
    org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:834)
    org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1415)
    org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49)
    java.base/java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1128)
    java.base/java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:628)
    org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
    java.base/java.lang.Thread.run(Thread.java:834)
</code>```

答:
Sorry, no. relaxedQueryChars is a Connector attribute so it can only be set in server.xml.

Possible options include:

Fixing the application to encode those characters

Updatign the Puppet config to set the required value for relaxedQueryChars

Body:
After a recent upgrade to Tomcat 9 from Tomcat 8, I got issues with the request header that has special characters, for my case "<" and ">" characters. Error says "Invalid character found in the request target. The valid characters are defined in RFC 7230 and RFC 3986"

I tried to search around for a way and stumbled upon a solution which says I can add "relaxedQueryChars="<,>" into my server's server.xml but the problem with this solution is that we're not allowed to edit anything in the server as it is managed by puppet so it just gets overwritten every time.

Is there a way to add relaxedQueryChars="<,>" on my application instead of adding it in the server? Somewhere like in context.xml or web.xml, I don't really know.

Error message:

java.lang.IllegalArgumentException: Invalid character found in the request target. The valid characters are defined in RFC 7230 and RFC 3986
    org.apache.coyote.http11.Http11InputBuffer.parseRequestLine(Http11InputBuffer.java:467)
    org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:294)
    org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:66)
    org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:834)
    org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1415)
    org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49)
    java.base/java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1128)
    java.base/java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:628)
    org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
    java.base/java.lang.Thread.run(Thread.java:834)


问:
Flask file download: filename persists within the session
I have a flask site and a webform that generates excel files. The problem I'm having is, if I send the user back to the form to submit again, the previous file -- with same file name and data -- is downloaded even though new files are generated in the tmp directory. So, I think this has to do with my session variable.

I add a timestamp to the file name with this function to make sure the file names are unique:

```<code>def rightnow():
    return dt.datetime.now().strftime("%m%d%y%h%m%S%f")
</code>```

In routes.py, here is the call for the download:

```<code>@app.route('/download/', methods=['POST','GET'])
def download_file():
    output_file = session.get('new_file', None)
    r = send_file(output_file, attachment_filename=output_file, as_attachment=True)
    return r
</code>```

This is the code for the script that generates the excel files:

```<code>new_file = 'output_' + rightnow() + '.xlsx'
writer = pd.ExcelWriter('tmp/' + new_file, engine='xlsxwriter')
df.to_excel(writer, sheet_name="data")
writer.save()
session['new_file'] = 'tmp/' + new_file
</code>```

The download statement from the template page:

```<code><a class="button" href="{{url_for('download_file')}}">Download new data</a>
</code>```

I have a "Submit Again" button tied to simple javascript

```<code><button onclick="goBack()">Submit Again</button>
<script>//for "revise search" button
function goBack() {
    window.history.back();
}
</script>
</code>```

I have played around with session.clear() with no success.

How can I drop the session when the user click's the "Submit Again" button so the saved file name is dropped?

EDIT: I checked the variables for the filename and the session variable and they are identical, and different from the file name assigned on download. Forinstance, the file is named 'output_May0554733504.xlsx' by the script that I wrote -- I can see it in the tmp directory. But when I go to download the file, the filename is different: 'output_May0536794357.xlsx'

This other file name is not that of a different file in the tmp directory. Any file I download will be 'output_May0536794357.xlsx'.

答: If session.pop('new_file') doesn't work, you could try session.modified = True to force the change to the session.

Body:
I have a flask site and a webform that generates excel files. The problem I'm having is, if I send the user back to the form to submit again, the previous file -- with same file name and data -- is downloaded even though new files are generated in the tmp directory. So, I think this has to do with my session variable.

I add a timestamp to the file name with this function to make sure the file names are unique:

def rightnow():
    return dt.datetime.now().strftime("%m%d%y%h%m%S%f")

In routes.py, here is the call for the download:

@app.route('/download/', methods=['POST','GET'])
def download_file():
    output_file = session.get('new_file', None)
    r = send_file(output_file, attachment_filename=output_file, as_attachment=True)
    return r

This is the code for the script that generates the excel files:

new_file = 'output_' + rightnow() + '.xlsx'
writer = pd.ExcelWriter('tmp/' + new_file, engine='xlsxwriter')
df.to_excel(writer, sheet_name="data")
writer.save()
session['new_file'] = 'tmp/' + new_file

The download statement from the template page:

Download new data

I have a "Submit Again" button tied to simple javascript

<button onclick="goBack()">Submit Again</button>

I have played around with session.clear() with no success.

How can I drop the session when the user click's the "Submit Again" button so the saved file name is dropped?

EDIT: I checked the variables for the filename and the session variable and they are identical, and different from the file name assigned on download. Forinstance, the file is named 'output_May0554733504.xlsx' by the script that I wrote -- I can see it in the tmp directory. But when I go to download the file, the filename is different: 'output_May0536794357.xlsx'

This other file name is not that of a different file in the tmp directory. Any file I download will be 'output_May0536794357.xlsx'.


问:
Methods for quickly calculating standard deviation of large number set in Numpy
What's the best(fastest) way to do this?

This generates what I believe is the correct answer, but obviously at N = 10e6 it is painfully slow. I think I need to keep the Xi values so I can correctly calculate the standard deviation, but are there any techniques to make this run faster?

```<code>def randomInterval(a,b):
    r = ((b-a)*float(random.random(1)) + a)
    return r

N = 10e6
Sum = 0
x = []
for sample in range(0,int(N)):
    n = randomInterval(-5.,5.)
    while n == 5.0:
        n = randomInterval(-5.,5.) # since X is [-5,5)
    Sum += n
    x = np.append(x, n)

A = Sum/N

for sample in range(0,int(N)):
    summation = (x[sample] - A)**2.0

standard_deviation = np.sqrt((1./N)*summation)
</code>```

答:
You made a decent attempt, but should make sure you understand this and don't copy explicitly since this is HW

```<code>import numpy as np
N = int(1e6)
a = np.random.uniform(-5,5,size=(N,))
standard_deviation = np.std(a)
</code>```

This assumes you can use a package like numpy (you tagged it as such). If you can, there are a whole host of methods that allow you to create and do operations on arrays of data, thus avoiding explicit looping (it's done under the hood in an efficient manner). It would be good to take a look at the documentation to see what features are available and how to use them:

http://docs.scipy.org/doc/numpy/reference/index.html

Body:
What's the best(fastest) way to do this?

This generates what I believe is the correct answer, but obviously at N = 10e6 it is painfully slow. I think I need to keep the Xi values so I can correctly calculate the standard deviation, but are there any techniques to make this run faster?

def randomInterval(a,b):
    r = ((b-a)*float(random.random(1)) + a)
    return r

N = 10e6
Sum = 0
x = []
for sample in range(0,int(N)):
    n = randomInterval(-5.,5.)
    while n == 5.0:
        n = randomInterval(-5.,5.) # since X is [-5,5)
    Sum += n
    x = np.append(x, n)

A = Sum/N

for sample in range(0,int(N)):
    summation = (x[sample] - A)**2.0

standard_deviation = np.sqrt((1./N)*summation)

Body:
You made a decent attempt, but should make sure you understand this and don't copy explicitly since this is HW

import numpy as np
N = int(1e6)
a = np.random.uniform(-5,5,size=(N,))
standard_deviation = np.std(a)

This assumes you can use a package like numpy (you tagged it as such). If you can, there are a whole host of methods that allow you to create and do operations on arrays of data, thus avoiding explicit looping (it's done under the hood in an efficient manner). It would be good to take a look at the documentation to see what features are available and how to use them:

http://docs.scipy.org/doc/numpy/reference/index.html


问:
Previous layout get clicked from overlaped layout in Activity
I have two reletive layout. First has spinner and recyclerview and second has a imageview. Second layout overlap first layout on button click. But when I click on second layout, first layout spinner and recylerview get clicked and it shows on second layout.</p>

答:
When you click on ImageView that click event is propagated to view under it automatically. If you block click event after using in ImageView then it will not trigger any click events on ImageView.

e.g.

```<code>class TouchBlockingImageView(context: Context?, attrs: AttributeSet?) : ImageView(context, attrs) {

    override fun onTouchEvent(event: MotionEvent?): Boolean {
        // Use your logic to handle click event
        return true
    }

}
</code>```

If we return true in onTouchEvent then android will not pass that touch event to next layer bellow.

Body:
When you click on ImageView that click event is propagated to view under it automatically. If you block click event after using in ImageView then it will not trigger any click events on ImageView.

e.g.

class TouchBlockingImageView(context: Context?, attrs: AttributeSet?) : ImageView(context, attrs) {

    override fun onTouchEvent(event: MotionEvent?): Boolean {
        // Use your logic to handle click event
        return true
    }

}

If we return true in onTouchEvent then android will not pass that touch event to next layer bellow.


问:
vim: How do I map <F5> to prepend a timestamp to the current word the cursor is on?
In vim, when I press F5, I want it to add a timestamp immediately before the word that the cursor is on.

For example: If I have a file with the following text:

```<code>the quick brown
fox jumps
over the lazy
dog
</code>```

and I press F5 while my cursor is on any of the letters in the word jumps, then I want it to add a timestamp immediately before the word jumps, so that it looks like below:

```<code>the quick brown
fox [ 12:34:50 20190531 ] jumps
over the lazy
dog
</code>```

If I move my cursor to any of the letters in the word dog and press F5, then I want it to look like this:

```<code>the quick brown
fox [ 12:34:50 20190531 ] jumps
over the lazy
[ 12:34:58 20190531 ] dog
</code>```

I currently have these lines in my .vimrc that will add a timestamp wherever the cursor is, but I want it to be a little smarter and add the timestamp immediately before the current word that the cursor is on:

```<code>nmap <F5> i<C-R>=strftime("[ %H:%M:%S %Y%m%d ] ")<CR>
imap <F5> <C-R>=strftime("[ %H:%M:%S %Y%m%d ] ")<CR>
</code>```

答:
The safest option is to use visual mode here:

```<code>nnoremap <F5> viWo<Esc>"=strftime("[ %H:%M:%S %Y%m%d ] ")<CR>gP
inoremap <F5> <C-O>viWo<Esc><C-R>=strftime("[ %H:%M:%S %Y%m%d ] ")<CR>
</code>```

That is, go visual mode, select inner WORD, go to the start of selection, end visual mode, put strftime().

Body:
In vim, when I press F5, I want it to add a timestamp immediately before the word that the cursor is on.

For example: If I have a file with the following text:

the quick brown
fox jumps
over the lazy
dog

and I press F5 while my cursor is on any of the letters in the word jumps, then I want it to add a timestamp immediately before the word jumps, so that it looks like below:

the quick brown
fox [ 12:34:50 20190531 ] jumps
over the lazy
dog

If I move my cursor to any of the letters in the word dog and press F5, then I want it to look like this:

the quick brown
fox [ 12:34:50 20190531 ] jumps
over the lazy
[ 12:34:58 20190531 ] dog

I currently have these lines in my .vimrc that will add a timestamp wherever the cursor is, but I want it to be a little smarter and add the timestamp immediately before the current word that the cursor is on:

nmap <F5> i<C-R>=strftime("[ %H:%M:%S %Y%m%d ] ")<CR>
imap <F5> <C-R>=strftime("[ %H:%M:%S %Y%m%d ] ")<CR>

Body:
The safest option is to use visual mode here:

nnoremap <F5> viWo<Esc>"=strftime("[ %H:%M:%S %Y%m%d ] ")<CR>gP
inoremap <F5> <C-O>viWo<Esc><C-R>=strftime("[ %H:%M:%S %Y%m%d ] ")<CR>

That is, go visual mode, select inner WORD, go to the start of selection, end visual mode, put strftime().


问:
Divide customers in classes based on the number of purchases and find who belongs in what range?
I have a table called: purchases

```<code>id |id_customer|id_product|date_of_purchase
1    1             1         2019-03-04
2    2             2         2019-02-05
3    3             3         2019-01-03
4    4             4         2019-01-10
5    5             5         2019-01-02
6    1             1         2019-03-05
7    1             3         2019-03-23
8    1             4         2019-03-23
9    1             3         2019-03-12
10   2             3         2019-03-23
11   2             1         2019-03-11
</code>```

Here is the code I have tried:

```<code>SELECT id_customer , count(id_customer) as times_bought,
CASE
    WHEN times_bought < 2 THEN "rare"
    WHEN times_bought >1 and times_bought < 4 THEN "neutral"
    ELSE "frequent"
END
FROM purchases;
</code>```

aside from the fact that the script may have many issues it gives times_bought is not a known column. What do you suggest?

答:
You should use a subquery for obtain the count and then join with your main select  </p>

```<code>select  id_customer
   , t.times_bought
  , CASE
    WHEN t.times_bought < 2 THEN "rare"
    WHEN t.times_bought >=2 and t.times_bought < 4 THEN "neutral"
    ELSE "frequent"
    END
from purchases
INNER JOIN (
    select  id_customer , count(date_of_purchase)  times_bought
    from  FROM purchases
    grouo by id_customer
  ) t on t.id_customer = purchases.id_customer
</code>```

Body:
I have a table called: purchases

id |id_customer|id_product|date_of_purchase
1    1             1         2019-03-04
2    2             2         2019-02-05
3    3             3         2019-01-03
4    4             4         2019-01-10
5    5             5         2019-01-02
6    1             1         2019-03-05
7    1             3         2019-03-23
8    1             4         2019-03-23
9    1             3         2019-03-12
10   2             3         2019-03-23
11   2             1         2019-03-11

Here is the code I have tried:

SELECT id_customer , count(id_customer) as times_bought,
CASE
    WHEN times_bought < 2 THEN "rare"
    WHEN times_bought >1 and times_bought < 4 THEN "neutral"
    ELSE "frequent"
END
FROM purchases;

aside from the fact that the script may have many issues it gives times_bought is not a known column. What do you suggest?

Body:
You should use a subquery for obtain the count and then join with your main select

select  id_customer
   , t.times_bought
  , CASE
    WHEN t.times_bought < 2 THEN "rare"
    WHEN t.times_bought >=2 and t.times_bought < 4 THEN "neutral"
    ELSE "frequent"
    END
from purchases
INNER JOIN (
    select  id_customer , count(date_of_purchase)  times_bought
    from  FROM purchases
    grouo by id_customer
  ) t on t.id_customer = purchases.id_customer


问:
How to get the xml sub-parameters
How to get the xml sub-parameters?
how to get all the results of category and return a result $category .. category = Test1, Test2

my xml

```<code><xml>
<title>Test 123</title>
<categories>
<category>Test1</category>
<category>Test2</category>
</categories>
</xml>
</code>```

my get code

```<code>$category = htmlspecialchars($item->categories->category, ENT_XML1 | ENT_QUOTES, 'UTF-8');

echo $category; //I want to return Test1, Test2
</code>```

答:
This is what are you searching for?

```<code>$xml = new SimpleXMLElement('<item id="1234">
<property name="country_id">
    <value>4402</value>
</property>
<property name="rc_maintenance_other">
</property>
<property name="claim_right_shareholder">
</property>
<property name="charges_other">
</property>
<property name="other_expenses_heating">
</property>
<property name="unpaid_bills_amount">
</property>
<property name="iv_person_phone">
    <value>03-6756711</value>
</property>
</item>
 ');

foreach ($xml->xpath('//item[@id="1234"]') as $item)
{
    foreach ($item->children() as $child) {
      echo $child['name'] ."\n";
    }
}
</code>```

duplicate question?
Access all children of a certain node with simplexml and php

Title: How to get the xml sub-parameters

Body:
How to get the xml sub-parameters?
how to get all the results of category and return a result $category .. category = Test1, Test2

my xml

<xml>
<title>Test 123</title>
<categories>
<category>Test1</category>
<category>Test2</category>
</categories>
</xml>

my get code

$category = htmlspecialchars($item->categories->category, ENT_XML1 | ENT_QUOTES, 'UTF-8');

echo $category; //I want to return Test1, Test2

Body:
This is what are you searching for?

$xml = new SimpleXMLElement('<item id="1234">
<property name="country_id">
    <value>4402</value>
</property>
<property name="rc_maintenance_other">
</property>
<property name="claim_right_shareholder">
</property>
<property name="charges_other">
</property>
<property name="other_expenses_heating">
</property>
<property name="unpaid_bills_amount">
</property>
<property name="iv_person_phone">
    <value>03-6756711</value>
</property>
</item>
 ');

foreach ($xml->xpath('//item[@id="1234"]') as $item)
{
    foreach ($item->children() as $child) {
      echo $child['name'] ."\n";
    }
}

duplicate question?
Access all children of a certain node with simplexml and php


问:
Is the following implementation making my code parallel?
I had an assignment in Go to parallelize a given loop of a code. I am unsure whether or not my code is parallel.

I tried simply dividing the array i had into two halves, and used a go routine on both halves.

package main

import (
    "fmt"
    "math"
)

type Body struct {
    x, y, vx, vy, mass float64
    r, g, b uint
}

func main() {
    var count uint
    var radius float64
    done := make(chan bool)
    fmt.Scan(&count, &radius)
    bodies := make([]Body, count)
    for i := range bodies {
        b := &bodies[i]
        fmt.Scan(&b.x, &b.y, &b.vx, &b.vy, &b.mass, &b.r, &b.g, &b.b)
    }

    updatedBodies := make([]Body, count)
    copy(updatedBodies, bodies)
    mid := len(updatedBodies)/2

    go func(){
    for i := range updatedBodies[mid:] {
        b := &updatedBodies[i+mid]
        for _, ob := range bodies {
            dx, dy := ob.x - b.x, ob.y - b.y
            if dist := math.Sqrt(dx*dx + dy*dy); dist > 1 { // far enough
                accel := 0.0000000000667 * ob.mass / (dist * dist * dist)
                b.vx += accel * dx
                b.vy += accel * dy
            }
        }
        b.x += b.vx
        b.y += b.vy

    }
    done <- true
}()
    go func(){
        for i := range updatedBodies[:mid] {
        b := &updatedBodies[i]
        for _, ob := range bodies {
            dx, dy := ob.x - b.x, ob.y - b.y
            if dist := math.Sqrt(dx*dx + dy*dy); dist > 1 { // far enough
                accel := 0.0000000000667 * ob.mass / (dist * dist * dist)
                b.vx += accel * dx
                b.vy += accel * dy
            }
        }
        b.x += b.vx
        b.y += b.vy

    }
    done <- true
}()

    <- done
    <- done
    fmt.Println(count)
    fmt.Println(radius)
    for _, b := range updatedBodies {
        fmt.Println(b.x, b.y, b.vx, b.vy, b.mass, b.r, b.g, b.b)
    }
}
```

```for i := range updatedBodies {
        b := &updatedBodies[i]
        for _, ob := range bodies {
            dx, dy := ob.x - b.x, ob.y - b.y
            if dist := math.Sqrt(dx*dx + dy*dy); dist > 1 { // far enough
                accel := 0.0000000000667 * ob.mass / (dist * dist * dist)
                b.vx += accel * dx
                b.vy += accel * dy
            }
        }
        b.x += b.vx
        b.y += b.vy

    }
```

I asked a professor about the code he said I had to recursively run a go routine to make the loop parallel.

答:
Your code does run concurrently*, but not necessarily in a very optimal way.  You've essentially split your workload into two, and you're running both halves concurrently.

[The professor] said I had to recursively run a go routine to make the loop parallel.

This is not true, but I don't know the exact words your professor said, so he may not have been lying to you.  He apparently has some sort of recursive solution in mind. I wouldn't use recursion here, but it would be one way.

It's hard to provide the answer your professor is looking for. The best advice is to ask your professor to explain his intentions.

*concurrency is not parallelism. Please read/watch this.

Body:
I had an assignment in Go to parallelize a given loop of a code. I am unsure whether or not my code is parallel.

I tried simply dividing the array i had into two halves, and used a go routine on both halves.

package main

import (
    "fmt"
    "math"
)

type Body struct {
    x, y, vx, vy, mass float64
    r, g, b uint
}

func main() {
    var count uint
    var radius float64
    done := make(chan bool)
    fmt.Scan(&count, &radius)
    bodies := make([]Body, count)
    for i := range bodies {
        b := &bodies[i]
        fmt.Scan(&b.x, &b.y, &b.vx, &b.vy, &b.mass, &b.r, &b.g, &b.b)
    }

    updatedBodies := make([]Body, count)
    copy(updatedBodies, bodies)
    mid := len(updatedBodies)/2

    go func(){
    for i := range updatedBodies[mid:] {
        b := &updatedBodies[i+mid]
        for _, ob := range bodies {
            dx, dy := ob.x - b.x, ob.y - b.y
            if dist := math.Sqrt(dx*dx + dy*dy); dist > 1 { // far enough
                accel := 0.0000000000667 * ob.mass / (dist * dist * dist)
                b.vx += accel * dx
                b.vy += accel * dy
            }
        }
        b.x += b.vx
        b.y += b.vy

    }
    done <- true
}()
    go func(){
        for i := range updatedBodies[:mid] {
        b := &updatedBodies[i]
        for _, ob := range bodies {
            dx, dy := ob.x - b.x, ob.y - b.y
            if dist := math.Sqrt(dx*dx + dy*dy); dist > 1 { // far enough
                accel := 0.0000000000667 * ob.mass / (dist * dist * dist)
                b.vx += accel * dx
                b.vy += accel * dy
            }
        }
        b.x += b.vx
        b.y += b.vy

    }
    done <- true
}()

    <- done
    <- done
    fmt.Println(count)
    fmt.Println(radius)
    for _, b := range updatedBodies {
        fmt.Println(b.x, b.y, b.vx, b.vy, b.mass, b.r, b.g, b.b)
    }
}

for i := range updatedBodies {
        b := &updatedBodies[i]
        for _, ob := range bodies {
            dx, dy := ob.x - b.x, ob.y - b.y
            if dist := math.Sqrt(dx*dx + dy*dy); dist > 1 { // far enough
                accel := 0.0000000000667 * ob.mass / (dist * dist * dist)
                b.vx += accel * dx
                b.vy += accel * dy
            }
        }
        b.x += b.vx
        b.y += b.vy

    }

I asked a professor about the code he said I had to recursively run a go routine to make the loop parallel.


问:
How to get inline keyboard for a previously sent message?
Consider the following sequence:

A Telegram bot sends a Message with an inline keyboard with InlineKeyboardMarkup to a specific User

When the user hits one of the buttons of an InlineKeyboardMarkup, bot receives a response with a CallbackQuery

CallbackQuery contains a message object, which represents the original message, which was sent in step 1, but as far as I can see in API docs, Message does not contain any information about InlineKeyboardMarkup or reply_markup.

So is it possible to get InlineKeyboardMarkup of the originally sent Message?

If there is no way of getting it, are there any workarounds in this case?

答:
Update 1 June 2019

Recently Telegram Bot API developers added a new field reply_markup of type InlineKeyboardMarkup to a Message object.

So now you can get previously sent keyboard like that: Update.CallbackQuery.Message.ReplyMarkup


问:
I don't know where i am wrong with Js objects
I am passing props to a component and collecting it with getDerivedStateFromProps which is receiving it but on decomposing it is giving undefined

```<code>static getDerivedStateFromProps(nextProps, nextState) {
        console.log(nextProps.imgData);
        console.log(nextProps.imgData.value);
        if (nextProps.imgData.value[nextProps.index]) {
            return nextState = {
                name: nextProps.imgData.value[nextProps.index],
                fileURL: nextProps.imgData.url[nextProps.index]
            }
        }
        return null
    }
</code>```

for first log it gave output:

```<code>imgData:{
url: ["https://firebasestorage.googleapis.com/v0/b/medkit…=media&token=xxxxxx-xxxx-xxxx-xxxx-xxxxxxx"],

valid: true,

value: ["xxxx-xxxx-xxxx-xxxx-1f45d20ffac3.png"]

}
</code>```

for second it gave:

```<code>[]
</code>```

can somebody help me?

答:
I'd try this:</p>

```<code>static getDerivedStateFromProps(nextProps, nextState) {
    let saved = nextProps.imgData;
    console.log(saved);
    console.log(saved.value);
    if (saved.value[nextProps.index]) {
        return nextState = {
            name: nextProps.imgData.value[nextProps.index],
            fileURL: nextProps.imgData.url[nextProps.index]
        }
    }
    return null
}
</code>```

Body:
I am passing props to a component and collecting it with getDerivedStateFromProps which is receiving it but on decomposing it is giving undefined

static getDerivedStateFromProps(nextProps, nextState) {
        console.log(nextProps.imgData);
        console.log(nextProps.imgData.value);
        if (nextProps.imgData.value[nextProps.index]) {
            return nextState = {
                name: nextProps.imgData.value[nextProps.index],
                fileURL: nextProps.imgData.url[nextProps.index]
            }
        }
        return null
    }

for first log it gave output:

imgData:{
url: ["https://firebasestorage.googleapis.com/v0/b/medkit…=media&token=xxxxxx-xxxx-xxxx-xxxx-xxxxxxx"],

valid: true,

value: ["xxxx-xxxx-xxxx-xxxx-1f45d20ffac3.png"]

}

for second it gave:

[]

can somebody help me?

Body:
I'd try this:

static getDerivedStateFromProps(nextProps, nextState) {
    let saved = nextProps.imgData;
    console.log(saved);
    console.log(saved.value);
    if (saved.value[nextProps.index]) {
        return nextState = {
            name: nextProps.imgData.value[nextProps.index],
            fileURL: nextProps.imgData.url[nextProps.index]
        }
    }
    return null
}


问:
How to use country flags in node and react
I am working on https://github.com/hjnilsson/country-flags

basically the instruction said just npm install --save svg-country-flags

which i did but I am not sure what how to show the right flag or even the size on the markup or render method in react.

The docs even provided this: http://hjnilsson.github.io/country-flags/

Usually there is some kind of HTML/CSS like  like that but there are no further docs. Any idea?

答:
The repository provides "all the worlds flags in SVG and PNG format". Meaning it's just a collection of images in convenient formats. It also provided functionality to resize images to specific dimensions if needed.

To use it, install the repo as you specified

```<code>npm install svg-country-flags --save
</code>```

It will then download the repository and store the SVGs and PNG in node_modules/svg-country-flags/

To use it just as it is you could just include a flag using the standard img element.

```<code><!doctype html>

<html lang="en">
  <head>
    <meta charset="utf-8">
    <title>Example using svg-country-flags</title>
  </head>

  <body>
    <img src="node_modules/svg-country-flags/svg/no.svg" height="50px" width="50px" title="Norwegian flag" />
  </body>
</html>
</code>```

If you need images of a specific size, read the documentation as to how to do just that.

Body:
The repository provides "all the worlds flags in SVG and PNG format". Meaning it's just a collection of images in convenient formats. It also provided functionality to resize images to specific dimensions if needed.

To use it, install the repo as you specified

npm install svg-country-flags --save

It will then download the repository and store the SVGs and PNG in node_modules/svg-country-flags/

To use it just as it is you could just include a flag using the standard img element.

<!doctype html>

<html lang="en">
  <head>
    <meta charset="utf-8">
    <title>Example using svg-country-flags</title>
  </head>

  <body>
    <img src="node_modules/svg-country-flags/svg/no.svg" height="50px" width="50px" title="Norwegian flag" />
  </body>
</html>

If you need images of a specific size, read the documentation as to how to do just that.


问:
Time measuring overhead in Java
When measuring elapsed time on a low level, I have the choice of using any of these:

```<code>System.currentTimeMillis();
System.nanoTime();
</code>```

Both methods are implemented native. Before digging into any C code, does anyone know if there is any substantial overhead calling one or the other? I mean, if I don't really care about the extra precision, which one would be expected to be less CPU time consuming?

N.B: I'm using the standard Java 1.6 JDK, but the question may be valid for any JRE...

答:
I don't believe you need to worry about the overhead of either. It's so minimal it's barely measurable itself. Here's a quick micro-benchmark of both:

```<code>for (int j = 0; j < 5; j++) {
    long time = System.nanoTime();
    for (int i = 0; i < 1000000; i++) {
        long x = System.currentTimeMillis();
    }
    System.out.println((System.nanoTime() - time) + "ns per million");

    time = System.nanoTime();
    for (int i = 0; i < 1000000; i++) {
        long x = System.nanoTime();
    }
    System.out.println((System.nanoTime() - time) + "ns per million");

    System.out.println();
}
</code>```

And the last result:

```<code>14297079ns per million
29206842ns per million
</code>```

It does appear that System.currentTimeMillis() is twice as fast as System.nanoTime(). However 29ns is going to be much shorter than anything else you'd be measuring anyhow. I'd go for System.nanoTime() for precision and accuracy since it's not associated with clocks.

Title: Time measuring overhead in Java

Body:
When measuring elapsed time on a low level, I have the choice of using any of these:

System.currentTimeMillis();
System.nanoTime();

Both methods are implemented native. Before digging into any C code, does anyone know if there is any substantial overhead calling one or the other? I mean, if I don't really care about the extra precision, which one would be expected to be less CPU time consuming?

N.B: I'm using the standard Java 1.6 JDK, but the question may be valid for any JRE...

Body:
I don't believe you need to worry about the overhead of either. It's so minimal it's barely measurable itself. Here's a quick micro-benchmark of both:

for (int j = 0; j < 5; j++) {
    long time = System.nanoTime();
    for (int i = 0; i < 1000000; i++) {
        long x = System.currentTimeMillis();
    }
    System.out.println((System.nanoTime() - time) + "ns per million");

    time = System.nanoTime();
    for (int i = 0; i < 1000000; i++) {
        long x = System.nanoTime();
    }
    System.out.println((System.nanoTime() - time) + "ns per million");

    System.out.println();
}

And the last result:

14297079ns per million
29206842ns per million

It does appear that System.currentTimeMillis() is twice as fast as System.nanoTime(). However 29ns is going to be much shorter than anything else you'd be measuring anyhow. I'd go for System.nanoTime() for precision and accuracy since it's not associated with clocks.


问:
How to deploy a dockerized php application
I have a Laravel application and docker setup for local development using docker-compose. My source code for the application is kept in BitBucket and now I would like to deploy the application to a Linode instance and serve it from the docker system. How this can be done ? As of now I have a LAMPP image running in Linode and I push my source code to the corresponding path when deployment is triggered. Now I would like to use the same docker image in the server instead of the LAMPP server I am using. How this can be done ? Or this is the correct method of doing it ?

It will be helpful if someone can point out a tutorial or guide for doing this ?

答:
If you are locked on staying with linode, I would try one of these options:

Linode docker machine driver - note that this is a non official docker machine driver.

Linode containers guide - using Kubernetes, which I usually try to avoid for my small-scale apps.

If you are NOT locked on staying with linode, and you wish to avoid the complexities of Kubernetes, I can tell you I have had success with running a docker machine on Digital Ocean - this solution (as most other docker-machine solutions) makes deployment as easy as running it locally.

List of docker machine drivers

Digital Ocean docker machine guide

As for how to get your code PHP code to the container, here is an example Dockerfile I have been using for one of my PHP dockerized apps:

```<code>FROM php:7-apache

# Packages
RUN apt-get -y update && apt-get -y install git zip
RUN a2enmod rewrite && docker-php-ext-install sockets

# App
COPY . .

# Composer
COPY private/composer.phar /usr/local/bin/composer
RUN chmod +x /usr/local/bin/composer
RUN [[ ! -f composer.json ]] || composer install --ansi --no-interaction
</code>```

You can adjust it to your needs.

Body:
If you are locked on staying with linode, I would try one of these options:

Linode docker machine driver - note that this is a non official docker machine driver.

Linode containers guide - using Kubernetes, which I usually try to avoid for my small-scale apps.

If you are NOT locked on staying with linode, and you wish to avoid the complexities of Kubernetes, I can tell you I have had success with running a docker machine on Digital Ocean - this solution (as most other docker-machine solutions) makes deployment as easy as running it locally.

List of docker machine drivers

Digital Ocean docker machine guide

As for how to get your code PHP code to the container, here is an example Dockerfile I have been using for one of my PHP dockerized apps:

FROM php:7-apache

# Packages
RUN apt-get -y update && apt-get -y install git zip
RUN a2enmod rewrite && docker-php-ext-install sockets

# App
COPY . .

# Composer
COPY private/composer.phar /usr/local/bin/composer
RUN chmod +x /usr/local/bin/composer
RUN [[ ! -f composer.json ]] || composer install --ansi --no-interaction

You can adjust it to your needs.


问:
PHPMailer 6 Contact Form with Gmail SMTP
I'm trying to make it so that emails can be sent to my Gmail address rather than my domain name email using a PHPMailer form that is in a Bootstrap website. That is my main goal, and the other is to figure out how to have the form include the person's name, email and a subject populate the email rather than the set subject and "no-reply" email.  Any help I could get on this would be great; I thought I would see if anyone wanted to solve this for the community here before I hire a freelancer. Thanks!!

I've tried several tutorials to solve this as well as trying to combine the existing code I'm posting below with the SMTP Gmail version on the PHPMailer Github page ( https://github.com/PHPMailer/PHPMailer/blob/master/examples/gmail.phps )but I was not successful, I would instead post the working code here to my domain name email than my failed attempts at sending to Gmail.

```<code>    <form id="contact-form" method="post" action="contact.php">

        <div class="messages"></div>
        <div class="controls">

            <div class="form-group">
                <input id="form_name" type="text" name="name" class="form-control" placeholder="Enter your name." required="required">
            </div>

            <div class="form-group">
                <input id="form_email" type="email" name="email" class="form-control" placeholder="Enter your email." required="required">
            </div>

            <div class="form-group">
                <textarea id="form_message" name="message" class="form-control" placeholder="Add your message." rows="4" required="required"></textarea>
            </div>

            <input type="submit" class="btn btn-outline-light btn-sm" value="Send message">

        </div>

    </form>

<?php

use PHPMailer\PHPMailer\PHPMailer;

require './PHPMailer-master/vendor/autoload.php';

$fromEmail = 'noreply@email.com';
$fromName = 'No Reply Email';

$sendToEmail = 'name@mydomain.com';
$sendToName = 'New Website Email Message';

$subject = 'New message from contact form';

$fields = array('name' => 'Name:', 'email' => 'Email:', 'message' => 'Message:');

$okMessage = 'Successfully submitted - we will get back to you soon!';

$errorMessage = 'There was an error while submitting the form. Please try again later';

error_reporting(E_ALL & ~E_NOTICE);

try
{

    if(count($_POST) == 0) throw new \Exception('Form is empty');
    $emailTextHtml .= "<h3>New message from website:</h3><hr>";
    $emailTextHtml .= "<table>";

    foreach ($_POST as $key => $value) {

        if (isset($fields[$key])) {
            $emailTextHtml .= "<tr><th>$fields[$key]</th><td>$value</td></tr>";
        }
    }
    $emailTextHtml .= "</table><hr>";
    $emailTextHtml .= "<p>Have a great day!</p>";

    $mail = new PHPMailer;

    $mail->setFrom($fromEmail, $fromName);
    $mail->addAddress($sendToEmail, $sendToName);
    $mail->addReplyTo($_POST['email'], $_POST['name']);

    $mail->Subject = $subject;

    $mail->Body = $emailTextHtml;
    $mail->isHTML(true);

    if(!$mail->send()) {
        throw new \Exception('Email send failed. ' . $mail->ErrorInfo);
    }

    $responseArray = array('type' => 'success', 'message' => $okMessage);
}
catch (\Exception $e)
{
    $responseArray = array('type' => 'danger', 'message' => $e->getMessage());
}

if (!empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest') {
    $encoded = json_encode($responseArray);

    header('Content-Type: application/json');

    echo $encoded;
}
else {
    echo $responseArray['message'];
}
?>
</code>```

答:
This is what I use for my form mail, change the variables accordingly.</p>

```<code>// PHPMailer
require '/var/www/...../PHPMailer/PHPMailerAutoload.php';

//Create a new PHPMailer instance
$mail = new PHPMailer;

$mail->SMTPOptions = array(
    'ssl' => array(
        'verify_peer' => false,
        'verify_peer_name' => false,
        'allow_self_signed' => true
    )
);

//Tell PHPMailer to use SMTP
$mail->isSMTP();

//Enable SMTP debugging
// 0 = off (for production use)
// 1 = client messages
// 2 = client and server messages
$mail->SMTPDebug = 0;

//Ask for HTML-friendly debug output
$mail->Debugoutput = 'html';

//Set the hostname of the mail server
$mail->Host = 'smtp.gmail.com';
// use
// $mail->Host = gethostbyname('smtp.gmail.com');
// if your network does not support SMTP over IPv6

//Set the SMTP port number - 587 for authenticated TLS, a.k.a. RFC4409 SMTP submission
$mail->Port = 587;

//Set the encryption system to use - ssl (deprecated) or tls
$mail->SMTPSecure = 'tls';

//Whether to use SMTP authentication
$mail->SMTPAuth = true;

//Username to use for SMTP authentication - use full email address for gmail
$mail->Username = "abcdefgh@gmail.com";

//Password to use for SMTP authentication
$mail->Password = "pppppppppppppppp";

//Set who the message is to be sent from
$mail->setFrom($Email, $Name);

//Set an alternative reply-to address
$mail->addReplyTo($Email, $Name);

//Set who the message is to be sent to
$mail->addAddress('myemailaddress@gmail.com', 'Form Mail');

//Set the subject line
$mail->Subject = 'Form Mail";
// END PHP Mailer
$mail->ContentType = 'text/plain';
$mail->isHTML(false);

// $mail->msgHTML("$Message");

$mail->Body = $Message;
//send the message, check for errors
if (!$mail->send()) {
    echo "Mailer Error: " . $mail->ErrorInfo;
} else {
    echo "Thank you for sending your message.";
}
</code>```

Body:
I'm trying to make it so that emails can be sent to my Gmail address rather than my domain name email using a PHPMailer form that is in a Bootstrap website. That is my main goal, and the other is to figure out how to have the form include the person's name, email and a subject populate the email rather than the set subject and "no-reply" email.  Any help I could get on this would be great; I thought I would see if anyone wanted to solve this for the community here before I hire a freelancer. Thanks!!

I've tried several tutorials to solve this as well as trying to combine the existing code I'm posting below with the SMTP Gmail version on the PHPMailer Github page ( https://github.com/PHPMailer/PHPMailer/blob/master/examples/gmail.phps )but I was not successful, I would instead post the working code here to my domain name email than my failed attempts at sending to Gmail.

    <form id="contact-form" method="post" action="contact.php">

                <input id="form_name" type="text" name="name" class="form-control" placeholder="Enter your name." required="required">

                <input id="form_email" type="email" name="email" class="form-control" placeholder="Enter your email." required="required">

                <textarea id="form_message" name="message" class="form-control" placeholder="Add your message." rows="4" required="required"></textarea>

            <input type="submit" class="btn btn-outline-light btn-sm" value="Send message">

    </form>

<?php

use PHPMailer\PHPMailer\PHPMailer;

require './PHPMailer-master/vendor/autoload.php';

$fromEmail = 'noreply@email.com';
$fromName = 'No Reply Email';

$sendToEmail = 'name@mydomain.com';
$sendToName = 'New Website Email Message';

$subject = 'New message from contact form';

$fields = array('name' => 'Name:', 'email' => 'Email:', 'message' => 'Message:');

$okMessage = 'Successfully submitted - we will get back to you soon!';

$errorMessage = 'There was an error while submitting the form. Please try again later';

error_reporting(E_ALL & ~E_NOTICE);

try
{

    if(count($_POST) == 0) throw new \Exception('Form is empty');
    $emailTextHtml .= "
New message from website:

";
    $emailTextHtml .= "
";

    foreach ($_POST as $key => $value) {

        if (isset($fields[$key])) {
            $emailTextHtml .= "
$fields[$key]	$value
";
        }
    }
    $emailTextHtml .= "

";
    $emailTextHtml .= "
Have a great day!
";

    $mail = new PHPMailer;

    $mail->setFrom($fromEmail, $fromName);
    $mail->addAddress($sendToEmail, $sendToName);
    $mail->addReplyTo($_POST['email'], $_POST['name']);

    $mail->Subject = $subject;

    $mail->Body = $emailTextHtml;
    $mail->isHTML(true);

    if(!$mail->send()) {
        throw new \Exception('Email send failed. ' . $mail->ErrorInfo);
    }

    $responseArray = array('type' => 'success', 'message' => $okMessage);
}
catch (\Exception $e)
{
    $responseArray = array('type' => 'danger', 'message' => $e->getMessage());
}

if (!empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest') {
    $encoded = json_encode($responseArray);

    header('Content-Type: application/json');

    echo $encoded;
}
else {
    echo $responseArray['message'];
}
?>

Body:
This is what I use for my form mail, change the variables accordingly.

// PHPMailer
require '/var/www/...../PHPMailer/PHPMailerAutoload.php';

//Create a new PHPMailer instance
$mail = new PHPMailer;

$mail->SMTPOptions = array(
    'ssl' => array(
        'verify_peer' => false,
        'verify_peer_name' => false,
        'allow_self_signed' => true
    )
);

//Tell PHPMailer to use SMTP
$mail->isSMTP();

//Enable SMTP debugging
// 0 = off (for production use)
// 1 = client messages
// 2 = client and server messages
$mail->SMTPDebug = 0;

//Ask for HTML-friendly debug output
$mail->Debugoutput = 'html';

//Set the hostname of the mail server
$mail->Host = 'smtp.gmail.com';
// use
// $mail->Host = gethostbyname('smtp.gmail.com');
// if your network does not support SMTP over IPv6

//Set the SMTP port number - 587 for authenticated TLS, a.k.a. RFC4409 SMTP submission
$mail->Port = 587;

//Set the encryption system to use - ssl (deprecated) or tls
$mail->SMTPSecure = 'tls';

//Whether to use SMTP authentication
$mail->SMTPAuth = true;

//Username to use for SMTP authentication - use full email address for gmail
$mail->Username = "abcdefgh@gmail.com";

//Password to use for SMTP authentication
$mail->Password = "pppppppppppppppp";

//Set who the message is to be sent from
$mail->setFrom($Email, $Name);

//Set an alternative reply-to address
$mail->addReplyTo($Email, $Name);

//Set who the message is to be sent to
$mail->addAddress('myemailaddress@gmail.com', 'Form Mail');

//Set the subject line
$mail->Subject = 'Form Mail";
// END PHP Mailer
$mail->ContentType = 'text/plain';
$mail->isHTML(false);

// $mail->msgHTML("$Message");

$mail->Body = $Message;
//send the message, check for errors
if (!$mail->send()) {
    echo "Mailer Error: " . $mail->ErrorInfo;
} else {
    echo "Thank you for sending your message.";
}


问:
Load S3 Data into AWS SageMaker Notebook
I've just started to experiment with AWS SageMaker and would like to load data from an S3 bucket into a pandas dataframe in my SageMaker python jupyter notebook for analysis.

I could use boto to grab the data from S3, but I'm wondering whether there is a more elegant method as part of the SageMaker framework to do this in my python code?

答:
You could also access your bucket as your file system using s3fs

import s3fs
fs = s3fs.S3FileSystem()

# To List 5 files in your accessible bucket
fs.ls('s3://bucket-name/data/')[:5]

# open it directly
with fs.open(f's3://bucket-name/data/image.png') as f:
    display(Image.open(f))
```