问:
Delete all comments of Wordfile
so I'm trying to delete all comments in a Wordfile per VBA-Code of an Excelfile.

I've tried using

```<code>'Dim ObjWord as Word.Application
ObjWord.ActiveDocument.DeleteAllComments
</code>```

and calling

```<code>Sub RemoveAllComments(Doc As Document)
    Dim n As Long
    Dim oComments As Comments
    Set oComments = Doc.Comments
    For n = oComments.Count To 1 Step -1
    oComments(n).Delete
    Next
    Set oComments = Nothing
End Sub
</code>```

but the first gave me the run-time 'error 4605 command not available' and the second code segment throws an 'error 438 object doesn't support this property or method'.

Is there any other way I could do it?

Edit 1:

```<code>Dim ObjWord As Word.Application
Set ObjWord = LoadWord()
ObjWord.Visible = True
</code>```

is in the Function and it calls LoadWord():

```<code>Function LoadWord() As Word.Application
    Set LoadWord = GetObject(, "Word.Application")
    If MsgBox("Word's already in use klick ok to dismiss all changes", vbOKCancel) = vbCancel Then
        Set LoadWord = Nothing
    End If
    Exit Function
End Function
</code>```

答:
Error 4605 with:

```<code>ObjWord.ActiveDocument.DeleteAllComments
</code>```

indicates the ActiveDocument (if there is one) contains no comments. Since you haven't posted any code relating to how the ActiveDocument (or Doc, in your second sub) is instantiated, or whether you've established that the document concerned even contains any comments, it is impossible to give further advice in that regard.

Furthermore, this:

```<code>Sub RemoveAllComments(Doc As Document)
</code>```

would be invalid. At the very least it would need to be:

```<code>Sub RemoveAllComments(Doc As ObjWord.Document)
</code>```

For the first example, the situation can be remedied with nothing more complicated than:

```<code>On Error Resume Next
ObjWord.ActiveDocument.DeleteAllComments
On Error Goto 0
</code>```

Title: Delete all comments of Wordfile

Body:
so I'm trying to delete all comments in a Wordfile per VBA-Code of an Excelfile.

I've tried using

'Dim ObjWord as Word.Application
ObjWord.ActiveDocument.DeleteAllComments

and calling

Sub RemoveAllComments(Doc As Document)
    Dim n As Long
    Dim oComments As Comments
    Set oComments = Doc.Comments
    For n = oComments.Count To 1 Step -1
    oComments(n).Delete
    Next
    Set oComments = Nothing
End Sub

but the first gave me the run-time 'error 4605 command not available' and the second code segment throws an 'error 438 object doesn't support this property or method'.

Is there any other way I could do it?

Edit 1:

Dim ObjWord As Word.Application
Set ObjWord = LoadWord()
ObjWord.Visible = True

is in the Function and it calls LoadWord():

Function LoadWord() As Word.Application
    Set LoadWord = GetObject(, "Word.Application")
    If MsgBox("Word's already in use klick ok to dismiss all changes", vbOKCancel) = vbCancel Then
        Set LoadWord = Nothing
    End If
    Exit Function
End Function

Body:
Error 4605 with:

ObjWord.ActiveDocument.DeleteAllComments

indicates the ActiveDocument (if there is one) contains no comments. Since you haven't posted any code relating to how the ActiveDocument (or Doc, in your second sub) is instantiated, or whether you've established that the document concerned even contains any comments, it is impossible to give further advice in that regard.

Furthermore, this:

Sub RemoveAllComments(Doc As Document)

would be invalid. At the very least it would need to be:

Sub RemoveAllComments(Doc As ObjWord.Document)

For the first example, the situation can be remedied with nothing more complicated than:

On Error Resume Next
ObjWord.ActiveDocument.DeleteAllComments
On Error Goto 0


来源: stackexchange

问:
conditional compiling three-file project
I have three files:
main.c

```<code>#include <stdio.h>
#include "file3.h"
#define PERMISSION

int main()
{
  #ifdef PERMISSION
  myfunction1();
  #else
  myfunction2();
  #endif // PERMISSION
return 0;
}
</code>```

file2.c

```<code>#include <stdio.h>
#include "file3.h"

#ifdef PERMISSION
void myfunction1()
{
    printf("Inside myfunction1 on file2.c \n");
}
#else
void myfunction2()
{
    printf("Inside myfunction2 on file2.c \n");
}
#endif
</code>```

file3.h

```<code>#ifndef FILE3_H_INCLUDED
#define FILE3_H_INCLUDED

#ifdef PERMISSION
void myfunction1();
#else
void myfunction2();

#endif
#endif
</code>```

I want to control the compilation of the 3-file project with the macro PERMISSION from the main or from the header file. If it is defined I should get all the myfunction1 parts compiled on all three files. If it is not, the myfunction2 parts. But I am getting an error when  ''#define PERMISSION''  is present wether I place it on main.c or on file3.h

Codeblocks shows me that file2 and file3 are defaulting to the else part, so they are not seeing PERMISSION defined. I don't want to put it on all files and modifify all of them when I want it not defined
Right now it's erroing with undefined reference to myfunction1
Maybe I shouldn't put the #ifdef in the header file file3.h but it doesn't work anyway.

How do I get it right?

答:
add it to your compiler command line there is its place

```<code> > I am using Codeblocks. I haven't been able to find the way to pass compiling options to it like in the command line – juan carlos vega oliver 3 hours ago
</code>```

Try under Project -> Build options,  inside tab Compiler settings select tab #defines

ContentLicense: CC BY-SA 4.0

Body:
I have three files:
main.c

#include <stdio.h>
#include "file3.h"
#define PERMISSION

int main()
{
  #ifdef PERMISSION
  myfunction1();
  #else
  myfunction2();
  #endif // PERMISSION
return 0;
}

file2.c

#include <stdio.h>
#include "file3.h"

#ifdef PERMISSION
void myfunction1()
{
    printf("Inside myfunction1 on file2.c \n");
}
#else
void myfunction2()
{
    printf("Inside myfunction2 on file2.c \n");
}
#endif

file3.h

#ifndef FILE3_H_INCLUDED
#define FILE3_H_INCLUDED

#ifdef PERMISSION
void myfunction1();
#else
void myfunction2();

#endif
#endif

I want to control the compilation of the 3-file project with the macro PERMISSION from the main or from the header file. If it is defined I should get all the myfunction1 parts compiled on all three files. If it is not, the myfunction2 parts. But I am getting an error when  ''#define PERMISSION''  is present wether I place it on main.c or on file3.h

Codeblocks shows me that file2 and file3 are defaulting to the else part, so they are not seeing PERMISSION defined. I don't want to put it on all files and modifify all of them when I want it not defined
Right now it's erroing with undefined reference to myfunction1
Maybe I shouldn't put the #ifdef in the header file file3.h but it doesn't work anyway.

How do I get it right?

Body:
add it to your compiler command line there is its place

 > I am using Codeblocks. I haven't been able to find the way to pass compiling options to it like in the command line – juan carlos vega oliver 3 hours ago

Try under Project -> Build options,  inside tab Compiler settings select tab #defines


问:
Question about Java synchronized
The Java documentation says that "it is not possible for two invocations of synchronized methods on the same object to interleave".  What I need to know is whether synchronized will also prevent a synchronized method in two different instances of the same class from interleaving.

E.g. class Worker has method called process().  We have several instances of Worker running in their own threads.  We want to prevent more than one instance running the process() method simultaneously.  Will synchronized do this?

Thanks.

答:
If you make the method process static, it would only allow one invocation of the method at the same time.

If that is not possible, have a static variable, say Integer lock;
And use synchronized (lock) inside your method process.
that is

```<code>process()
{
    synchronized (lock)
    {

        // all your code

    }
}
</code>```

ContentLicense: CC BY-SA 3.0

Title: Question about Java synchronized

Body:
If you make the method process static, it would only allow one invocation of the method at the same time.

If that is not possible, have a static variable, say Integer lock;
And use synchronized (lock) inside your method process.
that is

process()
{
    synchronized (lock)
    {

        // all your code

    }
}


问:
How to set JSON tab as the default view for response in SOAP UI Open Source?
I am using SOAP UI Open Source for REST API testing. I want to set the JSON tab as the default view for response.

The response I get already has content-type set to 'application/json'. It shows the XML tab and I need to click on JSON to view the response. Is there any way that I can achieve this?

I am using SOAP UI Open Source version 5.4.0.

答:
You can do this using a brute force teardown script. I had a teardown script on the project level that opens all test steps, switches to the 'Raw' view and takes a screenshot.
Just tested this one against the flikr sample API by pasting it into the testCase teardown script.

It will open all test steps after a test case has been ran and switch view.
The 'SelectView' function takes either an integer (0-4?) or a string "Source", "JSON Response", "HTML Response" or "Raw"
Tested this in SoapUI 5.5 and 5.2.1

For your situation, having a single TestStep per Test Case will basically allow the view to be opened with the desired response tab.

```<code>import com.eviware.soapui.support.editor.Editor
import java.awt.Component

def getContainers(Component c)
{
    Component[] subC = c.getComponents()
    for (Component d : subC)
    {
        String editorClassName = d.getClass().toString()
        if (editorClassName.contains("ResponseMessageEditor"))
        {
            ((Editor)d).selectView("JSON Response")
        }
    getContainers(d)
    }

}

def uiSupport = com.eviware.soapui.support.UISupport

for (tStep in testCase.testStepList) {
    def panel = uiSupport.showDesktopPanel(tStep)
    com.eviware.soapui.SoapUI.desktop.maximize(panel)
    getContainers(panel)
}

</code>```

Body:
You can do this using a brute force teardown script. I had a teardown script on the project level that opens all test steps, switches to the 'Raw' view and takes a screenshot.
Just tested this one against the flikr sample API by pasting it into the testCase teardown script.

It will open all test steps after a test case has been ran and switch view.
The 'SelectView' function takes either an integer (0-4?) or a string "Source", "JSON Response", "HTML Response" or "Raw"
Tested this in SoapUI 5.5 and 5.2.1

For your situation, having a single TestStep per Test Case will basically allow the view to be opened with the desired response tab.

import com.eviware.soapui.support.editor.Editor
import java.awt.Component

def getContainers(Component c)
{
    Component[] subC = c.getComponents()
    for (Component d : subC)
    {
        String editorClassName = d.getClass().toString()
        if (editorClassName.contains("ResponseMessageEditor"))
        {
            ((Editor)d).selectView("JSON Response")
        }
    getContainers(d)
    }

}

def uiSupport = com.eviware.soapui.support.UISupport

for (tStep in testCase.testStepList) {
    def panel = uiSupport.showDesktopPanel(tStep)
    com.eviware.soapui.SoapUI.desktop.maximize(panel)
    getContainers(panel)
}


问:
Selenium post request python
I need to login to a website, however, it has a hidden recaptcha field that I cannot use send_keys (element not interactable). Is there any possibility of making a POST request with selenium or selenium requests?</p>

答:
With Python you should be able to use something like this:

```<code>webdriver = Firefox()
response = webdriver.request('POST', 'url', data={"x": "y"})
</code>```

Alternatively, execute the POST request via JavaScript:

```<code>jsrequest = '''var xhr = new XMLHttpRequest();
xhr.open('POST', '{{URL}}', false);
xhr.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
xhr.send(param1=value&param2=value2');
return xhr.response;'''

result = driver.execute_script(jsrequest)
</code>```

Title: Selenium post request python

Body:
With Python you should be able to use something like this:

webdriver = Firefox()
response = webdriver.request('POST', 'url', data={"x": "y"})

Alternatively, execute the POST request via JavaScript:

jsrequest = '''var xhr = new XMLHttpRequest();
xhr.open('POST', '{{URL}}', false);
xhr.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
xhr.send(param1=value&param2=value2');
return xhr.response;'''

result = driver.execute_script(jsrequest)


问:
How to use regexp in where clause to filter rows in Postgres?
I have following table in postgres 11.0

col1
col2
col3
col4

NCT00001723
4894402
xenical (orlistat)capsules
xenical

NCT00001724
4894403
xenical (orlistat)capsules
orlistat

NCT00001725
4894404
capsules
capsules

NCT00001726
4894405
insulin
ins

I would like filter above rows such that either col3 = col4 or col3 exact content should be contained in col4.

The desired output is:

col1
col2
col3
col4

NCT00001723
4894402
xenical (orlistat)capsules
xenical

NCT00001724
4894403
xenical (orlistat)capsules
orlistat

NCT00001725
4894404
capsules
capsules

I am trying below query to get this output.

SELECT
    *
FROM
    table
where col3 = col4 or                         --exact match
regexp_matches(col3, '(.*).*\(') = col4 or   --match content before brackets
regexp_matches(col3, '.*\(.*\).*') = col4 --match content in brackets
```

Any suggestions here will be really helpful. Thanks

答:
If I followed you correctly, you could just use word boundaries escape \y:

\y:     matches only at the beginning or end of a word

In your query:

```<code>select * from mytable where col3 ~  ('\y' || col4 || '\y')
</code>```

Demo on DB Fiddle:

col1
col2
col3
col4

NCT00001723
4894402
xenical (orlistat)capsules
xenical

NCT00001724
4894403
xenical (orlistat)capsules
orlistat

NCT00001725
4894404
capsules
capsules

Body:
I have following table in postgres 11.0

col1
col2
col3
col4

NCT00001723
4894402
xenical (orlistat)capsules
xenical

NCT00001724
4894403
xenical (orlistat)capsules
orlistat

NCT00001725
4894404
capsules
capsules

NCT00001726
4894405
insulin
ins

I would like filter above rows such that either col3 = col4 or col3 exact content should be contained in col4.

The desired output is:

col1
col2
col3
col4

NCT00001723
4894402
xenical (orlistat)capsules
xenical

NCT00001724
4894403
xenical (orlistat)capsules
orlistat

NCT00001725
4894404
capsules
capsules

I am trying below query to get this output.

SELECT
    *
FROM
    table
where col3 = col4 or                         --exact match
regexp_matches(col3, '(.*).*\(') = col4 or   --match content before brackets
regexp_matches(col3, '.*\(.*\).*') = col4 --match content in brackets

Any suggestions here will be really helpful. Thanks

Body:
If I followed you correctly, you could just use word boundaries escape \y:

\y:     matches only at the beginning or end of a word

In your query:

select * from mytable where col3 ~  ('\y' || col4 || '\y')

Demo on DB Fiddle:

col1
col2
col3
col4

NCT00001723
4894402
xenical (orlistat)capsules
xenical

NCT00001724
4894403
xenical (orlistat)capsules
orlistat

NCT00001725
4894404
capsules
capsules


问:
MySQLi Repeat Row Depending on Column Quantity Value
I have created a simple SQL statement to display which products customers have purchased from a woo commerce store.

This is working great but i'm struggling to find a SQL function that repeats rows based on a value, maybe one doesn't exist and PHP is required, any help would be great.

Thanks

```<code>CURRENT VIEW

ORDER ID.  |   PRODUCT NAME.   | QTY
-------------------------------------
   123     |       APPLE       |  3
   124     |       ORANGE      |  2
   125     |       PEAR        |  1

DESIRED VIEW

ORDER ID.  |   PRODUCT NAME.   | QTY
-------------------------------------
   123     |       APPLE       |  3
   123     |       APPLE       |  3
   123     |       APPLE       |  3
   124     |       ORANGE      |  2
   124     |       ORANGE      |  2
   125     |       PEAR        |  1

CODE

<?php

// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
 die("Connection failed: " . $conn->connect_error);
}

$sql = "SELECT wppc_wc_customer_lookup.customer_id, wppc_wc_customer_lookup.first_name,
wppc_wc_customer_lookup.last_name, wppc_wc_customer_lookup.email,
wppc_wc_order_stats.customer_id, wppc_wc_order_stats.total_sales,
wppc_wc_order_stats.order_id, wppc_wc_order_stats.date_created, wppc_wc_order_stats.status,
wppc_woocommerce_order_items.order_id, wppc_woocommerce_order_items.order_item_name,
wppc_woocommerce_order_items.order_item_id, wppc_woocommerce_order_itemmeta.order_item_id,
wppc_woocommerce_order_itemmeta.meta_id, wppc_woocommerce_order_itemmeta.meta_key,
wppc_woocommerce_order_itemmeta.meta_value FROM wppc_wc_customer_lookup

LEFT JOIN wppc_wc_order_stats ON wppc_wc_customer_lookup.customer_id =
wppc_wc_order_stats.customer_id

LEFT JOIN wppc_woocommerce_order_items ON wppc_wc_order_stats.order_id =
wppc_woocommerce_order_items.order_id

LEFT JOIN wppc_woocommerce_order_itemmeta ON wppc_woocommerce_order_items.order_item_id =
wppc_woocommerce_order_itemmeta.order_item_id

WHERE wppc_woocommerce_order_itemmeta.meta_key = '_qty' AND
wppc_woocommerce_order_items.order_item_name = 'Product Name' AND
wppc_wc_order_stats.status = 'wc-completed'

ORDER BY wppc_wc_order_stats.date_created DESC";

$result = $conn->query($sql);

echo "<table border=\"1\"><tr>";
echo "<tr><th>Order ID</hr><th>First Name</hr><th>Last Name</hr><th>Email</hr><th>Total</hr>
<th>Order Date</hr><th>Product Name</hr><th>Quantity</hr>";

if ($result->num_rows > 0) {

// output data of each row
while($row = $result->fetch_assoc()) {

echo "<tr><td>".$row["order_id"]. " </td><td> " .$row["first_name"] . " </td><td> " .
$row["last_name"] . " </td> <td> " . $row["email"] . " </td><td> &pound".$row["total_sales"]
. " </td> <td>".$row["date_created"] . " </td> <td> ".$row["order_item_name"] . " </td> <td>
".$row["meta_value"] . " </td></tr> ";

}

} else {
echo "0 results";
}

echo "</table>";

$conn->close();
?>
</code>```

This is working great but i'm struggling to find a SQL function that repeats rows based on a value, maybe one doesn't exist and PHP is required, any help would be great.

答:
the idea is to make multiple select queries with different where clauses;

for instance in this case we need query like this:

```<code>SELECT * FROM table WHERE QTY > 0
UNION ALL
(SELECT * FROM table WHERE QTY > 1)
UNION ALL
(SELECT * FROM table WHERE QTY > 2)
ORDER BY `ORDER ID`
</code>```

so we can create mysql procedure to generate such query depending on maximum qty like so

```<code>CREATE PROCEDURE GetAllProducts()
BEGIN
    select max(QTY) - 1 into @maxQty from table;
    set @resQry = 'SELECT * FROM table WHERE QTY > 0';
    set @i = 0;

    label1:
    LOOP
        IF @i = @maxQty THEN
            leave label1;
        END IF;
        SET @i = @i + 1;
        SET @resQry = CONCAT(@resQry, ' UNION ALL (SELECT * FROM table WHERE QTY > ', @i, ')');
    END LOOP label1;
    SET @resQry = CONCAT(@resQry, ' ORDER BY `ORDER ID`');
    PREPARE stmt FROM @resQry;
    EXECUTE stmt;
END;
</code>```

and then you can call this procedure

```<code>CALL GetAllProducts();
</code>```

Body:
I have created a simple SQL statement to display which products customers have purchased from a woo commerce store.

This is working great but i'm struggling to find a SQL function that repeats rows based on a value, maybe one doesn't exist and PHP is required, any help would be great.

Thanks

CURRENT VIEW

ORDER ID.  |   PRODUCT NAME.   | QTY
-------------------------------------
   123     |       APPLE       |  3
   124     |       ORANGE      |  2
   125     |       PEAR        |  1

DESIRED VIEW

ORDER ID.  |   PRODUCT NAME.   | QTY
-------------------------------------
   123     |       APPLE       |  3
   123     |       APPLE       |  3
   123     |       APPLE       |  3
   124     |       ORANGE      |  2
   124     |       ORANGE      |  2
   125     |       PEAR        |  1

CODE

<?php

// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
 die("Connection failed: " . $conn->connect_error);
}

$sql = "SELECT wppc_wc_customer_lookup.customer_id, wppc_wc_customer_lookup.first_name,
wppc_wc_customer_lookup.last_name, wppc_wc_customer_lookup.email,
wppc_wc_order_stats.customer_id, wppc_wc_order_stats.total_sales,
wppc_wc_order_stats.order_id, wppc_wc_order_stats.date_created, wppc_wc_order_stats.status,
wppc_woocommerce_order_items.order_id, wppc_woocommerce_order_items.order_item_name,
wppc_woocommerce_order_items.order_item_id, wppc_woocommerce_order_itemmeta.order_item_id,
wppc_woocommerce_order_itemmeta.meta_id, wppc_woocommerce_order_itemmeta.meta_key,
wppc_woocommerce_order_itemmeta.meta_value FROM wppc_wc_customer_lookup

LEFT JOIN wppc_wc_order_stats ON wppc_wc_customer_lookup.customer_id =
wppc_wc_order_stats.customer_id

LEFT JOIN wppc_woocommerce_order_items ON wppc_wc_order_stats.order_id =
wppc_woocommerce_order_items.order_id

LEFT JOIN wppc_woocommerce_order_itemmeta ON wppc_woocommerce_order_items.order_item_id =
wppc_woocommerce_order_itemmeta.order_item_id

WHERE wppc_woocommerce_order_itemmeta.meta_key = '_qty' AND
wppc_woocommerce_order_items.order_item_name = 'Product Name' AND
wppc_wc_order_stats.status = 'wc-completed'

ORDER BY wppc_wc_order_stats.date_created DESC";

$result = $conn->query($sql);

echo "

";
echo "
Order ID
First Name
Last Name
Email
Total

Order Date
Product Name
Quantity
";

if ($result->num_rows > 0) {

// output data of each row
while($row = $result->fetch_assoc()) {

echo "
".$row["order_id"]. " 	 " .$row["first_name"] . " 	 " .
$row["last_name"] . " 	  " . $row["email"] . " 	 &pound".$row["total_sales"]
. " 	 ".$row["date_created"] . " 	  ".$row["order_item_name"] . "
".$row["meta_value"] . "
 ";

}

} else {
echo "0 results";
}

echo "
";

$conn->close();
?>

This is working great but i'm struggling to find a SQL function that repeats rows based on a value, maybe one doesn't exist and PHP is required, any help would be great.

Body:
the idea is to make multiple select queries with different where clauses;

for instance in this case we need query like this:

SELECT * FROM table WHERE QTY > 0
UNION ALL
(SELECT * FROM table WHERE QTY > 1)
UNION ALL
(SELECT * FROM table WHERE QTY > 2)
ORDER BY `ORDER ID`

so we can create mysql procedure to generate such query depending on maximum qty like so

CREATE PROCEDURE GetAllProducts()
BEGIN
    select max(QTY) - 1 into @maxQty from table;
    set @resQry = 'SELECT * FROM table WHERE QTY > 0';
    set @i = 0;

    label1:
    LOOP
        IF @i = @maxQty THEN
            leave label1;
        END IF;
        SET @i = @i + 1;
        SET @resQry = CONCAT(@resQry, ' UNION ALL (SELECT * FROM table WHERE QTY > ', @i, ')');
    END LOOP label1;
    SET @resQry = CONCAT(@resQry, ' ORDER BY `ORDER ID`');
    PREPARE stmt FROM @resQry;
    EXECUTE stmt;
END;

and then you can call this procedure

CALL GetAllProducts();


问:
Keycloak with Spring Cloud Gateway
I have tried securing my Spring Cloud Gateway using Keycloak Spring Boot Adapter. It is showing me this error as soon as I add the keycloak-spring-boot-starter dependency :

```<code>**********************************************************

Spring MVC found on classpath, which is incompatible with Spring Cloud Gateway at this time. Please remove spring-boot-starter-web dependency.

**********************************************************
</code>```

This is the stack trace:

```<code>org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'gatewayConfigurationService' defined in class path resource [org/springframework/cloud/gateway/config/GatewayAutoConfiguration.class]: Unsatisfied dependency expressed through method 'gatewayConfigurationService' parameter 1; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'org.springframework.core.convert.ConversionService' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {@org.springframework.beans.factory.annotation.Qualifier(value=webFluxConversionService)}
    at org.springframework.beans.factory.support.ConstructorResolver.createArgumentArray(ConstructorResolver.java:798) ~[spring-beans-5.2.3.RELEASE.jar:5.2.3.RELEASE]
    at org.springframework.beans.factory.support.ConstructorResolver.instantiateUsingFactoryMethod(ConstructorResolver.java:539) ~[spring-beans-5.2.3.RELEASE.jar:5.2.3.RELEASE]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.instantiateUsingFactoryMethod(AbstractAutowireCapableBeanFactory.java:1338) ~[spring-beans-5.2.3.RELEASE.jar:5.2.3.RELEASE]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:1177) ~[spring-beans-5.2.3.RELEASE.jar:5.2.3.RELEASE]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:557) ~[spring-beans-5.2.3.RELEASE.jar:5.2.3.RELEASE]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:517) ~[spring-beans-5.2.3.RELEASE.jar:5.2.3.RELEASE]
    at org.springframework.beans.factory.support.AbstractBeanFactory.lambda$doGetBean$0(AbstractBeanFactory.java:323) ~[spring-beans-5.2.3.RELEASE.jar:5.2.3.RELEASE]
    at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:222) ~[spring-beans-5.2.3.RELEASE.jar:5.2.3.RELEASE]
    at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:321) ~[spring-beans-5.2.3.RELEASE.jar:5.2.3.RELEASE]
    at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:202) ~[spring-beans-5.2.3.RELEASE.jar:5.2.3.RELEASE]
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:879) ~[spring-beans-5.2.3.RELEASE.jar:5.2.3.RELEASE]
    at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:878) ~[spring-context-5.2.3.RELEASE.jar:5.2.3.RELEASE]
    at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:550) ~[spring-context-5.2.3.RELEASE.jar:5.2.3.RELEASE]
    at org.springframework.boot.web.servlet.context.ServletWebServerApplicationContext.refresh(ServletWebServerApplicationContext.java:141) ~[spring-boot-2.2.4.RELEASE.jar:2.2.4.RELEASE]
    at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:747) [spring-boot-2.2.4.RELEASE.jar:2.2.4.RELEASE]
    at org.springframework.boot.SpringApplication.refreshContext(SpringApplication.java:397) [spring-boot-2.2.4.RELEASE.jar:2.2.4.RELEASE]
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:315) [spring-boot-2.2.4.RELEASE.jar:2.2.4.RELEASE]
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:1226) [spring-boot-2.2.4.RELEASE.jar:2.2.4.RELEASE]
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:1215) [spring-boot-2.2.4.RELEASE.jar:2.2.4.RELEASE]
    at com.example.gateway.GatewayApplication.main(GatewayApplication.java:13) [classes/:na]
Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'org.springframework.core.convert.ConversionService' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {@org.springframework.beans.factory.annotation.Qualifier(value=webFluxConversionService)}
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.raiseNoMatchingBeanFound(DefaultListableBeanFactory.java:1695) ~[spring-beans-5.2.3.RELEASE.jar:5.2.3.RELEASE]
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:1253) ~[spring-beans-5.2.3.RELEASE.jar:5.2.3.RELEASE]
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:1207) ~[spring-beans-5.2.3.RELEASE.jar:5.2.3.RELEASE]
    at org.springframework.beans.factory.support.ConstructorResolver.resolveAutowiredArgument(ConstructorResolver.java:885) ~[spring-beans-5.2.3.RELEASE.jar:5.2.3.RELEASE]
    at org.springframework.beans.factory.support.ConstructorResolver.createArgumentArray(ConstructorResolver.java:789) ~[spring-beans-5.2.3.RELEASE.jar:5.2.3.RELEASE]
    ... 19 common frames omitted
</code>```

答:
I use the following pom to resolve the issue:</p>

```<code><properties>
    <java.version>11</java.version>
    <spring-cloud.version>Hoxton.SR4</spring-cloud.version>
</properties>
...
<!-- gateway -->
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
<dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-starter-config</artifactId>
</dependency>
<dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-starter-gateway</artifactId>
</dependency>
<dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
</dependency>
<!-- end of gateway -->

<!-- using CircuitBreaker -->
<dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-starter-circuitbreaker-reactor-resilience4j</artifactId>
</dependency>
<!-- end of CircuitBreaker -->

<!-- oauth2 keycloak -->
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-webflux</artifactId>
</dependency>
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-oauth2-client</artifactId>
</dependency>
<dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-starter-security</artifactId>
</dependency>
<!-- end of oauth2 keycloak -->
</code>```

Title: Keycloak with Spring Cloud Gateway

Body:
I have tried securing my Spring Cloud Gateway using Keycloak Spring Boot Adapter. It is showing me this error as soon as I add the keycloak-spring-boot-starter dependency :

**********************************************************

Spring MVC found on classpath, which is incompatible with Spring Cloud Gateway at this time. Please remove spring-boot-starter-web dependency.

**********************************************************

This is the stack trace:

org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'gatewayConfigurationService' defined in class path resource [org/springframework/cloud/gateway/config/GatewayAutoConfiguration.class]: Unsatisfied dependency expressed through method 'gatewayConfigurationService' parameter 1; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'org.springframework.core.convert.ConversionService' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {@org.springframework.beans.factory.annotation.Qualifier(value=webFluxConversionService)}
    at org.springframework.beans.factory.support.ConstructorResolver.createArgumentArray(ConstructorResolver.java:798) ~[spring-beans-5.2.3.RELEASE.jar:5.2.3.RELEASE]
    at org.springframework.beans.factory.support.ConstructorResolver.instantiateUsingFactoryMethod(ConstructorResolver.java:539) ~[spring-beans-5.2.3.RELEASE.jar:5.2.3.RELEASE]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.instantiateUsingFactoryMethod(AbstractAutowireCapableBeanFactory.java:1338) ~[spring-beans-5.2.3.RELEASE.jar:5.2.3.RELEASE]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:1177) ~[spring-beans-5.2.3.RELEASE.jar:5.2.3.RELEASE]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:557) ~[spring-beans-5.2.3.RELEASE.jar:5.2.3.RELEASE]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:517) ~[spring-beans-5.2.3.RELEASE.jar:5.2.3.RELEASE]
    at org.springframework.beans.factory.support.AbstractBeanFactory.lambda$doGetBean$0(AbstractBeanFactory.java:323) ~[spring-beans-5.2.3.RELEASE.jar:5.2.3.RELEASE]
    at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:222) ~[spring-beans-5.2.3.RELEASE.jar:5.2.3.RELEASE]
    at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:321) ~[spring-beans-5.2.3.RELEASE.jar:5.2.3.RELEASE]
    at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:202) ~[spring-beans-5.2.3.RELEASE.jar:5.2.3.RELEASE]
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:879) ~[spring-beans-5.2.3.RELEASE.jar:5.2.3.RELEASE]
    at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:878) ~[spring-context-5.2.3.RELEASE.jar:5.2.3.RELEASE]
    at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:550) ~[spring-context-5.2.3.RELEASE.jar:5.2.3.RELEASE]
    at org.springframework.boot.web.servlet.context.ServletWebServerApplicationContext.refresh(ServletWebServerApplicationContext.java:141) ~[spring-boot-2.2.4.RELEASE.jar:2.2.4.RELEASE]
    at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:747) [spring-boot-2.2.4.RELEASE.jar:2.2.4.RELEASE]
    at org.springframework.boot.SpringApplication.refreshContext(SpringApplication.java:397) [spring-boot-2.2.4.RELEASE.jar:2.2.4.RELEASE]
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:315) [spring-boot-2.2.4.RELEASE.jar:2.2.4.RELEASE]
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:1226) [spring-boot-2.2.4.RELEASE.jar:2.2.4.RELEASE]
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:1215) [spring-boot-2.2.4.RELEASE.jar:2.2.4.RELEASE]
    at com.example.gateway.GatewayApplication.main(GatewayApplication.java:13) [classes/:na]
Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'org.springframework.core.convert.ConversionService' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {@org.springframework.beans.factory.annotation.Qualifier(value=webFluxConversionService)}
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.raiseNoMatchingBeanFound(DefaultListableBeanFactory.java:1695) ~[spring-beans-5.2.3.RELEASE.jar:5.2.3.RELEASE]
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:1253) ~[spring-beans-5.2.3.RELEASE.jar:5.2.3.RELEASE]
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:1207) ~[spring-beans-5.2.3.RELEASE.jar:5.2.3.RELEASE]
    at org.springframework.beans.factory.support.ConstructorResolver.resolveAutowiredArgument(ConstructorResolver.java:885) ~[spring-beans-5.2.3.RELEASE.jar:5.2.3.RELEASE]
    at org.springframework.beans.factory.support.ConstructorResolver.createArgumentArray(ConstructorResolver.java:789) ~[spring-beans-5.2.3.RELEASE.jar:5.2.3.RELEASE]
    ... 19 common frames omitted

Body:
I use the following pom to resolve the issue:

<properties>
    <java.version>11</java.version>
    <spring-cloud.version>Hoxton.SR4</spring-cloud.version>
</properties>
...
<!-- gateway -->
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
<dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-starter-config</artifactId>
</dependency>
<dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-starter-gateway</artifactId>
</dependency>
<dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
</dependency>
<!-- end of gateway -->

<!-- using CircuitBreaker -->
<dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-starter-circuitbreaker-reactor-resilience4j</artifactId>
</dependency>
<!-- end of CircuitBreaker -->

<!-- oauth2 keycloak -->
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-webflux</artifactId>
</dependency>
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-oauth2-client</artifactId>
</dependency>
<dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-starter-security</artifactId>
</dependency>
<!-- end of oauth2 keycloak -->


问:
I am looking to plot a histogram from the lorenz model
I am looking to plot a histogram from matplotlib, specifically the x1 variable. However, I am having trouble navigating the histogram. At the moment, I have:

```<code>43: h = plt.hist(y[:, 0])
44: h.plot(y[:, 0])
45: h.set_xlabel('$x_1$')
46: plt.show()
</code>```

I am getting the error:  File "/Users/scottdayton/PycharmProjects/Uncertainty Research/lorenz.py", line 44, in
    h.plot(y[:, 0])
AttributeError: 'tuple' object has no attribute 'plot'

How can I get the histogram to plot the values I am getting? (y[:, 0])

答:
You're operating on the tuple returned by plt.hist(). This tuple contains values of histogram bins, bin edges, patches. These are usually not needed for the plot itself.

You should only operate on the plt interface, or preferably OO interface (axes) which you seem to be not using here.

As far as I can understand from the incomplete code, line 44 is not needed.  Fix the line 45 with:

```<code>plt.set_xlabel('$x_1$')
</code>```

Also just make sure to enable the LaTeX support by importing:

```<code>from matplotlib import rc
rc('text', usetex=True)
</code>```

Hopefully, that should fix the issue. For a complete histogram plot please see: PyPlot Text histogram

Body:
I am looking to plot a histogram from matplotlib, specifically the x1 variable. However, I am having trouble navigating the histogram. At the moment, I have:

43: h = plt.hist(y[:, 0])
44: h.plot(y[:, 0])
45: h.set_xlabel('$x_1$')
46: plt.show()

I am getting the error:  File "/Users/scottdayton/PycharmProjects/Uncertainty Research/lorenz.py", line 44, in
    h.plot(y[:, 0])
AttributeError: 'tuple' object has no attribute 'plot'

How can I get the histogram to plot the values I am getting? (y[:, 0])

Body:
You're operating on the tuple returned by plt.hist(). This tuple contains values of histogram bins, bin edges, patches. These are usually not needed for the plot itself.

You should only operate on the plt interface, or preferably OO interface (axes) which you seem to be not using here.

As far as I can understand from the incomplete code, line 44 is not needed.  Fix the line 45 with:

plt.set_xlabel('$x_1$')

Also just make sure to enable the LaTeX support by importing:

from matplotlib import rc
rc('text', usetex=True)

Hopefully, that should fix the issue. For a complete histogram plot please see: PyPlot Text histogram


问:
free country, city database for sql server
have anyone used this before, i need free country, city, IP database for sqlserver</p>

答:
I have used http://www.maxmind.com/app/geolitecity .  It is a less exact version of their paid database.  The free database claims to be "over 99.5% on a country level and 79% on a city level for the US within a 25 mile radius".  You can see their accuracy detailed at http://www.maxmind.com/app/geolite_city_accuracy.

The data is presented as a CSV file containing the starting IP block, ending IP block, and the location.  It is easy enough to load into sqlserver.

APIs in C, C#, PHP, Java, Perl and the free version, GeoLite, has an IPv6 version in addition to the downloadable CSV Format.

OwnerDisplayName: StoneHeart

ContentLicense: CC BY-SA 2.5

OwnerDisplayName: Nathan Voxland


问:
Saving/Loading OrderedDictionary to Session
I am trying to save the OrderedDictionary into the session and reload it.
basically, it is a "Last Played" game list.

for some reason, the dictionary is allays NEW .... anyone can pinpoint the reason?

```<code><%@ WebHandler Language="C#" Class="LastPlayed" %>

using System;
using System.Web;
using System.Web.SessionState;

public class LastPlayed : IHttpHandler, IReadOnlySessionState
{
    public bool IsReusable { get { return false; } }

    public void ProcessRequest (HttpContext context) {

        context.Response.ContentType = "text/plain";

        string GameTitle = context.Request["gt"];
        string GameAlias = context.Request["ga"];

        System.Collections.Specialized.OrderedDictionary GamesDictionary = null;

        if (context.Session["LastPlayed"] != null)
        {
            // Load Dictionary from Session
            GamesDictionary = (System.Collections.Specialized.OrderedDictionary)context.Session["LastPlayed"];
            context.Response.Write("Loaded from Session");
        }
        else
        {
            // Creates and initializes a OrderedDictionary.
            GamesDictionary = new System.Collections.Specialized.OrderedDictionary();
            context.Response.Write("Created New Dictionary");
        }

        try
        {
            if (GamesDictionary.Count >= 5)
                // Remove the last entry from the OrderedDictionary
                GamesDictionary.RemoveAt(GamesDictionary.Count - 1);
            // Insert a new key to the beginning of the OrderedDictionary
            GamesDictionary.Insert(0, GameTitle, GameAlias);
            context.Session["LastPlayed"] = GamesDictionary;
            context.Response.Write("Added");
        }
        catch { context.Response.Write("Duplicate Found."); }
    }

}
</code>```

答:
Avoid double container lookup:</p>

```<code>var GamesDictionary = context.Session["LastPlayed"] as OrderedDictionary;
if (GamesDictionary != null)
{
    // do stuff
}
else
{
    // create new
    GamesDictionary = new OrderedDictionary();

    // probably! - put it inside
    context.Session["LastPlayed"] = GamesDictionary
}
</code>```

Body:
I am trying to save the OrderedDictionary into the session and reload it.
basically, it is a "Last Played" game list.

for some reason, the dictionary is allays NEW .... anyone can pinpoint the reason?

<%@ WebHandler Language="C#" Class="LastPlayed" %>

using System;
using System.Web;
using System.Web.SessionState;

public class LastPlayed : IHttpHandler, IReadOnlySessionState
{
    public bool IsReusable { get { return false; } }

    public void ProcessRequest (HttpContext context) {

        context.Response.ContentType = "text/plain";

        string GameTitle = context.Request["gt"];
        string GameAlias = context.Request["ga"];

        System.Collections.Specialized.OrderedDictionary GamesDictionary = null;

        if (context.Session["LastPlayed"] != null)
        {
            // Load Dictionary from Session
            GamesDictionary = (System.Collections.Specialized.OrderedDictionary)context.Session["LastPlayed"];
            context.Response.Write("Loaded from Session");
        }
        else
        {
            // Creates and initializes a OrderedDictionary.
            GamesDictionary = new System.Collections.Specialized.OrderedDictionary();
            context.Response.Write("Created New Dictionary");
        }

        try
        {
            if (GamesDictionary.Count >= 5)
                // Remove the last entry from the OrderedDictionary
                GamesDictionary.RemoveAt(GamesDictionary.Count - 1);
            // Insert a new key to the beginning of the OrderedDictionary
            GamesDictionary.Insert(0, GameTitle, GameAlias);
            context.Session["LastPlayed"] = GamesDictionary;
            context.Response.Write("Added");
        }
        catch { context.Response.Write("Duplicate Found."); }
    }

}

Body:
Avoid double container lookup:

var GamesDictionary = context.Session["LastPlayed"] as OrderedDictionary;
if (GamesDictionary != null)
{
    // do stuff
}
else
{
    // create new
    GamesDictionary = new OrderedDictionary();

    // probably! - put it inside
    context.Session["LastPlayed"] = GamesDictionary
}


问:
create a new column from existing multiple columns in R
can someone guide me how to create new 4 variables in R? I want to create new 4 variables from the below data in R something like;</p>

```<code>data$VarApple = var1 through var6 = "apple"
data$varBerry = var1 through var6 = "berry"
data$varPear = var1 through var6 = "pear"
data$varBanana = var1 through var6 = "banana"

data = data.frame(var1 = c("apple","pear","berry","apple","pear","banana","berry"),
       var2 = c("banana","apple","berry","apple","banana","banana","berry"),
       var3 = c("berry","pear","pear","apple","berry","banana","apple"),
       var4 = c("apple","banana","apple","pear","berry","pear","berry"),
       var5 = c("banana","pear","pear","apple","apple","banana","berry"),
       var6 = c("pear","berry","apple","apple","banana","banana","apple"))
</code>```

答:
Do you want to create a 1/0 column for each of the unique values in data?

Something like this :

```<code>unique_vals <- unique(unlist(data))
cbind(data, sapply(unique_vals, function(x) +(rowSums(data == x) > 0)))

#    var1   var2   var3   var4   var5   var6 apple pear berry banana
#1  apple banana  berry  apple banana   pear     1    1     1      1
#2   pear  apple   pear banana   pear  berry     1    1     1      1
#3  berry  berry   pear  apple   pear  apple     1    1     1      0
#4  apple  apple  apple   pear  apple  apple     1    1     0      0
#5   pear banana  berry  berry  apple banana     1    1     1      1
#6 banana banana banana   pear banana banana     0    1     0      1
#7  berry  berry  apple  berry  berry  apple     1    0     1      0
</code>```

Body:
can someone guide me how to create new 4 variables in R? I want to create new 4 variables from the below data in R something like;

data$VarApple = var1 through var6 = "apple"
data$varBerry = var1 through var6 = "berry"
data$varPear = var1 through var6 = "pear"
data$varBanana = var1 through var6 = "banana"

data = data.frame(var1 = c("apple","pear","berry","apple","pear","banana","berry"),
       var2 = c("banana","apple","berry","apple","banana","banana","berry"),
       var3 = c("berry","pear","pear","apple","berry","banana","apple"),
       var4 = c("apple","banana","apple","pear","berry","pear","berry"),
       var5 = c("banana","pear","pear","apple","apple","banana","berry"),
       var6 = c("pear","berry","apple","apple","banana","banana","apple"))

Body:
Do you want to create a 1/0 column for each of the unique values in data?

Something like this :

unique_vals <- unique(unlist(data))
cbind(data, sapply(unique_vals, function(x) +(rowSums(data == x) > 0)))

#    var1   var2   var3   var4   var5   var6 apple pear berry banana
#1  apple banana  berry  apple banana   pear     1    1     1      1
#2   pear  apple   pear banana   pear  berry     1    1     1      1
#3  berry  berry   pear  apple   pear  apple     1    1     1      0
#4  apple  apple  apple   pear  apple  apple     1    1     0      0
#5   pear banana  berry  berry  apple banana     1    1     1      1
#6 banana banana banana   pear banana banana     0    1     0      1
#7  berry  berry  apple  berry  berry  apple     1    0     1      0


问:
Is there a way for my spring-boot controller to know a button was pushed in the interface associated?
I'm using Spring boot with maven to develop a a marketplace, i have my items listed in a template and when you over an item, you can add it to your cart, my question is, how to i tell my controller that a specific button on the template was pressed? I know that using django I could just check if a specific post request was made and so something with it after, but I have no idea how to do so using spring
Here's the code:

shop controller:

```<code>@RequestMapping(value = "/shop/{type}",  method = {RequestMethod.POST, RequestMethod.GET})
    public String shop(@PathVariable String type, String movietag, Model model, Principal principal){
        if (movietag == null)
            model.addAttribute("products", productService.listAll());
        else
            model.addAttribute("products", productService.findByMovietag(movietag));
        model.addAttribute("productSearch", new Product());
        model.addAttribute("title", "Shop");
        model.addAttribute("title2", "Check out all the new Movie Arrivals Collection 2020");
        model.addAttribute("type", type);
        model.addAttribute("day", java.sql.Date.valueOf(LocalDate.now()));
        if (principal == null) {
            model.addAttribute("cart", null);
        } else {
            Customer customer = customerService.findCustomerByEmail(principal.getName());
            model.addAttribute("cart", customer.getCart());
        }
        return "shop";
    }
</code>```

shop template:

```<code><!-- Product -->
                    <div class="row">
                        <div th:each="product: ${products}" th:if="${(type=='all') or (type=='new' and product.getDate().equals(day)) or (type=='sale' and product.getPrice()<product.getOldPrice())}" class="col-sm-12 col-md-6 col-lg-4 p-b-50">
                            <!-- Block2 -->
                            <div class="block2">
                                <div class="block2-img wrap-pic-w of-hidden pos-relative" th:classappend="${product.getDate().equals(day)} ? 'block2-labelnew'">
                                    <img th:src="${product.getImage()}" alt="IMG-PRODUCT">

                                    <div class="block2-overlay trans-0-4">
                                        <div class="block2-btn-addcart w-size1 trans-0-4">
                                            <!-- Button -->
                                            <button class="flex-c-m size1 bg4 bo-rad-23 hov1 s-text1 trans-0-4">
                                                Add to Cart
                                            </button>
                                        </div>
                                    </div>
                                </div>

                                <div class="block2-txt p-t-20">
                                    <a href="item.html" th:href="@{|/item/${product.getProductId()}|}" th:text="${product.getName()}" class="block2-name dis-block s-text3 p-b-5"></a>
                                    <span th:if="${product.getPrice()<product.getOldPrice()}" th:text="'$'+${product.getOldPrice()}" class="block2-oldprice m-text7 p-r-5"></span>
                                    <span th:text="'$'+${product.getPrice()}" class="block2-price p-r-5" th:classappend="${product.getPrice()<product.getOldPrice()} ? 'm-text8' : 'm-text6'"></span>
                                </div>
                            </div>
                        </div>
                    </div>
</code>```

答:
you need to pass the id of the button to the controller and can handle the subsequent logic in the controller.

you can get the id of the button onSubmit() event of the button and set the id in the request header and retrieve it in the controller.

Body:
I'm using Spring boot with maven to develop a a marketplace, i have my items listed in a template and when you over an item, you can add it to your cart, my question is, how to i tell my controller that a specific button on the template was pressed? I know that using django I could just check if a specific post request was made and so something with it after, but I have no idea how to do so using spring
Here's the code:

shop controller:

@RequestMapping(value = "/shop/{type}",  method = {RequestMethod.POST, RequestMethod.GET})
    public String shop(@PathVariable String type, String movietag, Model model, Principal principal){
        if (movietag == null)
            model.addAttribute("products", productService.listAll());
        else
            model.addAttribute("products", productService.findByMovietag(movietag));
        model.addAttribute("productSearch", new Product());
        model.addAttribute("title", "Shop");
        model.addAttribute("title2", "Check out all the new Movie Arrivals Collection 2020");
        model.addAttribute("type", type);
        model.addAttribute("day", java.sql.Date.valueOf(LocalDate.now()));
        if (principal == null) {
            model.addAttribute("cart", null);
        } else {
            Customer customer = customerService.findCustomerByEmail(principal.getName());
            model.addAttribute("cart", customer.getCart());
        }
        return "shop";
    }

shop template:

                        <div th:each="product: ${products}" th:if="${(type=='all') or (type=='new' and product.getDate().equals(day)) or (type=='sale' and product.getPrice()<product.getOldPrice())}" class="col-sm-12 col-md-6 col-lg-4 p-b-50">

                                            <button class="flex-c-m size1 bg4 bo-rad-23 hov1 s-text1 trans-0-4">
                                                Add to Cart
                                            </button>

                                    <span th:if="${product.getPrice()<product.getOldPrice()}" th:text="'$'+${product.getOldPrice()}" class="block2-oldprice m-text7 p-r-5">
                                    <span th:text="'$'+${product.getPrice()}" class="block2-price p-r-5" th:classappend="${product.getPrice()<product.getOldPrice()} ? 'm-text8' : 'm-text6'">


问:
Java Serializable Object to Byte Array
Let's say I have a serializable class AppMessage.

I would like to transmit it as byte[] over sockets to another machine where it is rebuilt from the bytes received.

How could I achieve this?

答:
This is just an optimized code form of the accepted answer in case anyone wants to use this in production :</p>

```<code>    public static void byteArrayOps() throws IOException, ClassNotFoundException{

    String str="123";
     byte[] yourBytes = null;

    // Convert to byte[]

    try(ByteArrayOutputStream bos = new ByteArrayOutputStream();
            ObjectOutputStream out =  new ObjectOutputStream(bos);) {

      out.writeObject(str);
      out.flush();
      yourBytes = bos.toByteArray();

    } finally {

    }

    // convert back to Object

    try(ByteArrayInputStream bis = new ByteArrayInputStream(yourBytes);
            ObjectInput in = new ObjectInputStream(bis);) {

      Object o = in.readObject();

    } finally {

    }

}
</code>```

Title: Java Serializable Object to Byte Array

Body:
This is just an optimized code form of the accepted answer in case anyone wants to use this in production :

    public static void byteArrayOps() throws IOException, ClassNotFoundException{

    String str="123";
     byte[] yourBytes = null;

    // Convert to byte[]

    try(ByteArrayOutputStream bos = new ByteArrayOutputStream();
            ObjectOutputStream out =  new ObjectOutputStream(bos);) {

      out.writeObject(str);
      out.flush();
      yourBytes = bos.toByteArray();

    } finally {

    }

    // convert back to Object

    try(ByteArrayInputStream bis = new ByteArrayInputStream(yourBytes);
            ObjectInput in = new ObjectInputStream(bis);) {

      Object o = in.readObject();

    } finally {

    }

}


问:
React Native Webview not loading any url (React native web view not working)
I am trying to implement react native webview component in my application, but the web view is not loading any url its just showing the white page.

```<code>var React = require('react-native');
var{
 View,
 Text,
 StyleSheet,
 WebView
} = React;

module.exports = React.createClass({
 render: function(){
   return(
     <View style={styles.container}>
      <WebView source={{uri: 'https://m.facebook.com'}} style= {styles.webView}/>
     </View>
   );
 }
});

var styles = StyleSheet.create({
   container: {
     flex:1,
     backgroundColor:  '#ff00ff'
   },webView :{
     height: 320,
     width : 200
   }
});
</code>```

Below is the screenshot of the output .

答:
As of June 2020 (noting the date because React Native answers seem to become out-of-date quickly), the simplest solution to this appears to be:

import React from 'react'
import { View, StyleSheet } from 'react-native'
import { WebView } from 'react-native-webview'

export const ComponentWithWebView = () => {
  return (
    <View style={styles.view}>
      <WebView source = {{uri: 'https://www.google.com/'}} />
    </View>
  )
}

const styles = StyleSheet.create({
  view: {
    alignSelf: 'stretch',
    flex: 1,
  }
}
```

This results in a WebView filling the available space and being nested within a View. I believe the typical problems faced when placing a WebView within a View is that View expects children to force the View to expand (that is, a Text component would take up some amount of width and height which the View then accommodates). WebView, on the other hand, expands to the size of the parent component unless a style is passed specifying the width. Therefore, a simple <View><WebView /></View> results in a 0 width and nothing shown on the screen. The earlier solutions of setting the WebView width work well but require either the device dimensions to be fetched (which might not be the desired width) or for the View to have an onLayout function AND have some way to expand the View to the desired space. I found it easiest to just apply the flex: 1 and alignSelf: 'stretch' for the View to fill the space as desired and then WebView to automatically follow suit.

Hope this helps someone before it becomes obsolete!

Body:
I am trying to implement react native webview component in my application, but the web view is not loading any url its just showing the white page.

var React = require('react-native');
var{
 View,
 Text,
 StyleSheet,
 WebView
} = React;

module.exports = React.createClass({
 render: function(){
   return(
     <View style={styles.container}>
      <WebView source={{uri: 'https://m.facebook.com'}} style= {styles.webView}/>
     </View>
   );
 }
});

var styles = StyleSheet.create({
   container: {
     flex:1,
     backgroundColor:  '#ff00ff'
   },webView :{
     height: 320,
     width : 200
   }
});

Below is the screenshot of the output .

Body:
As of June 2020 (noting the date because React Native answers seem to become out-of-date quickly), the simplest solution to this appears to be:

import React from 'react'
import { View, StyleSheet } from 'react-native'
import { WebView } from 'react-native-webview'

export const ComponentWithWebView = () => {
  return (
    <View style={styles.view}>
      <WebView source = {{uri: 'https://www.google.com/'}} />
    </View>
  )
}

const styles = StyleSheet.create({
  view: {
    alignSelf: 'stretch',
    flex: 1,
  }
}

This results in a WebView filling the available space and being nested within a View. I believe the typical problems faced when placing a WebView within a View is that View expects children to force the View to expand (that is, a Text component would take up some amount of width and height which the View then accommodates). WebView, on the other hand, expands to the size of the parent component unless a style is passed specifying the width. Therefore, a simple <View><WebView /></View> results in a 0 width and nothing shown on the screen. The earlier solutions of setting the WebView width work well but require either the device dimensions to be fetched (which might not be the desired width) or for the View to have an onLayout function AND have some way to expand the View to the desired space. I found it easiest to just apply the flex: 1 and alignSelf: 'stretch' for the View to fill the space as desired and then WebView to automatically follow suit.

Hope this helps someone before it becomes obsolete!


问:
Upgrading to Gradle version 4.0.0 broke R8 code shrinking
I have upgraded my gradle version to 4.0.0 from 3.6.3. Android Studio was able to install the app properly when minifyenabled was true and gradle version was 3.6.3 without any issues. On gradle version 4.0.0 and minifyenabled set to true doesn't even install the application. Here is what I see:

```<code>Installation did not succeed.
The application could not be installed: INSTALL_FAILED_INVALID_APK

List of apks:
[0] 'C:\Users\user\Desktop\Projects\Application\app\build\outputs\apk\debug\app-debug.apk'
[1] 'C:\Users\user\Desktop\Projects\Application\module1\build\outputs\apk\debug\module1-debug.apk'
[2] 'C:\Users\user\Desktop\Projects\Application\module2\build\outputs\apk\debug\module2-debug.apk'
[3] 'C:\Users\user\Desktop\Projects\Application\module3\build\outputs\apk\debug\module3-debug.apk'
[4] 'C:\Users\user\Desktop\Projects\Application\module4\build\outputs\apk\debug\module4-debug.apk'
[5] 'C:\Users\user\Desktop\Projects\Application\module5\build\outputs\apk\debug\module5-debug.apk'
The APKs are invalid.
</code>```

build.gradle file:

```<code>android {
    compileSdkVersion androidDependencies.compile_sdk_version
    buildToolsVersion "29.0.3"
    defaultConfig {
        applicationId "com.pills.mydemoapplication"
        minSdkVersion androidDependencies.min_sdk_version
        targetSdkVersion androidDependencies.target_sdk_version
        versionCode 7
        versionName "5.0.2"
        testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
    }
    kotlinOptions {
        jvmTarget = "1.8"
    }
    buildTypes {
        debug {
            minifyEnabled true
            proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
        }
        release {
            minifyEnabled true
            proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
        }
    }
    buildFeatures{
        dataBinding = true
    }
    dynamicFeatures = [":module1", ":module2", ":module3", ":module4", ":module5"]
}
</code>```

Project level build.gradle

```<code>buildscript {
    ext.kotlin_version = '1.3.72'
    repositories {
        google()
        jcenter()

    }
    dependencies {
        classpath "com.android.tools:r8:1.6.84"
        classpath "com.android.tools.build:gradle:4.0.0"
        classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"
        classpath "androidx.navigation:navigation-safe-args-gradle-plugin:2.3.0-beta01"
    }
}
</code>```

答:
Removing the following line from project level build.gradle made it work.

```<code>classpath "com.android.tools:r8:1.6.84"
</code>```

R8 is now bundled with Android Gradle Plugin by default and the version of R8 in AGP is 2.0.74 and I was overriding it with a much older version which broke R8 code shrinking.

Body:
I have upgraded my gradle version to 4.0.0 from 3.6.3. Android Studio was able to install the app properly when minifyenabled was true and gradle version was 3.6.3 without any issues. On gradle version 4.0.0 and minifyenabled set to true doesn't even install the application. Here is what I see:

Installation did not succeed.
The application could not be installed: INSTALL_FAILED_INVALID_APK

List of apks:
[0] 'C:\Users\user\Desktop\Projects\Application\app\build\outputs\apk\debug\app-debug.apk'
[1] 'C:\Users\user\Desktop\Projects\Application\module1\build\outputs\apk\debug\module1-debug.apk'
[2] 'C:\Users\user\Desktop\Projects\Application\module2\build\outputs\apk\debug\module2-debug.apk'
[3] 'C:\Users\user\Desktop\Projects\Application\module3\build\outputs\apk\debug\module3-debug.apk'
[4] 'C:\Users\user\Desktop\Projects\Application\module4\build\outputs\apk\debug\module4-debug.apk'
[5] 'C:\Users\user\Desktop\Projects\Application\module5\build\outputs\apk\debug\module5-debug.apk'
The APKs are invalid.

build.gradle file:

android {
    compileSdkVersion androidDependencies.compile_sdk_version
    buildToolsVersion "29.0.3"
    defaultConfig {
        applicationId "com.pills.mydemoapplication"
        minSdkVersion androidDependencies.min_sdk_version
        targetSdkVersion androidDependencies.target_sdk_version
        versionCode 7
        versionName "5.0.2"
        testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
    }
    kotlinOptions {
        jvmTarget = "1.8"
    }
    buildTypes {
        debug {
            minifyEnabled true
            proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
        }
        release {
            minifyEnabled true
            proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
        }
    }
    buildFeatures{
        dataBinding = true
    }
    dynamicFeatures = [":module1", ":module2", ":module3", ":module4", ":module5"]
}

Project level build.gradle

buildscript {
    ext.kotlin_version = '1.3.72'
    repositories {
        google()
        jcenter()

    }
    dependencies {
        classpath "com.android.tools:r8:1.6.84"
        classpath "com.android.tools.build:gradle:4.0.0"
        classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"
        classpath "androidx.navigation:navigation-safe-args-gradle-plugin:2.3.0-beta01"
    }
}

Body:
Removing the following line from project level build.gradle made it work.

classpath "com.android.tools:r8:1.6.84"

R8 is now bundled with Android Gradle Plugin by default and the version of R8 in AGP is 2.0.74 and I was overriding it with a much older version which broke R8 code shrinking.


问:
Quiz Timer JavaScript
Would anyone be able to check this code and see where I'm going wrong. The quiz should give you 1 minute to answer the questions. If the user completes the quiz in time, it should display the reset button and stop the timer. If the user then clicks the reset button, the quiz should restart with a restarted timer.

If the timer runs out, the quiz displays the reset button.

Thanks for any pointers in the right direction.

const startButton = document.getElementById('start-btn')
const nextButton = document.getElementById('next-btn')
const questionContainerElement = document.getElementById('question-container')
const questionElement = document.getElementById('question')
const answerButtonsElement = document.getElementById('answer-buttons')

let shuffledQuestions, currentQuestionIndex

var timeInMinutes = 1;
var currentTime = Date.parse(new Date());
var deadline = new Date(currentTime + timeInMinutes*60*1000);

function getTimeRemaining(endtime){
  var t = Date.parse(endtime) - Date.parse(new Date());
  var seconds = Math.floor( (t/1000) % 60 );
  var minutes = Math.floor( (t/1000/60) % 60 );
  var hours = Math.floor( (t/(1000*60*60)) % 24 );
  var days = Math.floor( t/(1000*60*60*24) );
  return {
    'total': t,
    'minutes': minutes,
    'seconds': seconds
  };
}

function initializeClock(id, endtime){
  var clock = document.getElementById(id);
  function updateClock(){
    var t = getTimeRemaining(endtime);
    clock.innerHTML = t.minutes + ':' + t.seconds;
    if(t.total<=0){
      clearInterval(timeinterval);
      startButton.innerText = 'Restart'
      startButton.classList.remove('hide')
    }
  }

  updateClock(); // run function once at first to avoid delay
  var timeinterval = setInterval(updateClock,1000);
}

startButton.addEventListener('click', startGame)
nextButton.addEventListener('click', () => {
  currentQuestionIndex++
  setNextQuestion()
})

function startGame() {
  currentTime = Date.parse(new Date());
  deadline = new Date(currentTime + timeInMinutes*60*1000);
  console.log(new Date, deadline)
  initializeClock('clockdiv', deadline);
  startButton.classList.add('hide')
  shuffledQuestions = questions.sort(() => Math.random() - .5)
  currentQuestionIndex = 0
  questionContainerElement.classList.remove('hide')
  setNextQuestion()
}

function setNextQuestion() {
  resetState()
  showQuestion(shuffledQuestions[currentQuestionIndex])
}

function showQuestion(question) {
  questionElement.innerText = question.question
  question.answers.forEach(answer => {
    const button = document.createElement('button')
    button.innerText = answer.text
    button.classList.add('btn')
    if (answer.correct) {
      button.dataset.correct = answer.correct
    }
    button.addEventListener('click', selectAnswer)
    answerButtonsElement.appendChild(button)
  })
}

function resetState() {
  clearStatusClass(document.body)
  nextButton.classList.add('hide')
  while (answerButtonsElement.firstChild) {
    answerButtonsElement.removeChild(answerButtonsElement.firstChild)
  }
}

function selectAnswer(e) {
  const selectedButton = e.target
  const correct = selectedButton.dataset.correct
  setStatusClass(document.body, correct)
  Array.from(answerButtonsElement.children).forEach(button => {
    setStatusClass(button, button.dataset.correct)
  })
  if (shuffledQuestions.length > currentQuestionIndex + 1) {
    nextButton.classList.remove('hide')
  } else {
    startButton.innerText = 'Restart'
    startButton.classList.remove('hide')
  }
}

function setStatusClass(element, correct) {
  clearStatusClass(element)
  if (correct) {
    element.classList.add('correct')
  } else {
    element.classList.add('wrong')
  }
}

function clearStatusClass(element) {
  element.classList.remove('correct')
  element.classList.remove('wrong')
}

const questions = [
  {
    question: 'What is 2 + 2?',
    answers: [
      { text: '4', correct: true },
      { text: '22', correct: false }
    ]
  },
  {
    question: 'Who is the best YouTuber?',
    answers: [
      { text: 'Web Dev Simplified', correct: true },
      { text: 'Traversy Media', correct: true },
      { text: 'Dev Ed', correct: true },
      { text: 'Fun Fun Function', correct: true }
    ]
  },
  {
    question: 'Is web development fun?',
    answers: [
      { text: 'Kinda', correct: false },
      { text: 'YES!!!', correct: true },
      { text: 'Um no', correct: false },
      { text: 'IDK', correct: false }
    ]
  },
  {
    question: 'What is 4 * 2?',
    answers: [
      { text: '6', correct: false },
      { text: '8', correct: true }
    ]
  }
]```
<pre class="snippet-code-css lang-css prettyprint-override"><code>*, * ::before, *::after {
    box-sizing: border-box;
    font-family: 'Gill Sans', 'Gill Sans MT', Calibri, 'Trebuchet MS', sans-serif;
}

:root {
    --hue-neutral: 200;
    --hue-wrong: 0;
    --hue-correct: 145;
}

body{
font-size: 2rem;
--hue: var(--hue-neutral);
padding: 0;
margin: 0;
display: flex;
width: 100vw;
height: 100vh;
text-align: center;
justify-content: center;
align-items: center;
background-color: hsl(var(--hue), 100%, 20%);
}

body.correct {
    --hue: var(--hue-correct);
}

body.wrong {
    --hue: var(--hue-wrong);
}

.container{
    width: 800px;
    max-width: 80%;
    background-color: white;
    border-radius: 5px;
    padding: 10px;
    box-shadow: 0 0 10px 2px;
}

.btn-grid{
    display: grid;
    grid-template-columns: repeat(2, auto);
    gap: 10px;
    margin: 20px 0;
}

.btn{
    font-size: 2rem;
    --hue: var(--hue-neutral);
    border: 1px solid hsl(var(--hue), 100%, 30%);
    background-color: hsl(var(--hue), 100%, 50%);
    height: 50px;
    border-radius: 5px;
    padding: 5px 10px;
    color: white;
    outline: none;
}

.btn:hover{
    border-color: black;
}

.btn-correct {
    --hue: var(--hue-correct);
    color: black;
}

.btn-wrong {
    --hue: var(--hue-wrong);
}

.start-btn, .next-btn{
    font-size: 1.5rem;
    font-weight: bold;
    padding: 10px 20px;
}

.score-btn{
    background-color: coral;
    font-size: 1.5rem;
    font-weight: bold;
    padding: 10px 20px;
}

.controls{
    display: flex;
    justify-content: center;
    align-items: center;
}

.hide {
    display: none;
}

.titlecontainer{
    margin-bottom: 30px;
    margin-top: 30px;
    font-size: 2rem;
}

#time{
    color: red;
    justify-content: left;
    text-align: left;
}</code>```

<!DOCTYPE html>

  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <link href="styles.css" rel="stylesheet">

  <title>Quiz App</title>

Question

        <button class="btn">Answer 1</button>
        <button class="btn">Answer 2</button>
        <button class="btn">Answer 3</button>
        <button class="btn">Answer 4</button>

      <button id="start-btn" class="start-btn btn">Start</button>
      <button id="next-btn" class="next-btn btn hide">Next</button>

```

答:
As I see, the problem is that countdown does not stop when quiz is finished. Countdown works thanks to this line in the function initializeClock

var timeinterval = setInterval(updateClock,1000);

So all you should do is to kill this process with

clearInterval(timeinterval)

when the quiz is over. But here is the problem - you can not reach varyable 'timeinterval' from outside of initializeClock function. The easiest way to solve this is:

Declare 'timeinterval' in the global scope.

Make some changes inside selectAnswer function just like this:

```<code>function selectAnswer(e) {
  const selectedButton = e.target
  const correct = selectedButton.dataset.correct
  setStatusClass(document.body, correct)
  Array.from(answerButtonsElement.children).forEach(button => {
    setStatusClass(button, button.dataset.correct)
  })
  if (shuffledQuestions.length > currentQuestionIndex + 1) {
    nextButton.classList.remove('hide')
  } else {
    // THESE ARE THE OLD 'ELSE' INSTRUCTIONS:
        // startButton.innerText = 'Restart'
    // startButton.classList.remove('hide')

    // HERE BELOW ARE NEW:
    clearInterval(timeinterval) // clear current countdown
    startButton.innerText = 'You finished, restart?'// Little text mod
    startButton.classList.remove('hide') //this is exactly from old version
  }
}
</code>```

Title: Quiz Timer JavaScript

Body:
Would anyone be able to check this code and see where I'm going wrong. The quiz should give you 1 minute to answer the questions. If the user completes the quiz in time, it should display the reset button and stop the timer. If the user then clicks the reset button, the quiz should restart with a restarted timer.

If the timer runs out, the quiz displays the reset button.

Thanks for any pointers in the right direction.

const startButton = document.getElementById('start-btn')
const nextButton = document.getElementById('next-btn')
const questionContainerElement = document.getElementById('question-container')
const questionElement = document.getElementById('question')
const answerButtonsElement = document.getElementById('answer-buttons')

let shuffledQuestions, currentQuestionIndex

var timeInMinutes = 1;
var currentTime = Date.parse(new Date());
var deadline = new Date(currentTime + timeInMinutes*60*1000);

function getTimeRemaining(endtime){
  var t = Date.parse(endtime) - Date.parse(new Date());
  var seconds = Math.floor( (t/1000) % 60 );
  var minutes = Math.floor( (t/1000/60) % 60 );
  var hours = Math.floor( (t/(1000*60*60)) % 24 );
  var days = Math.floor( t/(1000*60*60*24) );
  return {
    'total': t,
    'minutes': minutes,
    'seconds': seconds
  };
}

function initializeClock(id, endtime){
  var clock = document.getElementById(id);
  function updateClock(){
    var t = getTimeRemaining(endtime);
    clock.innerHTML = t.minutes + ':' + t.seconds;
    if(t.total<=0){
      clearInterval(timeinterval);
      startButton.innerText = 'Restart'
      startButton.classList.remove('hide')
    }
  }

  updateClock(); // run function once at first to avoid delay
  var timeinterval = setInterval(updateClock,1000);
}

startButton.addEventListener('click', startGame)
nextButton.addEventListener('click', () => {
  currentQuestionIndex++
  setNextQuestion()
})

function startGame() {
  currentTime = Date.parse(new Date());
  deadline = new Date(currentTime + timeInMinutes*60*1000);
  console.log(new Date, deadline)
  initializeClock('clockdiv', deadline);
  startButton.classList.add('hide')
  shuffledQuestions = questions.sort(() => Math.random() - .5)
  currentQuestionIndex = 0
  questionContainerElement.classList.remove('hide')
  setNextQuestion()
}

function setNextQuestion() {
  resetState()
  showQuestion(shuffledQuestions[currentQuestionIndex])
}

function showQuestion(question) {
  questionElement.innerText = question.question
  question.answers.forEach(answer => {
    const button = document.createElement('button')
    button.innerText = answer.text
    button.classList.add('btn')
    if (answer.correct) {
      button.dataset.correct = answer.correct
    }
    button.addEventListener('click', selectAnswer)
    answerButtonsElement.appendChild(button)
  })
}

function resetState() {
  clearStatusClass(document.body)
  nextButton.classList.add('hide')
  while (answerButtonsElement.firstChild) {
    answerButtonsElement.removeChild(answerButtonsElement.firstChild)
  }
}

function selectAnswer(e) {
  const selectedButton = e.target
  const correct = selectedButton.dataset.correct
  setStatusClass(document.body, correct)
  Array.from(answerButtonsElement.children).forEach(button => {
    setStatusClass(button, button.dataset.correct)
  })
  if (shuffledQuestions.length > currentQuestionIndex + 1) {
    nextButton.classList.remove('hide')
  } else {
    startButton.innerText = 'Restart'
    startButton.classList.remove('hide')
  }
}

function setStatusClass(element, correct) {
  clearStatusClass(element)
  if (correct) {
    element.classList.add('correct')
  } else {
    element.classList.add('wrong')
  }
}

function clearStatusClass(element) {
  element.classList.remove('correct')
  element.classList.remove('wrong')
}

const questions = [
  {
    question: 'What is 2 + 2?',
    answers: [
      { text: '4', correct: true },
      { text: '22', correct: false }
    ]
  },
  {
    question: 'Who is the best YouTuber?',
    answers: [
      { text: 'Web Dev Simplified', correct: true },
      { text: 'Traversy Media', correct: true },
      { text: 'Dev Ed', correct: true },
      { text: 'Fun Fun Function', correct: true }
    ]
  },
  {
    question: 'Is web development fun?',
    answers: [
      { text: 'Kinda', correct: false },
      { text: 'YES!!!', correct: true },
      { text: 'Um no', correct: false },
      { text: 'IDK', correct: false }
    ]
  },
  {
    question: 'What is 4 * 2?',
    answers: [
      { text: '6', correct: false },
      { text: '8', correct: true }
    ]
  }
]

*, * ::before, *::after {
    box-sizing: border-box;
    font-family: 'Gill Sans', 'Gill Sans MT', Calibri, 'Trebuchet MS', sans-serif;
}

:root {
    --hue-neutral: 200;
    --hue-wrong: 0;
    --hue-correct: 145;
}

body{
font-size: 2rem;
--hue: var(--hue-neutral);
padding: 0;
margin: 0;
display: flex;
width: 100vw;
height: 100vh;
text-align: center;
justify-content: center;
align-items: center;
background-color: hsl(var(--hue), 100%, 20%);
}

body.correct {
    --hue: var(--hue-correct);
}

body.wrong {
    --hue: var(--hue-wrong);
}

.container{
    width: 800px;
    max-width: 80%;
    background-color: white;
    border-radius: 5px;
    padding: 10px;
    box-shadow: 0 0 10px 2px;
}

.btn-grid{
    display: grid;
    grid-template-columns: repeat(2, auto);
    gap: 10px;
    margin: 20px 0;
}

.btn{
    font-size: 2rem;
    --hue: var(--hue-neutral);
    border: 1px solid hsl(var(--hue), 100%, 30%);
    background-color: hsl(var(--hue), 100%, 50%);
    height: 50px;
    border-radius: 5px;
    padding: 5px 10px;
    color: white;
    outline: none;
}

.btn:hover{
    border-color: black;
}

.btn-correct {
    --hue: var(--hue-correct);
    color: black;
}

.btn-wrong {
    --hue: var(--hue-wrong);
}

.start-btn, .next-btn{
    font-size: 1.5rem;
    font-weight: bold;
    padding: 10px 20px;
}

.score-btn{
    background-color: coral;
    font-size: 1.5rem;
    font-weight: bold;
    padding: 10px 20px;
}

.controls{
    display: flex;
    justify-content: center;
    align-items: center;
}

.hide {
    display: none;
}

.titlecontainer{
    margin-bottom: 30px;
    margin-top: 30px;
    font-size: 2rem;
}

#time{
    color: red;
    justify-content: left;
    text-align: left;
}

<!DOCTYPE html>

  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <link href="styles.css" rel="stylesheet">

  <title>Quiz App</title>

Question

        <button class="btn">Answer 1</button>
        <button class="btn">Answer 2</button>
        <button class="btn">Answer 3</button>
        <button class="btn">Answer 4</button>

      <button id="start-btn" class="start-btn btn">Start</button>
      <button id="next-btn" class="next-btn btn hide">Next</button>

Body:
As I see, the problem is that countdown does not stop when quiz is finished. Countdown works thanks to this line in the function initializeClock

var timeinterval = setInterval(updateClock,1000);

So all you should do is to kill this process with

clearInterval(timeinterval)

when the quiz is over. But here is the problem - you can not reach varyable 'timeinterval' from outside of initializeClock function. The easiest way to solve this is:

Declare 'timeinterval' in the global scope.

Make some changes inside selectAnswer function just like this:

function selectAnswer(e) {
  const selectedButton = e.target
  const correct = selectedButton.dataset.correct
  setStatusClass(document.body, correct)
  Array.from(answerButtonsElement.children).forEach(button => {
    setStatusClass(button, button.dataset.correct)
  })
  if (shuffledQuestions.length > currentQuestionIndex + 1) {
    nextButton.classList.remove('hide')
  } else {
    // THESE ARE THE OLD 'ELSE' INSTRUCTIONS:
        // startButton.innerText = 'Restart'
    // startButton.classList.remove('hide')

    // HERE BELOW ARE NEW:
    clearInterval(timeinterval) // clear current countdown
    startButton.innerText = 'You finished, restart?'// Little text mod
    startButton.classList.remove('hide') //this is exactly from old version
  }
}


问:
How to fix the adding to CSV file problem?
I have a csv file with 400+ rows and 2 columns containing movies and their genre.
I am trying to add at the end of my existing CSV file a new movie and a new genre.

I wrote this:

```<code>import csv

with open('/Users/Desktop/okok.csv','a') as csvfile:
    writer = csv.writer(csvfile)
    writer.writerow(["newFilm", "newGenre"])
</code>```

When I open the file after running this I see that newFilm was added to the last row, column genre and newGenre, in a new column in the same row.

I would like this:

Taken, Thriller
newFilm, newGenre
```

<p>and I get this:</p>

<pre class="lang-none prettyprint-override"><code>Taken, ThrillernewFilm, newGenre
</code>```

How can I fix this?

答:
okok.csv wasn't a valid CSV file. Python's csv module assumes that each line in a CSV file is terminated with a newline. okok.csv wasn't, so the new row appended to the old row. Garbage in, garbage out.

The writer itself isn't in a position to rewind and check for validity. But you can write your own routine to fix this common bug if you have upstream writers of CSV who don't follow the rules. Call it before opening for your regular update.

```<code>def fix_csv_file_ending(filename):
    with open(filename, "ab+") as fileobj:
        fileobj.seek(-1, 2)
        if fileobj.read() != b"\n":
            fileobj.write(b"\r\n")

# test
lines = b'good\r\ngood\r\n\bad'
open('test.csv', 'wb').write(lines)
fix_csv_file_ending('test.csv')
want = lines + b'\r\n'
got = open('test.csv', 'rb').read()
assert want == got, 'first test'
fix_csv_file_ending('test.csv')
got = open('test.csv', 'rb').read()
assert want == got, 'second test'
print(got)
</code>```

Body:
I have a csv file with 400+ rows and 2 columns containing movies and their genre.
I am trying to add at the end of my existing CSV file a new movie and a new genre.

I wrote this:

import csv

with open('/Users/Desktop/okok.csv','a') as csvfile:
    writer = csv.writer(csvfile)
    writer.writerow(["newFilm", "newGenre"])

When I open the file after running this I see that newFilm was added to the last row, column genre and newGenre, in a new column in the same row.

I would like this:

Taken, Thriller
newFilm, newGenre

and I get this:

Taken, ThrillernewFilm, newGenre

How can I fix this?

Body:
okok.csv wasn't a valid CSV file. Python's csv module assumes that each line in a CSV file is terminated with a newline. okok.csv wasn't, so the new row appended to the old row. Garbage in, garbage out.

The writer itself isn't in a position to rewind and check for validity. But you can write your own routine to fix this common bug if you have upstream writers of CSV who don't follow the rules. Call it before opening for your regular update.

def fix_csv_file_ending(filename):
    with open(filename, "ab+") as fileobj:
        fileobj.seek(-1, 2)
        if fileobj.read() != b"\n":
            fileobj.write(b"\r\n")

# test
lines = b'good\r\ngood\r\n\bad'
open('test.csv', 'wb').write(lines)
fix_csv_file_ending('test.csv')
want = lines + b'\r\n'
got = open('test.csv', 'rb').read()
assert want == got, 'first test'
fix_csv_file_ending('test.csv')
got = open('test.csv', 'rb').read()
assert want == got, 'second test'
print(got)


问:
Adding a JComponent on top of full-screen-graphics
I have a fullscreen program, which draws a lot of things for the game I am making. The canvas is the entire window, which it should be. Now I want to add a button, or textfield (JButton and JTextField etc...) to my window. However, when I add a button, or anything else, they go begind the canvas.

Do you have any idea how to get the button to show up ON the canvas, so I can click it?

Edit:
Drawing code:

```<code>public synchronized void draw(Graphics2D g) {
        if (!welcome)
            g.drawImage(background,0,0,null);

        if (welcome) {
            g.drawImage(new ImageIcon (getClass().getResource("images/backgroundWelcome.jpg")).getImage(), 0,0, null);
        }
        else if (gettingName) {
            setFont (new Font("Verdana", Font.ITALIC, 40));

            g.draw3DRect(center.x -325, center.y -50, 650, 100, true);
            g.drawString("Please enter your name", center.x -250, center.y -120);
            g.drawString(name, center.x -315, center.y);
        }
        if (game) {
            for (Player p: player) {
                int x = center.x;
                int y = center.y;

                switch (p.getID()) {
                case 1:
                    x -= name.length()*10;
                    y *= 1.4;
                    break;
                case 2:
                    x -= name.length()*10;
                    y /= 1.4;
                    break;
                case 3:
                    x *= 1.4;
                    x -= name.length()*10;
                    break;
                case 4:
                    x *= 0.6;
                    x -= name.length()*10;
                    break;
                default:
                    System.out.println("Error 2");
                }
                g.drawString(p.getName(),x,y);
            }
            for (int x = 0; x<13; x++) {
                g.drawImage(diamonds[x].getImage(), (int) diamonds[x].getX(), (int) diamonds[x].getY(), null);
                g.drawImage(clubs[x].getImage(), (int) clubs[x].getX(), (int) clubs[x].getY(), null);
                g.drawImage(hearts[x].getImage(), (int) hearts[x].getX(), (int) hearts[x].getY(), null);
                g.drawImage(spades[x].getImage(), (int) spades[x].getX(), (int) spades[x].getY(), null);
            }
            g.drawImage(put.getImage(), (int) put.getX(), (int) put.getY(), null);
        }

        if (won) {
            g.drawImage(new ImageIcon (getClass().getResource("images/backgroundWelcome.jpg")).getImage(), 0,0, null);
        }
        else if (lost) {
            g.drawImage(new ImageIcon (getClass().getResource("images/backgroundWelcome.jpg")).getImage(), 0,0, null);
        }
    }
</code>```

Edit2:
My frame is a JFrame.

答: You are painting the canvas yourself so you will need to add the button elsewhere or paint an area that looks like a button and check if mouse events fall inside the button's area.</p>

Body:
I have a fullscreen program, which draws a lot of things for the game I am making. The canvas is the entire window, which it should be. Now I want to add a button, or textfield (JButton and JTextField etc...) to my window. However, when I add a button, or anything else, they go begind the canvas.

Do you have any idea how to get the button to show up ON the canvas, so I can click it?

Edit:
Drawing code:

public synchronized void draw(Graphics2D g) {
        if (!welcome)
            g.drawImage(background,0,0,null);

        if (welcome) {
            g.drawImage(new ImageIcon (getClass().getResource("images/backgroundWelcome.jpg")).getImage(), 0,0, null);
        }
        else if (gettingName) {
            setFont (new Font("Verdana", Font.ITALIC, 40));

            g.draw3DRect(center.x -325, center.y -50, 650, 100, true);
            g.drawString("Please enter your name", center.x -250, center.y -120);
            g.drawString(name, center.x -315, center.y);
        }
        if (game) {
            for (Player p: player) {
                int x = center.x;
                int y = center.y;

                switch (p.getID()) {
                case 1:
                    x -= name.length()*10;
                    y *= 1.4;
                    break;
                case 2:
                    x -= name.length()*10;
                    y /= 1.4;
                    break;
                case 3:
                    x *= 1.4;
                    x -= name.length()*10;
                    break;
                case 4:
                    x *= 0.6;
                    x -= name.length()*10;
                    break;
                default:
                    System.out.println("Error 2");
                }
                g.drawString(p.getName(),x,y);
            }
            for (int x = 0; x<13; x++) {
                g.drawImage(diamonds[x].getImage(), (int) diamonds[x].getX(), (int) diamonds[x].getY(), null);
                g.drawImage(clubs[x].getImage(), (int) clubs[x].getX(), (int) clubs[x].getY(), null);
                g.drawImage(hearts[x].getImage(), (int) hearts[x].getX(), (int) hearts[x].getY(), null);
                g.drawImage(spades[x].getImage(), (int) spades[x].getX(), (int) spades[x].getY(), null);
            }
            g.drawImage(put.getImage(), (int) put.getX(), (int) put.getY(), null);
        }

        if (won) {
            g.drawImage(new ImageIcon (getClass().getResource("images/backgroundWelcome.jpg")).getImage(), 0,0, null);
        }
        else if (lost) {
            g.drawImage(new ImageIcon (getClass().getResource("images/backgroundWelcome.jpg")).getImage(), 0,0, null);
        }
    }

Edit2:
My frame is a JFrame.