问:
How to obtain a closeness score bounded between 0 and 1
I would like to calculate the closeness of a network like e.g.

```<code>relations=structure(list(From = c("France", "Italy", "Malta", "Spain",
"Germany", "Austria", "Luxembourg", "Luxembourg", "Luxembourg",
"Greece", "Slovakia", "Belgium", "Luxembourg", "Estonia", "Germany",
"Netherlands", "Netherlands", "Cyprus", "Greece", "Lithuania",
"Estonia", "Greece", "Lithuania", "Slovakia", "Netherlands",
"Luxembourg", "Estonia", "Malta", "Belgium", "Cyprus", "Austria",
"Estonia", "Austria", "Germany", "Austria", "Netherlands", "Portugal",
"Portugal", "Estonia", "Italy", "Spain", "Finland", "Belgium",
"Spain", "Estonia", "Latvia", "Luxembourg", "Luxembourg", "Netherlands",
"Italy", "Lithuania", "Cyprus", "Ireland", "Luxembourg", "Ireland",
"Spain", "Belgium", "Latvia", "Netherlands", "Italy", "Slovenia",
"Netherlands", "Greece", "Spain", "Austria", "Finland", "Malta",
"Spain", "Austria", "Lithuania", "France", "Portugal", "Cyprus",
"Finland", "Spain", "Spain", "Belgium", "Germany", "Germany",
"Greece", "Netherlands", "Luxembourg", "Estonia", "Ireland",
"Italy", "Portugal", "Greece", "Estonia", "Belgium", "Germany",
"Slovenia", "Slovakia", "Lithuania", "Slovenia", "Portugal",
"Portugal", "Slovakia", "France", "Portugal", "Netherlands"),
    To = c("Slovakia", "Germany", "Portugal", "Austria", "Latvia",
    "Cyprus", "Portugal", "Greece", "Italy", "Slovenia", "Ireland",
    "Malta", "Ireland", "Germany", "Cyprus", "Portugal", "Slovenia",
    "Italy", "Luxembourg", "France", "Slovakia", "Netherlands",
    "Greece", "France", "Ireland", "Netherlands", "Cyprus", "Germany",
    "Portugal", "Austria", "Luxembourg", "Austria", "Spain",
    "Netherlands", "Belgium", "Cyprus", "Cyprus", "Luxembourg",
    "Finland", "Belgium", "Lithuania", "Austria", "Spain", "Slovenia",
    "Luxembourg", "Finland", "Slovenia", "Germany", "Austria",
    "Slovenia", "Slovenia", "Portugal", "Finland", "Lithuania",
    "Latvia", "France", "Netherlands", "Cyprus", "Spain", "Malta",
    "France", "Finland", "Belgium", "Latvia", "Slovenia", "Slovenia",
    "Cyprus", "Slovakia", "Slovakia", "Latvia", "Austria", "Ireland",
    "Luxembourg", "Belgium", "Italy", "Estonia", "Greece", "Slovakia",
    "Belgium", "Italy", "Latvia", "Malta", "Greece", "France",
    "Greece", "Netherlands", "France", "Slovenia", "Latvia",
    "Finland", "Austria", "Slovenia", "Belgium", "Cyprus", "Greece",
    "Slovenia", "Cyprus", "Finland", "Malta", "Germany"), weight = c(3.63689639539779e-09,
    2.36155345798604e-11, 1.90981717262912e-08, 1.27550515412245e-09,
    2.75032212941667e-09, 3.79663088493923e-08, 1.42368280746262e-08,
    1.51146811601353e-08, 1.75314892144034e-09, 2.07956027448449e-08,
    1.38623943876156e-07, 1.92893849444567e-08, 5.66419694274739e-08,
    5.8089561312222e-09, 1.95827364947702e-09, 6.7071674411728e-10,
    4.23667746162198e-09, 4.62966220873406e-08, 1.21403390886489e-07,
    1.26979107479853e-08, 5.59978765605208e-07, 3.14788992090851e-09,
    5.0058794053616e-07, 5.22186410794211e-09, 9.21607337940845e-10,
    2.51322812227745e-09, 3.04984607426863e-07, 3.20992561385791e-09,
    8.92180336424503e-10, 6.12766236972513e-08, 1.20231538847898e-08,
    1.34589665048046e-07, 8.84238627642763e-10, 2.63370671763944e-11,
    1.11903749128791e-09, 1.16731679208085e-08, 4.99654438989995e-08,
    2.90162442064053e-08, 2.55621731534268e-09, 1.58298464637584e-10,
    5.07475932446428e-08, 2.54927518867625e-09, 2.24427326793633e-10,
    4.49723284363684e-09, 2.43010060636845e-06, 1.90760030501003e-08,
    6.35902610582491e-08, 5.48833215255332e-10, 4.06612010446768e-10,
    5.32889353797193e-10, 1.23745070305762e-06, 8.89608483306497e-07,
    3.75876719292064e-09, 4.44758324449273e-07, 1.35536579831994e-07,
    5.42265922046125e-11, 4.8233448207134e-11, 3.4286615533894e-07,
    2.0214285544428e-10, 8.57988303618593e-10, 1.35631258148319e-09,
    7.97944858545598e-10, 4.2673026648725e-09, 9.28491399244895e-08,
    1.03420112425729e-09, 2.4972909387896e-08, 8.12118760999133e-07,
    1.31225365800221e-08, 1.77287287047586e-09, 6.53958727055997e-09,
    3.05841917976996e-10, 9.20687775127977e-09, 4.32323785012335e-07,
    8.40653865200987e-10, 1.23500809608508e-10, 6.59008808575339e-08,
    1.13962199159936e-09, 4.68300414991578e-10, 3.54758342726504e-11,
    6.55880483863129e-10, 1.17833628272869e-08, 5.08802989644665e-07,
    7.22191649442396e-07, 2.7028184600344e-10, 2.2810918951755e-10,
    8.10987753872438e-10, 1.50406384816011e-09, 5.46176491471454e-06,
    2.32716789835402e-08, 2.10873259303399e-10, 1.81735402994258e-09,
    9.71369590422109e-09, 2.01941765282435e-08, 1.8961914804496e-07,
    9.4461402995167e-09, 1.69816623519093e-07, 9.16774899583353e-08,
    8.54588845128718e-10, 4.79160495478785e-08, 2.31994460360924e-11
    )), row.names = c(NA, -100L), class = c("tbl_df", "tbl",
"data.frame"))
actors= c("Slovakia", "Germany", "Portugal", "Austria", "Latvia", "Cyprus",
"Greece", "Italy", "Slovenia", "Ireland", "Malta", "Luxembourg",
"France", "Netherlands", "Spain", "Belgium", "Finland", "Lithuania",
"Estonia")
g <- graph_from_data_frame(relations, directed=TRUE, vertices=actors)
</code>```

by using package igraph. Using function closeness I obtain:

```<code>closeness(g)
   Slovakia     Germany    Portugal     Austria      Latvia      Cyprus      Greece       Italy    Slovenia     Ireland
    4002492     7111002     6478738     6502665     2017834     1029940     6615891     7164685     5533119     6240785
      Malta  Luxembourg      France Netherlands       Spain     Belgium     Finland   Lithuania     Estonia
    5071100     7243749     6342911     7121291     7144000     7090895     6415382     3086085     7411727
</code>```

I would like to obtain a normalized closeness score bounded between 0 and 1. It is 0 if a node is an isolate, and 1 if a node is directly connected all others. What can I do

答:
Have you tried normalizing it yourself out of igraph? You might use caret package:

```<code>library(caret)
c1 <-closeness(g)
df <- tibble(actors = actors,
             close = c1)
df_normalized <- df %>%
  preProcess(., method=c("range")) %>%
  predict(., df)

df_normalized

</code>```

Body:
I would like to calculate the closeness of a network like e.g.

relations=structure(list(From = c("France", "Italy", "Malta", "Spain",
"Germany", "Austria", "Luxembourg", "Luxembourg", "Luxembourg",
"Greece", "Slovakia", "Belgium", "Luxembourg", "Estonia", "Germany",
"Netherlands", "Netherlands", "Cyprus", "Greece", "Lithuania",
"Estonia", "Greece", "Lithuania", "Slovakia", "Netherlands",
"Luxembourg", "Estonia", "Malta", "Belgium", "Cyprus", "Austria",
"Estonia", "Austria", "Germany", "Austria", "Netherlands", "Portugal",
"Portugal", "Estonia", "Italy", "Spain", "Finland", "Belgium",
"Spain", "Estonia", "Latvia", "Luxembourg", "Luxembourg", "Netherlands",
"Italy", "Lithuania", "Cyprus", "Ireland", "Luxembourg", "Ireland",
"Spain", "Belgium", "Latvia", "Netherlands", "Italy", "Slovenia",
"Netherlands", "Greece", "Spain", "Austria", "Finland", "Malta",
"Spain", "Austria", "Lithuania", "France", "Portugal", "Cyprus",
"Finland", "Spain", "Spain", "Belgium", "Germany", "Germany",
"Greece", "Netherlands", "Luxembourg", "Estonia", "Ireland",
"Italy", "Portugal", "Greece", "Estonia", "Belgium", "Germany",
"Slovenia", "Slovakia", "Lithuania", "Slovenia", "Portugal",
"Portugal", "Slovakia", "France", "Portugal", "Netherlands"),
    To = c("Slovakia", "Germany", "Portugal", "Austria", "Latvia",
    "Cyprus", "Portugal", "Greece", "Italy", "Slovenia", "Ireland",
    "Malta", "Ireland", "Germany", "Cyprus", "Portugal", "Slovenia",
    "Italy", "Luxembourg", "France", "Slovakia", "Netherlands",
    "Greece", "France", "Ireland", "Netherlands", "Cyprus", "Germany",
    "Portugal", "Austria", "Luxembourg", "Austria", "Spain",
    "Netherlands", "Belgium", "Cyprus", "Cyprus", "Luxembourg",
    "Finland", "Belgium", "Lithuania", "Austria", "Spain", "Slovenia",
    "Luxembourg", "Finland", "Slovenia", "Germany", "Austria",
    "Slovenia", "Slovenia", "Portugal", "Finland", "Lithuania",
    "Latvia", "France", "Netherlands", "Cyprus", "Spain", "Malta",
    "France", "Finland", "Belgium", "Latvia", "Slovenia", "Slovenia",
    "Cyprus", "Slovakia", "Slovakia", "Latvia", "Austria", "Ireland",
    "Luxembourg", "Belgium", "Italy", "Estonia", "Greece", "Slovakia",
    "Belgium", "Italy", "Latvia", "Malta", "Greece", "France",
    "Greece", "Netherlands", "France", "Slovenia", "Latvia",
    "Finland", "Austria", "Slovenia", "Belgium", "Cyprus", "Greece",
    "Slovenia", "Cyprus", "Finland", "Malta", "Germany"), weight = c(3.63689639539779e-09,
    2.36155345798604e-11, 1.90981717262912e-08, 1.27550515412245e-09,
    2.75032212941667e-09, 3.79663088493923e-08, 1.42368280746262e-08,
    1.51146811601353e-08, 1.75314892144034e-09, 2.07956027448449e-08,
    1.38623943876156e-07, 1.92893849444567e-08, 5.66419694274739e-08,
    5.8089561312222e-09, 1.95827364947702e-09, 6.7071674411728e-10,
    4.23667746162198e-09, 4.62966220873406e-08, 1.21403390886489e-07,
    1.26979107479853e-08, 5.59978765605208e-07, 3.14788992090851e-09,
    5.0058794053616e-07, 5.22186410794211e-09, 9.21607337940845e-10,
    2.51322812227745e-09, 3.04984607426863e-07, 3.20992561385791e-09,
    8.92180336424503e-10, 6.12766236972513e-08, 1.20231538847898e-08,
    1.34589665048046e-07, 8.84238627642763e-10, 2.63370671763944e-11,
    1.11903749128791e-09, 1.16731679208085e-08, 4.99654438989995e-08,
    2.90162442064053e-08, 2.55621731534268e-09, 1.58298464637584e-10,
    5.07475932446428e-08, 2.54927518867625e-09, 2.24427326793633e-10,
    4.49723284363684e-09, 2.43010060636845e-06, 1.90760030501003e-08,
    6.35902610582491e-08, 5.48833215255332e-10, 4.06612010446768e-10,
    5.32889353797193e-10, 1.23745070305762e-06, 8.89608483306497e-07,
    3.75876719292064e-09, 4.44758324449273e-07, 1.35536579831994e-07,
    5.42265922046125e-11, 4.8233448207134e-11, 3.4286615533894e-07,
    2.0214285544428e-10, 8.57988303618593e-10, 1.35631258148319e-09,
    7.97944858545598e-10, 4.2673026648725e-09, 9.28491399244895e-08,
    1.03420112425729e-09, 2.4972909387896e-08, 8.12118760999133e-07,
    1.31225365800221e-08, 1.77287287047586e-09, 6.53958727055997e-09,
    3.05841917976996e-10, 9.20687775127977e-09, 4.32323785012335e-07,
    8.40653865200987e-10, 1.23500809608508e-10, 6.59008808575339e-08,
    1.13962199159936e-09, 4.68300414991578e-10, 3.54758342726504e-11,
    6.55880483863129e-10, 1.17833628272869e-08, 5.08802989644665e-07,
    7.22191649442396e-07, 2.7028184600344e-10, 2.2810918951755e-10,
    8.10987753872438e-10, 1.50406384816011e-09, 5.46176491471454e-06,
    2.32716789835402e-08, 2.10873259303399e-10, 1.81735402994258e-09,
    9.71369590422109e-09, 2.01941765282435e-08, 1.8961914804496e-07,
    9.4461402995167e-09, 1.69816623519093e-07, 9.16774899583353e-08,
    8.54588845128718e-10, 4.79160495478785e-08, 2.31994460360924e-11
    )), row.names = c(NA, -100L), class = c("tbl_df", "tbl",
"data.frame"))
actors= c("Slovakia", "Germany", "Portugal", "Austria", "Latvia", "Cyprus",
"Greece", "Italy", "Slovenia", "Ireland", "Malta", "Luxembourg",
"France", "Netherlands", "Spain", "Belgium", "Finland", "Lithuania",
"Estonia")
g <- graph_from_data_frame(relations, directed=TRUE, vertices=actors)

by using package igraph. Using function closeness I obtain:

closeness(g)
   Slovakia     Germany    Portugal     Austria      Latvia      Cyprus      Greece       Italy    Slovenia     Ireland
    4002492     7111002     6478738     6502665     2017834     1029940     6615891     7164685     5533119     6240785
      Malta  Luxembourg      France Netherlands       Spain     Belgium     Finland   Lithuania     Estonia
    5071100     7243749     6342911     7121291     7144000     7090895     6415382     3086085     7411727

I would like to obtain a normalized closeness score bounded between 0 and 1. It is 0 if a node is an isolate, and 1 if a node is directly connected all others. What can I do

Body:
Have you tried normalizing it yourself out of igraph? You might use caret package:

library(caret)
c1 <-closeness(g)
df <- tibble(actors = actors,
             close = c1)
df_normalized <- df %>%
  preProcess(., method=c("range")) %>%
  predict(., df)

df_normalized


来源: stackexchange

问:
from tensorflow.examples.tutorials.mnist not working in Google Colab
I am a beginner and trying to practice tensor flow using google colab. When I try to import in-build dataset available(mnist) in tensor flow ,I am getting below error.

Many users had this same problem in juypter notebook. I am using Google Colab to make use of free resource

Code Snippet:

```<code>import tensorflow as tf
 from tensorflow.examples.tutorials.mnist import input_data
 mnist = input_data.read_data_sets("MNIST_data", one_hot=True)
</code>```

Error:

```<code>     ModuleNotFoundError                       Traceback (most recent
  call last)   <ipython-input-4-4e25ee396bc7> in <module>()    ----> 1
  from tensorflow.examples.tutorials.mnist import input_data
        2 mnist = input_data.read_data_sets("MNIST_data", one_hot=True)

     ModuleNotFoundError: No module named
  'tensorflow.examples.tutorials'
</code>```

Someone please guide me to resolve this error.

Thank you

答:
At the top write !pip install mnist. Use import mnist.

Then simply store the images and labels:

```<code>train_images = mnist.train_images()
train_labels = mnist.train_labels()
test_images = mnist.test_images()
test_labels = mnist.test_labels()
</code>```

That's it!!!

ContentLicense: CC BY-SA 4.0

Body:
I am a beginner and trying to practice tensor flow using google colab. When I try to import in-build dataset available(mnist) in tensor flow ,I am getting below error.

Many users had this same problem in juypter notebook. I am using Google Colab to make use of free resource

Code Snippet:

import tensorflow as tf
 from tensorflow.examples.tutorials.mnist import input_data
 mnist = input_data.read_data_sets("MNIST_data", one_hot=True)

Error:

     ModuleNotFoundError                       Traceback (most recent
  call last)   <ipython-input-4-4e25ee396bc7> in <module>()    ----> 1
  from tensorflow.examples.tutorials.mnist import input_data
        2 mnist = input_data.read_data_sets("MNIST_data", one_hot=True)

     ModuleNotFoundError: No module named
  'tensorflow.examples.tutorials'

Someone please guide me to resolve this error.

Thank you

Body:
At the top write !pip install mnist. Use import mnist.

Then simply store the images and labels:

train_images = mnist.train_images()
train_labels = mnist.train_labels()
test_images = mnist.test_images()
test_labels = mnist.test_labels()

That's it!!!


问:
How can I submit unsubmitted Moodle attempt via SQL
Hello I ma trying to submit unsubmitted quiz attempts so I can grade them. So far I have set the timefinish column in mdl_quiz_attempts which changes the attempt status to "Not yet graded", then setting fraction to 0 from NULL and state to "gradewrong" from "complete" in mdl_question_attempt_steps to simulate submission but this seems to break the site. What am I missing?</p>

答:
You're going to have to trace through the code for the process_finish() function in mod/quiz/attemptlib.php ( https://github.com/moodle/moodle/blob/master/mod/quiz/attemptlib.php#L2171 ) and figure out how that all works.

This is a complex process and will require a lot of DB queries / updates in order to achieve it manually.

I would strongly recommend that you write a PHP script to do this, instead of trying to handle it manually (that way you can create an instance of 'quiz_attempt' for each user's attempt, then call $attempt->process_finish() on each, in order to close the attempt properly).


问:
Write a program that takes a character as input (string length 1) the output is the next character in the alphabet. If input is 'Z', output is 'A'
Write a program that takes a character as input (a string of length 1), which you should assume is an upper-case character; the output should be the next character in the alphabet.

If the input is 'Z', your output should be 'A'.

Here's what i've done so far but I’m not getting A when I input Z. I’m getting [.

Please help, what am I doing wrong?

```<code>input = (input()).upper()
for character in input:
   number = ord(character) + 1
   number1 = chr(number)
   if ord('z'):
       new_number = ord(character) - 25
        number2 = chr(new_number)

print(number1)
</code>```

答:
I have figured it out!! Thanks to everyone for reaching out with an alternative method! I'm ever grateful.</p>
```<code>input = (input()).upper()
encrypted = ""
for character in input:
    if character == "":
        encrypted += ""
elif ord(character) + 1 > ord("Z"):
    encrypted += chr(ord(character) + 1 - 26)
else:
    encrypted += chr(ord(character) + 1)

print(encrypted)
</code>```

Body:
Write a program that takes a character as input (a string of length 1), which you should assume is an upper-case character; the output should be the next character in the alphabet.

If the input is 'Z', your output should be 'A'.

Here's what i've done so far but I’m not getting A when I input Z. I’m getting [.

Please help, what am I doing wrong?

input = (input()).upper()
for character in input:
   number = ord(character) + 1
   number1 = chr(number)
   if ord('z'):
       new_number = ord(character) - 25
        number2 = chr(new_number)

print(number1)

Body:
I have figured it out!! Thanks to everyone for reaching out with an alternative method! I'm ever grateful.

input = (input()).upper()
encrypted = ""
for character in input:
    if character == "":
        encrypted += ""
elif ord(character) + 1 > ord("Z"):
    encrypted += chr(ord(character) + 1 - 26)
else:
    encrypted += chr(ord(character) + 1)

print(encrypted)


问:
Activity is closed when AsyncTask is using database
My Activity opens a database in onResume() and close it in onPause(). When Activity starts, many AsyncTasks which use that database execute. When I pressed Back button, database was closed and errors appear because AsyncTask is using it. What is solution for this problem?</p>

答: Don't close the database. Have your db helper class be a singleton and access it from your activities as needed. When you process dies, the database will be properly closed. Do make sure you are closing your cursors though.</p>

ContentLicense: CC BY-SA 3.0


问:
ConstraintValidator always has null value during test
after fixing a bug in an older Java Spring MVC 4.1 application, I wanted to add a unit test, but the method the current code base is using for testing won't actually execute validation.

So I wanted to add MVCMock, but when it executes the validation methods, the values passed to isValid is always null.

Relevant files below (I've tried to strip out as much noise as possible):

// Unit Test
@RunWith(SpringJUnit4ClassRunner.class)
@WebAppConfiguration
@EnableWebMvc
@ContextConfiguration(locations = {"/applicationContext-test.xml"})
public class ExampleControllerTest extends AbstractControllerTestBase {
    @Autowired
    private WebApplicationContext context;

    private MockMvc mockMvc;

    @Before
    public void setup() {
        this.mockMvc = webAppContextSetup(this.context).build();
    }

    @Test
    public void fileUploadZipArchive() throws Exception {
        // Upload a zip file
        File mockFile = new File("src/test/resources/fixtures/ex.zip");

        MockHttpServletRequestBuilder multipart = MockMvcRequestBuilders
                .fileUpload("/files/ex/upload/Tex")
                .file("ex.zip",  FileUtils.readFileToByteArray(mockFile));

        MvcResult result = mockMvc.perform(multipart)
                .andReturn();
    }
```
<pre class="lang-java prettyprint-override"><code>// Bean
public class FileUploadBean {

    @Valid
    @MultipartMimeTypeMatch
    private MultipartFile file = null;

    // ...

}
</code>```

// Validator
public class MultipartMimeTypeMatchValidator implements ConstraintValidator<MultipartMimeTypeMatch, Object> {

    // ...

    public boolean isValid(Object value, final ConstraintValidatorContext context) {
        // value and context is always null
    }
}
```
<pre class="lang-java prettyprint-override"><code>// Controller
@RequestMapping(value = "/files/{ex1}/upload/{ex2}", method = RequestMethod.POST)
    public Object uploadFile(HttpServletRequest request, @PathVariable String ex1,
            @PathVariable String ex2, @Valid FileUploadBean fileUploadBean, BindingResult result) throws IllegalStateException, IOException {
         // ...
     }
}
</code>```

What could be going wrong?

NOTE: Spring 4.1

答:
The javadoc of the file method states that the name should be the name of the file. I agree that that is a bit misleading. Instead it should be the name of the request parameter to use, which should be (generally speaking) the same as the property in your model object.

.file("ex.zip",  FileUtils.readFileToByteArray(mockFile));
```
<p>With this a request parameter named <code>ex.zip</code> will be part of the request, however you have one that is named <code>file</code>.</p>
<pre class="lang-java prettyprint-override"><code>.file("file",  FileUtils.readFileToByteArray(mockFile));
</code>```

Using the above line should fix it and properly bind to your object in turn properly invoking your validator.

On a side node, your validator should properly handle the null case as well or add a @NotNull on the field as well. The @Valid on the field doesn't do anything so you can remove that.

Body:
after fixing a bug in an older Java Spring MVC 4.1 application, I wanted to add a unit test, but the method the current code base is using for testing won't actually execute validation.

So I wanted to add MVCMock, but when it executes the validation methods, the values passed to isValid is always null.

Relevant files below (I've tried to strip out as much noise as possible):

// Unit Test
@RunWith(SpringJUnit4ClassRunner.class)
@WebAppConfiguration
@EnableWebMvc
@ContextConfiguration(locations = {"/applicationContext-test.xml"})
public class ExampleControllerTest extends AbstractControllerTestBase {
    @Autowired
    private WebApplicationContext context;

    private MockMvc mockMvc;

    @Before
    public void setup() {
        this.mockMvc = webAppContextSetup(this.context).build();
    }

    @Test
    public void fileUploadZipArchive() throws Exception {
        // Upload a zip file
        File mockFile = new File("src/test/resources/fixtures/ex.zip");

        MockHttpServletRequestBuilder multipart = MockMvcRequestBuilders
                .fileUpload("/files/ex/upload/Tex")
                .file("ex.zip",  FileUtils.readFileToByteArray(mockFile));

        MvcResult result = mockMvc.perform(multipart)
                .andReturn();
    }

// Bean
public class FileUploadBean {

    @Valid
    @MultipartMimeTypeMatch
    private MultipartFile file = null;

    // ...

}

// Validator
public class MultipartMimeTypeMatchValidator implements ConstraintValidator<MultipartMimeTypeMatch, Object> {

    // ...

    public boolean isValid(Object value, final ConstraintValidatorContext context) {
        // value and context is always null
    }
}

// Controller
@RequestMapping(value = "/files/{ex1}/upload/{ex2}", method = RequestMethod.POST)
    public Object uploadFile(HttpServletRequest request, @PathVariable String ex1,
            @PathVariable String ex2, @Valid FileUploadBean fileUploadBean, BindingResult result) throws IllegalStateException, IOException {
         // ...
     }
}

What could be going wrong?

NOTE: Spring 4.1

Body:
The javadoc of the file method states that the name should be the name of the file. I agree that that is a bit misleading. Instead it should be the name of the request parameter to use, which should be (generally speaking) the same as the property in your model object.

.file("ex.zip",  FileUtils.readFileToByteArray(mockFile));

With this a request parameter named ex.zip will be part of the request, however you have one that is named file.

.file("file",  FileUtils.readFileToByteArray(mockFile));

Using the above line should fix it and properly bind to your object in turn properly invoking your validator.

On a side node, your validator should properly handle the null case as well or add a @NotNull on the field as well. The @Valid on the field doesn't do anything so you can remove that.


问:
Unable to find method 'org.gradle.api.artifacts.result.ComponentSelectionReason.getDescription()Ljava/lang/String;'
This Is the error that it shows after compiling my app imported :
**Unable to find method 'org.gradle.api.artifacts.result.ComponentSelectionReason.getDescription()Ljava/lang/String;'.
Possible causes for this unexpected error include:
Gradle's dependency cache may be corrupt (this sometimes occurs after a network connection timeout.)
Re-download dependencies and sync project (requires network)

The state of a Gradle build process (daemon) may be corrupt. Stopping all Gradle daemons may solve this problem.
Stop Gradle build processes (requires restart)

Your project may be using a third-party plugin which is not compatible with the other plugins in the project or the version of Gradle requested by the project.

In the case of corrupt Gradle processes, you can also try closing the IDE and then killing all Java processes.**

build.gradle

```<code>    var = '4.0.1'
}

// Top-level build file where you can add configuration options common to all sub-projects/modules.

buildscript {

    ext.versions = [
            'compileSdk'      : 30,
            'targetSdk'       : 30,
            'fragment'     : '2.3.5',
            'core'     : '1.6.0',
            'butterknife'     : '10.2.3',
            'constraint'      : '1.1.3',
            'dagger'          : '2.37',
            'espresso'        : '3.0.2',
            'glide'           : '4.12.0',
            'gson'            : '2.8.7',
            'junit'           : '4.13',
            'leakcanary'      : '1.6.3',
            'lifecycle'       : '1.1.1',
            'mockito'         : '1.10.19',
            'powerMockito'    : '1.6.2',
            'hamcrest'        : '1.3',
            'okhttp'          : '5.0.0-alpha.2',
            'retrofit'        : '2.9.0',
            'room'            : '1.1.1',
            'runner'          : '1.0.2',
            'rxandroid'       : '3.0.0',
            'rxjava'          : '3.0.13',
            'supportlibrary'  : '28.0.0',
            'timber'          : '4.7.1',
            'firebase'        : '22.0.0',
            'youtube'        : '2.1.0',
            'exoplayer'        : '2.11.7',
            'stringcare_version'        : '4.0.1',
    ]

    repositories {
        google()
        mavenCentral()
        gradlePluginPortal()
        jcenter()
        maven {
            url 'https://maven.google.com'
            }
        maven {
            url 'https://android-sdk.is.com/'
        }

        maven { url 'https://artifacts.applovin.com/android' }

    }
    dependencies {
        classpath 'com.android.tools.build:gradle:7.0.2'
        classpath 'com.google.gms:google-services:4.3.10'
        classpath "com.stringcare:plugin:${versions.stringcare_version}"
        classpath "com.applovin.quality:AppLovinQualityServiceGradlePlugin:+"

    }
}

allprojects {
    repositories {
        google()
        mavenCentral()
        jcenter()
        maven { url "https://jitpack.io" }
        maven { url 'https://maven.fabric.io/public'}
        maven { url "https://oss.sonatype.org/content/repositories/snapshots/" }
        maven {
            url "https://artifactory.appodeal.com/appodeal"
        }
        maven {
            url 'https://android-sdk.is.com/'
        }
        maven {
            url "https://dl.appnext.com/"
        }

        maven {
            url  "https://cardinalcommerceprod.jfrog.io/artifactory/android"
            credentials {
                // Be sure to add these non-sensitive credentials in order to retrieve dependencies from
                // the private repository.
                username 'paypal_sgerritz'
                password 'AKCp8jQ8tAahqpT5JjZ4FRP2mW7GMoFZ674kGqHmupTesKeAY2G8NcmPKLuTxTGkKjDLRzDUQ'
            }
        }
        mavenLocal()

    }
}

ext.versions2 = [
        'api'            : 'https://api.envato.com/v3/',
        'api2'            : 'https://api.yobdev.live/easyplex/api/'
]

task clean(type: Delete) {
    delete rootProject.buildDir
}
</code>```

app\build.gradle

```<code>    var = '4.0.1'
}

// Top-level build file where you can add configuration options common to all sub-projects/modules.

buildscript {

    ext.versions = [
            'compileSdk'      : 30,
            'targetSdk'       : 30,
            'fragment'     : '2.3.5',
            'core'     : '1.6.0',
            'butterknife'     : '10.2.3',
            'constraint'      : '1.1.3',
            'dagger'          : '2.37',
            'espresso'        : '3.0.2',
            'glide'           : '4.12.0',
            'gson'            : '2.8.7',
            'junit'           : '4.13',
            'leakcanary'      : '1.6.3',
            'lifecycle'       : '1.1.1',
            'mockito'         : '1.10.19',
            'powerMockito'    : '1.6.2',
            'hamcrest'        : '1.3',
            'okhttp'          : '5.0.0-alpha.2',
            'retrofit'        : '2.9.0',
            'room'            : '1.1.1',
            'runner'          : '1.0.2',
            'rxandroid'       : '3.0.0',
            'rxjava'          : '3.0.13',
            'supportlibrary'  : '28.0.0',
            'timber'          : '4.7.1',
            'firebase'        : '22.0.0',
            'youtube'        : '2.1.0',
            'exoplayer'        : '2.11.7',
            'stringcare_version'        : '4.0.1',
    ]

    repositories {
        google()
        mavenCentral()
        gradlePluginPortal()
        jcenter()
        maven {
            url 'https://maven.google.com'
            }
        maven {
            url 'https://android-sdk.is.com/'
        }

        maven { url 'https://artifacts.applovin.com/android' }

    }
    dependencies {
        classpath 'com.android.tools.build:gradle:7.0.2'
        classpath 'com.google.gms:google-services:4.3.10'
        classpath "com.stringcare:plugin:${versions.stringcare_version}"
        classpath "com.applovin.quality:AppLovinQualityServiceGradlePlugin:+"

    }
}

allprojects {
    repositories {
        google()
        mavenCentral()
        jcenter()
        maven { url "https://jitpack.io" }
        maven { url 'https://maven.fabric.io/public'}
        maven { url "https://oss.sonatype.org/content/repositories/snapshots/" }
        maven {
            url "https://artifactory.appodeal.com/appodeal"
        }
        maven {
            url 'https://android-sdk.is.com/'
        }
        maven {
            url "https://dl.appnext.com/"
        }

        maven {
            url  "https://cardinalcommerceprod.jfrog.io/artifactory/android"
            credentials {
                // Be sure to add these non-sensitive credentials in order to retrieve dependencies from
                // the private repository.
                username 'paypal_sgerritz'
                password 'AKCp8jQ8tAahqpT5JjZ4FRP2mW7GMoFZ674kGqHmupTesKeAY2G8NcmPKLuTxTGkKjDLRzDUQ'
            }
        }
        mavenLocal()

    }
}

ext.versions2 = [
        'api'            : 'https://api.envato.com/v3/',
        'api2'            : 'https://api.yobdev.live/easyplex/api/'
]

task clean(type: Delete) {
    delete rootProject.buildDir
}
</code>```

gradle-wrapper.properties

```<code>distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists
zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists
distributionUrl=https\://services.gradle.org/distributions/gradle-7.0.2-all.zip
</code>```

gradle.properties

```<code># IDE (e.g. Android Studio) users:
# Gradle settings configured through the IDE *will override*
# any settings specified in this file.
# For more details on how to configure your build environment visit
# http://www.gradle.org/docs/current/userguide/build_environment.html
# Specifies the JVM arguments used for the daemon process.
# The setting is particularly useful for tweaking memory settings.
android.useAndroidX=true
android.enableJetifier=true
org.gradle.jvmargs=-Xmx4096m
android.nonTransitiveRClass=true
org.gradle.daemon=true
org.gradle.parallel=true

# When configured, Gradle will run in incubating parallel mode.
# This option should only be used with decoupled projects. More details, visit
# http://www.gradle.org/docs/current/userguide/multi_project_builds.html#sec:decoupled_projects
# org.gradle.parallel=true
</code>```

答: I used the latest Android Studio version and the issue was solved.</p>

Body:
This Is the error that it shows after compiling my app imported :
**Unable to find method 'org.gradle.api.artifacts.result.ComponentSelectionReason.getDescription()Ljava/lang/String;'.
Possible causes for this unexpected error include:
Gradle's dependency cache may be corrupt (this sometimes occurs after a network connection timeout.)
Re-download dependencies and sync project (requires network)

The state of a Gradle build process (daemon) may be corrupt. Stopping all Gradle daemons may solve this problem.
Stop Gradle build processes (requires restart)

Your project may be using a third-party plugin which is not compatible with the other plugins in the project or the version of Gradle requested by the project.

In the case of corrupt Gradle processes, you can also try closing the IDE and then killing all Java processes.**

build.gradle

    var = '4.0.1'
}

// Top-level build file where you can add configuration options common to all sub-projects/modules.

buildscript {

    ext.versions = [
            'compileSdk'      : 30,
            'targetSdk'       : 30,
            'fragment'     : '2.3.5',
            'core'     : '1.6.0',
            'butterknife'     : '10.2.3',
            'constraint'      : '1.1.3',
            'dagger'          : '2.37',
            'espresso'        : '3.0.2',
            'glide'           : '4.12.0',
            'gson'            : '2.8.7',
            'junit'           : '4.13',
            'leakcanary'      : '1.6.3',
            'lifecycle'       : '1.1.1',
            'mockito'         : '1.10.19',
            'powerMockito'    : '1.6.2',
            'hamcrest'        : '1.3',
            'okhttp'          : '5.0.0-alpha.2',
            'retrofit'        : '2.9.0',
            'room'            : '1.1.1',
            'runner'          : '1.0.2',
            'rxandroid'       : '3.0.0',
            'rxjava'          : '3.0.13',
            'supportlibrary'  : '28.0.0',
            'timber'          : '4.7.1',
            'firebase'        : '22.0.0',
            'youtube'        : '2.1.0',
            'exoplayer'        : '2.11.7',
            'stringcare_version'        : '4.0.1',
    ]

    repositories {
        google()
        mavenCentral()
        gradlePluginPortal()
        jcenter()
        maven {
            url 'https://maven.google.com'
            }
        maven {
            url 'https://android-sdk.is.com/'
        }

        maven { url 'https://artifacts.applovin.com/android' }

    }
    dependencies {
        classpath 'com.android.tools.build:gradle:7.0.2'
        classpath 'com.google.gms:google-services:4.3.10'
        classpath "com.stringcare:plugin:${versions.stringcare_version}"
        classpath "com.applovin.quality:AppLovinQualityServiceGradlePlugin:+"

    }
}

allprojects {
    repositories {
        google()
        mavenCentral()
        jcenter()
        maven { url "https://jitpack.io" }
        maven { url 'https://maven.fabric.io/public'}
        maven { url "https://oss.sonatype.org/content/repositories/snapshots/" }
        maven {
            url "https://artifactory.appodeal.com/appodeal"
        }
        maven {
            url 'https://android-sdk.is.com/'
        }
        maven {
            url "https://dl.appnext.com/"
        }

        maven {
            url  "https://cardinalcommerceprod.jfrog.io/artifactory/android"
            credentials {
                // Be sure to add these non-sensitive credentials in order to retrieve dependencies from
                // the private repository.
                username 'paypal_sgerritz'
                password 'AKCp8jQ8tAahqpT5JjZ4FRP2mW7GMoFZ674kGqHmupTesKeAY2G8NcmPKLuTxTGkKjDLRzDUQ'
            }
        }
        mavenLocal()

    }
}

ext.versions2 = [
        'api'            : 'https://api.envato.com/v3/',
        'api2'            : 'https://api.yobdev.live/easyplex/api/'
]

task clean(type: Delete) {
    delete rootProject.buildDir
}

app\build.gradle

    var = '4.0.1'
}

// Top-level build file where you can add configuration options common to all sub-projects/modules.

buildscript {

    ext.versions = [
            'compileSdk'      : 30,
            'targetSdk'       : 30,
            'fragment'     : '2.3.5',
            'core'     : '1.6.0',
            'butterknife'     : '10.2.3',
            'constraint'      : '1.1.3',
            'dagger'          : '2.37',
            'espresso'        : '3.0.2',
            'glide'           : '4.12.0',
            'gson'            : '2.8.7',
            'junit'           : '4.13',
            'leakcanary'      : '1.6.3',
            'lifecycle'       : '1.1.1',
            'mockito'         : '1.10.19',
            'powerMockito'    : '1.6.2',
            'hamcrest'        : '1.3',
            'okhttp'          : '5.0.0-alpha.2',
            'retrofit'        : '2.9.0',
            'room'            : '1.1.1',
            'runner'          : '1.0.2',
            'rxandroid'       : '3.0.0',
            'rxjava'          : '3.0.13',
            'supportlibrary'  : '28.0.0',
            'timber'          : '4.7.1',
            'firebase'        : '22.0.0',
            'youtube'        : '2.1.0',
            'exoplayer'        : '2.11.7',
            'stringcare_version'        : '4.0.1',
    ]

    repositories {
        google()
        mavenCentral()
        gradlePluginPortal()
        jcenter()
        maven {
            url 'https://maven.google.com'
            }
        maven {
            url 'https://android-sdk.is.com/'
        }

        maven { url 'https://artifacts.applovin.com/android' }

    }
    dependencies {
        classpath 'com.android.tools.build:gradle:7.0.2'
        classpath 'com.google.gms:google-services:4.3.10'
        classpath "com.stringcare:plugin:${versions.stringcare_version}"
        classpath "com.applovin.quality:AppLovinQualityServiceGradlePlugin:+"

    }
}

allprojects {
    repositories {
        google()
        mavenCentral()
        jcenter()
        maven { url "https://jitpack.io" }
        maven { url 'https://maven.fabric.io/public'}
        maven { url "https://oss.sonatype.org/content/repositories/snapshots/" }
        maven {
            url "https://artifactory.appodeal.com/appodeal"
        }
        maven {
            url 'https://android-sdk.is.com/'
        }
        maven {
            url "https://dl.appnext.com/"
        }

        maven {
            url  "https://cardinalcommerceprod.jfrog.io/artifactory/android"
            credentials {
                // Be sure to add these non-sensitive credentials in order to retrieve dependencies from
                // the private repository.
                username 'paypal_sgerritz'
                password 'AKCp8jQ8tAahqpT5JjZ4FRP2mW7GMoFZ674kGqHmupTesKeAY2G8NcmPKLuTxTGkKjDLRzDUQ'
            }
        }
        mavenLocal()

    }
}

ext.versions2 = [
        'api'            : 'https://api.envato.com/v3/',
        'api2'            : 'https://api.yobdev.live/easyplex/api/'
]

task clean(type: Delete) {
    delete rootProject.buildDir
}

gradle-wrapper.properties

distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists
zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists
distributionUrl=https\://services.gradle.org/distributions/gradle-7.0.2-all.zip

gradle.properties

# IDE (e.g. Android Studio) users:
# Gradle settings configured through the IDE *will override*
# any settings specified in this file.
# For more details on how to configure your build environment visit
# http://www.gradle.org/docs/current/userguide/build_environment.html
# Specifies the JVM arguments used for the daemon process.
# The setting is particularly useful for tweaking memory settings.
android.useAndroidX=true
android.enableJetifier=true
org.gradle.jvmargs=-Xmx4096m
android.nonTransitiveRClass=true
org.gradle.daemon=true
org.gradle.parallel=true

# When configured, Gradle will run in incubating parallel mode.
# This option should only be used with decoupled projects. More details, visit
# http://www.gradle.org/docs/current/userguide/multi_project_builds.html#sec:decoupled_projects
# org.gradle.parallel=true


问:
Express: serving static files in express using app.use() not working on * route
I am trying to serve static html and css files using express on any route. The files are present in public folder in the same directory the express file is present. The express code is given below:</p>
```<code>const express = require('express')
const path = require('path')

const app = express()

// app.use('*', express.static('./public')); // Not Working
// app.use('/', express.static('./public')); // Working but only limited to home route
app.use(express.static('./public')); // Working but only limited to home route

app.listen(5000, () => {
  console.log('server is listening on port 5000....')
})
</code>```

答:
if the folder public in the same root with your node app use:

```<code>app.use(express.static('public'))
</code>```

To create a virtual path prefix (where the path does not actually exist in the file system) for files that are served by the express.static function, specify a mount path for the static directory, as shown below:

app.use('/static', express.static('public'))

Now, you can load the files that are in the public directory from the /static path prefix.

http://localhost:3000/static/images/kitten.jpg
http://localhost:3000/static/css/style.css

However, the path that you provide to the express.static function is relative to the directory from where you launch your node process. If you run the express app from another directory, it’s safer to use the absolute path of the directory that you want to serve:

const path = require('path')
app.use('/static', express.static(path.join(__dirname, 'public')))

Body:
I am trying to serve static html and css files using express on any route. The files are present in public folder in the same directory the express file is present. The express code is given below:

const express = require('express')
const path = require('path')

const app = express()

// app.use('*', express.static('./public')); // Not Working
// app.use('/', express.static('./public')); // Working but only limited to home route
app.use(express.static('./public')); // Working but only limited to home route

app.listen(5000, () => {
  console.log('server is listening on port 5000....')
})

Body:
if the folder public in the same root with your node app use:

app.use(express.static('public'))

To create a virtual path prefix (where the path does not actually exist in the file system) for files that are served by the express.static function, specify a mount path for the static directory, as shown below:

app.use('/static', express.static('public'))

Now, you can load the files that are in the public directory from the /static path prefix.

http://localhost:3000/static/images/kitten.jpg
http://localhost:3000/static/css/style.css

However, the path that you provide to the express.static function is relative to the directory from where you launch your node process. If you run the express app from another directory, it’s safer to use the absolute path of the directory that you want to serve:

const path = require('path')
app.use('/static', express.static(path.join(__dirname, 'public')))


问:
How to combine two tables into one using my sql statement
i'm new in Database, i want to get a result from both sql table.
Here is the example

Table 1

Item Code
Price

A001
5 Dollar

A002
6 Dollar

Table 2 - Item Code Information

Item Code
Item Description

A001
Fish

A002
Chicken

And my question i want to get result with table 1 combine with 2 with item code, item description and price

Item Code
Item Description
Price

A001
Fish
5 Dollar

A002
Chicken
6 Dollar

Does anyone know how to do the SQL statement? Please help Thank you

答:
Join both tables with item codes and select all the desired fields from both tables

```<code>SELECT table2.itemcode,table2.itemdescription,table1.price FROM table1
INNER JOIN table2
ON table1.itemcode=table2.itemcode
</code>```

Body:
Join both tables with item codes and select all the desired fields from both tables

SELECT table2.itemcode,table2.itemdescription,table1.price FROM table1
INNER JOIN table2
ON table1.itemcode=table2.itemcode


问:
Objectify - can we set a startAt(cursor) for QueryKeys? Or how to iterate over many Keys query?
I'm trying to iterate over 1000 keys of an entity at a time using this code but unlike Query, QueryKeys does not have a startAt() method for me to set it's cursor:

```<code>QueryKeys<Car> queryKeys = ofy().load().type(Car.class)
    .limit(1000)
     .keys();

// queryKeys has no startAt()
queryKeys = queryKeys.startAt(cursor)
</code>```

Is there a way to loop through keys with QueryKeys just like Query?

The reason I want to loop through keys is that I need to delete those entities from the Datastore. I might be deleting 100k - 1 million entities of a single entity type and wanted to do it in chunks because I am afraid that loading that many keys may slow things down too much or maybe error out somehow.

答:
If you delete a page synchronously, there's no need for pagination:</p>
```<code> public void deleteAllEntities() {
    boolean continueDeletionLoop = true;

    while (continueDeletionLoop) {
        QueryKeys<Car> queryKeys = objectify.get().load().type(Car.class)
            .limit(1000)
            .keys();

        if (queryKeys.list().isEmpty()) {
            continueDeletionLoop = false;
        } else {
            objectify.get().delete().keys(queryKeys).now();
        }
    }

}
</code>```

Body:
I'm trying to iterate over 1000 keys of an entity at a time using this code but unlike Query, QueryKeys does not have a startAt() method for me to set it's cursor:

QueryKeys<Car> queryKeys = ofy().load().type(Car.class)
    .limit(1000)
     .keys();

// queryKeys has no startAt()
queryKeys = queryKeys.startAt(cursor)

Is there a way to loop through keys with QueryKeys just like Query?

The reason I want to loop through keys is that I need to delete those entities from the Datastore. I might be deleting 100k - 1 million entities of a single entity type and wanted to do it in chunks because I am afraid that loading that many keys may slow things down too much or maybe error out somehow.

Body:
If you delete a page synchronously, there's no need for pagination:

 public void deleteAllEntities() {
    boolean continueDeletionLoop = true;

    while (continueDeletionLoop) {
        QueryKeys<Car> queryKeys = objectify.get().load().type(Car.class)
            .limit(1000)
            .keys();

        if (queryKeys.list().isEmpty()) {
            continueDeletionLoop = false;
        } else {
            objectify.get().delete().keys(queryKeys).now();
        }
    }

}


问:
How do I share user controls between web applications in ASP.NET?
This question is a follow up to my question about sharing resources between web applications, because I have not yet found a good solution.

I have a web application with user controls and resources that are shared by three other web applications.

```
Solution
|
+-CommonControlsWebApp
| +- resources
| |  +- images
| |  +- scripts
| |  +- stylesheets
| +- UserControls
|
+-WebApp1
|
+-WebApp2
|
+-WebApp3
```

This is what I know this far:

I can not compile CommonControlsWebApp into a single dll since I am creating user controls. This is only possible with custom server controls, where everything is in the code-behind file. So I need a way to share the ascx files between the four projects.

Copying the files from CommonControlsWebApp into the three other projects does not update their files in the solution explorer. I would have to 'add exting items' all in all three WebApps when a file is added or renamed in CommonControls.

Changing to the Web Site model would remedy this, but I am worried about the compile time for WebApp1-3 if I do this.

'Add as link' does not work for directories.

I could use Subversion to share the files between the projects, but i believe that this would require me to check the files in and out again all the time if I am developing a user control that I have to test through one of the WebApps.

Can it really be true that ASP.NET does not have a good solution for this? How are you guys organizing large web applications?

Edit: Thanks a lot for all the answers. I am going to copy my user controls with a build event for now, and then see if we have time to refactor them into server controls.

答:
You might consider using source control and sharing your controls at that level. We do this for a sizable user control library and it works quite well.

Using SourceGear Vault but you should be able to do this with any source control product.

OwnerDisplayName: Jan Aagaard

ContentLicense: CC BY-SA 2.5

Body:
This question is a follow up to my question about sharing resources between web applications, because I have not yet found a good solution.

I have a web application with user controls and resources that are shared by three other web applications.

Solution
|
+-CommonControlsWebApp
| +- resources
| |  +- images
| |  +- scripts
| |  +- stylesheets
| +- UserControls
|
+-WebApp1
|
+-WebApp2
|
+-WebApp3

This is what I know this far:

I can not compile CommonControlsWebApp into a single dll since I am creating user controls. This is only possible with custom server controls, where everything is in the code-behind file. So I need a way to share the ascx files between the four projects.

Copying the files from CommonControlsWebApp into the three other projects does not update their files in the solution explorer. I would have to 'add exting items' all in all three WebApps when a file is added or renamed in CommonControls.

Changing to the Web Site model would remedy this, but I am worried about the compile time for WebApp1-3 if I do this.

'Add as link' does not work for directories.

I could use Subversion to share the files between the projects, but i believe that this would require me to check the files in and out again all the time if I am developing a user control that I have to test through one of the WebApps.

Can it really be true that ASP.NET does not have a good solution for this? How are you guys organizing large web applications?

Edit: Thanks a lot for all the answers. I am going to copy my user controls with a build event for now, and then see if we have time to refactor them into server controls.

LastEditorDisplayName: Jan Aagaard

OwnerDisplayName: Andrew Robinson


问:
How to cache poetry install for GitHub Actions
I tried to use this actions/cache@v2 to cache poetry venv. There are only two libraries pylint and pytest installed. It seems that installation was cached (cache size ~ 26MB). However, they couldn't be retrieved after cache hit.

The cache installed libraries are not found while run

poetry run pip list

```<code>Package    Version
---------- -------
pip        20.1.1
setuptools 41.2.0
</code>```

https://github.com/northtree/poetry-github-actions/runs/875926237?check_suite_focus=true#step:9:1

The YAML is here.

Could I know how to use actions/cache@v2 to cache poetry installation / virturalenv to avoid reinstalling dependencies.

答:
You don't need to use an external action for installing Poetry, or set up virtual environments. poetry installs modules to ~/.cache/pypoetry, so:

    - name: Load cached venv
      id: cached-poetry-dependencies
      uses: actions/cache@v2
      with:
        path: |
          ~/.cache/pypoetry
          .venv
        key: poetry-${{ runner.os }}-${{ hashFiles('**/poetry.lock') }}

    - name: Install poetry no matter what
      run: |
        curl -sSL https://install.python-poetry.org | python3 -
        echo "$HOME/.local/bin" >> $GITHUB_PATH

    - name: Install requirements
      if: steps.cached-poetry-dependencies.outputs.cache-hit != 'true'
      run: |
        poetry install

```

It should theoretically be possible to cache installation of poetry too, which is installed to ~/.poetry. I couldn't find the way, though.

However, by the time you read this, this PR might have already landed so all you're going to need to cache Poetry deps is actions/setup-python

Body:
I tried to use this actions/cache@v2 to cache poetry venv. There are only two libraries pylint and pytest installed. It seems that installation was cached (cache size ~ 26MB). However, they couldn't be retrieved after cache hit.

The cache installed libraries are not found while run

poetry run pip list

Package    Version
---------- -------
pip        20.1.1
setuptools 41.2.0

https://github.com/northtree/poetry-github-actions/runs/875926237?check_suite_focus=true#step:9:1

The YAML is here.

Could I know how to use actions/cache@v2 to cache poetry installation / virturalenv to avoid reinstalling dependencies.

Body:
You don't need to use an external action for installing Poetry, or set up virtual environments. poetry installs modules to ~/.cache/pypoetry, so:

    - name: Load cached venv
      id: cached-poetry-dependencies
      uses: actions/cache@v2
      with:
        path: |
          ~/.cache/pypoetry
          .venv
        key: poetry-${{ runner.os }}-${{ hashFiles('**/poetry.lock') }}

    - name: Install poetry no matter what
      run: |
        curl -sSL https://install.python-poetry.org | python3 -
        echo "$HOME/.local/bin" >> $GITHUB_PATH

    - name: Install requirements
      if: steps.cached-poetry-dependencies.outputs.cache-hit != 'true'
      run: |
        poetry install

It should theoretically be possible to cache installation of poetry too, which is installed to ~/.poetry. I couldn't find the way, though.

However, by the time you read this, this PR might have already landed so all you're going to need to cache Poetry deps is actions/setup-python


问:
Remove unwanted parts from strings in Dataframe
I am looking for an efficient way to remove unwanted parts from strings in a DataFrame column.

My dataframe:

```<code>     Passengers

1    Sally Muller, President, Mark Smith, Vicepresident, John Doe, Chief of Staff
2    Sally Muller, President, Mark Smith, Vicepresident
3    Sally Muller, President, Mark Smith, Vicepresident, John Doe, Chief of Staff
4    Mark Smith, Vicepresident, John Doe, Chief of Staff, Peter Parker, Special Effects
5    Sally Muller, President, John Doe, Chief of Staff, Peter Parker, Special Effects, Lydia Johnson, Vice Chief of Staff
...
</code>```

desired form of df:

```<code>     Passengers

1    Sally Muller, Mark Smith, John Doe
2    Sally Muller, Mark Smith
3    Sally Muller, Mark Smith, John Doe
4    Mark Smith, John Doe, Peter Parker
5    Sally Muller, John Doe, Peter Parker, Lydia Johnson
...
</code>```

Up to now I did it with endless handmade copy/paste regex list:

```<code>df = df.replace(r'President,','', regex=True)
df = df.replace(r'Vicepresident,','', regex=True)
df = df.replace(r'Chief of Staff,','', regex=True)
df = df.replace(r'Special Effects,','', regex=True)
df = df.replace(r'Vice Chief of Staff,','', regex=True)
...
</code>```

Is there a more comfortable way to do this?

Edit

More accurate example of original df:

```<code>     Passengers

1    Sally Muller, President, EL Mark Smith, John Doe, Chief of Staff,  Peter Gordon, Director of Central Command
2    Sally Muller, President, EL Mark Smith, Vicepresident
3    Sally Muller, President, EL Mark Smith, Vicepresident, John Doe, Chief of Staff, Peter Gordon, Dir CC
4    Mark Smith, Vicepresident, John Doe, Chief of Staff, Peter Parker, Special Effects
5    President Sally Muller, John Doe Chief of Staff, Peter Parker, Special Effects, Lydia Johnson , Vice Chief of Staff
...
</code>```

desired form of df:

```<code>     Passengers

1    Sally Muller, Mark Smith, John Doe, Peter Gordon
2    Sally Muller, Mark Smith
3    Sally Muller, Mark Smith, John Doe, Peter Gordon
4    Mark Smith, John Doe, Peter Parker
5    Sally Muller, John Doe, Peter Parker, Lydia Johnson
...
</code>```

Up to now I did it with endless handmade copy/paste regex list:

```<code>df = df.replace(r'President','', regex=True)
df = df.replace(r'Director of Central Command,','', regex=True)
df = df.replace(r'Dir CC','', regex=True)
df = df.replace(r'Vicepresident','', regex=True)
df = df.replace(r'Chief of Staff','', regex=True)
df = df.replace(r'Special Effects','', regex=True)
df = df.replace(r'Vice Chief of Staff','', regex=True)
...
</code>```

messy output is like:

```<code>     Passengers

1    Sally Muller, , Mark Smith, John Doe, , Peter Gordon,
2    Sally Muller, Mark Smith,
3    Sally Muller, Mark Smith,, John Doe, Peter Gordon
4    Mark Smith, John Doe, Peter Parker
5    Sally Muller,, John Doe, Peter Parker , Lydia Johnson,
...
</code>```

答:
This is one case where apply is actually faster that explode:

```<code>df2 = df['Passengers'].apply(lambda x: ', '.join(x.split(', ')[::2])) #.to_frame() # if dataframe needed
</code>```

output:

```<code>                                          Passengers
0                 Sally Muller, Mark Smith, John Doe
1                           Sally Muller, Mark Smith
2                 Sally Muller, Mark Smith, John Doe
3                 Mark Smith, John Doe, Peter Parker
4  Sally Muller, John Doe, Peter Parker, Lydia Jo...
</code>```

Body:
I am looking for an efficient way to remove unwanted parts from strings in a DataFrame column.

My dataframe:

     Passengers

1    Sally Muller, President, Mark Smith, Vicepresident, John Doe, Chief of Staff
2    Sally Muller, President, Mark Smith, Vicepresident
3    Sally Muller, President, Mark Smith, Vicepresident, John Doe, Chief of Staff
4    Mark Smith, Vicepresident, John Doe, Chief of Staff, Peter Parker, Special Effects
5    Sally Muller, President, John Doe, Chief of Staff, Peter Parker, Special Effects, Lydia Johnson, Vice Chief of Staff
...

desired form of df:

     Passengers

1    Sally Muller, Mark Smith, John Doe
2    Sally Muller, Mark Smith
3    Sally Muller, Mark Smith, John Doe
4    Mark Smith, John Doe, Peter Parker
5    Sally Muller, John Doe, Peter Parker, Lydia Johnson
...

Up to now I did it with endless handmade copy/paste regex list:

df = df.replace(r'President,','', regex=True)
df = df.replace(r'Vicepresident,','', regex=True)
df = df.replace(r'Chief of Staff,','', regex=True)
df = df.replace(r'Special Effects,','', regex=True)
df = df.replace(r'Vice Chief of Staff,','', regex=True)
...

Is there a more comfortable way to do this?

Edit

More accurate example of original df:

     Passengers

1    Sally Muller, President, EL Mark Smith, John Doe, Chief of Staff,  Peter Gordon, Director of Central Command
2    Sally Muller, President, EL Mark Smith, Vicepresident
3    Sally Muller, President, EL Mark Smith, Vicepresident, John Doe, Chief of Staff, Peter Gordon, Dir CC
4    Mark Smith, Vicepresident, John Doe, Chief of Staff, Peter Parker, Special Effects
5    President Sally Muller, John Doe Chief of Staff, Peter Parker, Special Effects, Lydia Johnson , Vice Chief of Staff
...

desired form of df:

     Passengers

1    Sally Muller, Mark Smith, John Doe, Peter Gordon
2    Sally Muller, Mark Smith
3    Sally Muller, Mark Smith, John Doe, Peter Gordon
4    Mark Smith, John Doe, Peter Parker
5    Sally Muller, John Doe, Peter Parker, Lydia Johnson
...

Up to now I did it with endless handmade copy/paste regex list:

df = df.replace(r'President','', regex=True)
df = df.replace(r'Director of Central Command,','', regex=True)
df = df.replace(r'Dir CC','', regex=True)
df = df.replace(r'Vicepresident','', regex=True)
df = df.replace(r'Chief of Staff','', regex=True)
df = df.replace(r'Special Effects','', regex=True)
df = df.replace(r'Vice Chief of Staff','', regex=True)
...

messy output is like:

     Passengers

1    Sally Muller, , Mark Smith, John Doe, , Peter Gordon,
2    Sally Muller, Mark Smith,
3    Sally Muller, Mark Smith,, John Doe, Peter Gordon
4    Mark Smith, John Doe, Peter Parker
5    Sally Muller,, John Doe, Peter Parker , Lydia Johnson,
...

Body:
This is one case where apply is actually faster that explode:

df2 = df['Passengers'].apply(lambda x: ', '.join(x.split(', ')[::2])) #.to_frame() # if dataframe needed

output:

                                          Passengers
0                 Sally Muller, Mark Smith, John Doe
1                           Sally Muller, Mark Smith
2                 Sally Muller, Mark Smith, John Doe
3                 Mark Smith, John Doe, Peter Parker
4  Sally Muller, John Doe, Peter Parker, Lydia Jo...


问:
useEffect not being executed in React
This seems to be a common problem but somehow I simply cannot get it to work : I am trying to read some data from a mongoDB database. If I call the NodeJS server directly in a browser, as in

http://localhost:5000/record/nilan

I get the data as a JSON string:

```<code>
  {
   "pid":{
        "ck":"F19909120:525.522.8788.37",
        "name":"nilan",
        "cID":"0SL8CT4NP9VO"
      }
}

</code>```

But when I am calling this from a React function RecordDetails(), I get nothing. Please see the code below :

    import React, { useEffect, useState } from "react";
    import { Link } from "react-router-dom";
    import { useParams, useNavigate } from "react-router";

    export default function RecordDetails() {
     const params = useParams();
     const [record1, setRecords] = useState([]);
     window.alert('here1');
     // This method fetches the records from the database.
     useEffect(() => {
       async function get1Record() {
         //const id = params.id.toString();
         const response = await fetch(`http://localhost:5000/record/${params.id.toString()}`);

         if (!response.ok) {
           const message = `An error occurred: ${response.statusText}`;
           window.alert(message);
           return;
         }

         const record1 = await response.json();
         const message2 = 'here'
         window.alert(message2);
         window.alert(record1.pid.name);
         window.alert(record1.pid.ck);
         setRecords(record1);

       }

       get1Record();

       return;
     } , [record1.length]);

     window.alert('here2');

     // This following section will display the table with the records of individuals.
     return (

Record Details

         {record1.pid.name}
         {record1.pid.ck}
         {record1.pid.cID}

     );
    }
```

The process does not seem to be entering the useEffect() part of the code .

When this function RecordDetails() is called, we get the alerts in this sequence. "here1", "here2", "here1", "here2"; then the functions terminates with a blank screen.

I do not get any of the alerts from inside the useEffect, not even the error message alert. What am I doing wrong?

答:
The useEffect hook only runs after the DOM has rendered and when the values inside the dependency array have changed; since you don't change the values inside the dependency array anywhere except within the useEffect hook, it never runs because record1.length will never change -- the code is never reached. You may want to use the useMemo hook instead, which runs once and then will only change when its dependency changes. Also, in order to get it to update, you need to trigger the change from outside the hook, not within, otherwise it will not run. Thus, may I suggest something along the following:

```<code>
const userInfo = useMemo(() => {
  const response = //make server call
  return response
}, [dependentValues]);

setRecords({record1: userInfo});

return (
  <div onChange={() => {changeDependentValues()}} />
)

</code>```

Title: useEffect not being executed in React

Body:
This seems to be a common problem but somehow I simply cannot get it to work : I am trying to read some data from a mongoDB database. If I call the NodeJS server directly in a browser, as in

http://localhost:5000/record/nilan

I get the data as a JSON string:

  {
   "pid":{
        "ck":"F19909120:525.522.8788.37",
        "name":"nilan",
        "cID":"0SL8CT4NP9VO"
      }
}

But when I am calling this from a React function RecordDetails(), I get nothing. Please see the code below :

    import React, { useEffect, useState } from "react";
    import { Link } from "react-router-dom";
    import { useParams, useNavigate } from "react-router";

    export default function RecordDetails() {
     const params = useParams();
     const [record1, setRecords] = useState([]);
     window.alert('here1');
     // This method fetches the records from the database.
     useEffect(() => {
       async function get1Record() {
         //const id = params.id.toString();
         const response = await fetch(`http://localhost:5000/record/${params.id.toString()}`);

         if (!response.ok) {
           const message = `An error occurred: ${response.statusText}`;
           window.alert(message);
           return;
         }

         const record1 = await response.json();
         const message2 = 'here'
         window.alert(message2);
         window.alert(record1.pid.name);
         window.alert(record1.pid.ck);
         setRecords(record1);

       }

       get1Record();

       return;
     } , [record1.length]);

     window.alert('here2');

     // This following section will display the table with the records of individuals.
     return (

Record Details

         {record1.pid.name}
         {record1.pid.ck}
         {record1.pid.cID}

     );
    }

The process does not seem to be entering the useEffect() part of the code .

When this function RecordDetails() is called, we get the alerts in this sequence. "here1", "here2", "here1", "here2"; then the functions terminates with a blank screen.

I do not get any of the alerts from inside the useEffect, not even the error message alert. What am I doing wrong?

Body:
The useEffect hook only runs after the DOM has rendered and when the values inside the dependency array have changed; since you don't change the values inside the dependency array anywhere except within the useEffect hook, it never runs because record1.length will never change -- the code is never reached. You may want to use the useMemo hook instead, which runs once and then will only change when its dependency changes. Also, in order to get it to update, you need to trigger the change from outside the hook, not within, otherwise it will not run. Thus, may I suggest something along the following:

const userInfo = useMemo(() => {
  const response = //make server call
  return response
}, [dependentValues]);

setRecords({record1: userInfo});

return (
  <div onChange={() => {changeDependentValues()}} />
)


问:
Testing navigation with react-testing-library
I want to test if a sidebar that I have created for navigation works or not, this is a simple example of what I have made

```<code><ul>
  <li><Link to="/location1">location 1</Link></li>
  <li><Link to="/location2">location 2</Link></li>
</ul>
</code>```

this is my test

```<code>const routerWrapper = ({children}) => <BrowserRouter>{children}</BrowserRouter>

// The first one runs fine
it('navigation to location 1' , () => {
render(<SideBar/> , {wrapper:routerWrapper})
// get the element and click on it
// check if title of page is correct
})

it('navigation to location 2' , () => {
render(<SideBar/> , {wrapper:routerWrapper})
// can't run because location is at /location1
})
</code>```

When I test the navigation with RTL, first test runs fine, but after that the location remains at that directory for next test, how do I clear location after every test? or any suggestions how should I test navigation?

答:
Well I did figure it out, we can use <MemoryRouter> for this purpose.
https://reactrouter.com/docs/en/v6/api#memoryrouter

Just passed the value ['/'] to initialEntries prop from <MemoryRouter> and tests work fine.

also slideshowp2 answer
is very useful if you are interested

Body:
I want to test if a sidebar that I have created for navigation works or not, this is a simple example of what I have made

<Link to="/location1">location 1</Link>

<Link to="/location2">location 2</Link>

this is my test

const routerWrapper = ({children}) => <BrowserRouter>{children}</BrowserRouter>

// The first one runs fine
it('navigation to location 1' , () => {
render(<SideBar/> , {wrapper:routerWrapper})
// get the element and click on it
// check if title of page is correct
})

it('navigation to location 2' , () => {
render(<SideBar/> , {wrapper:routerWrapper})
// can't run because location is at /location1
})

When I test the navigation with RTL, first test runs fine, but after that the location remains at that directory for next test, how do I clear location after every test? or any suggestions how should I test navigation?


问:
Can you implement 'sweep' using apply in R?
I'm brushing up on my R skills and finally feel like I've mastered the strange sweep function e.g.

```<code>df <- data.frame(a = 1:3, b = 2:4)
sweep(df, MARGIN = 2, STATS = c(5, 10), FUN = "*")

##    a  b
## 1  5 20
## 2 10 30
## 3 15 40
</code>```

and more usefully here, on a tutorial I'm working on implementing a spatial interaction model in R.

They say that a sign you understand something is that you can say it in many ways, and I think this applies more in programming than almost anywhere else. Yet, despite the problem that sweep solves seeming apply-esque, I have NO IDEA whether they are to some degree interchangeable.

So, in order to improve my own understanding of R, is there any way to do the above procedure using apply?

答:
As an additional information, since questions about sweep are recurring, quick benchmarking gives (on Intel i7-8700 with Windows)

```<code>x <- matrix(data = 20000*5000, nrow = 20000, ncol = 5000)
system.time(expr = {
  aa <- colMeans(x = x)
  bb <- sweep(x = x, MARGIN = 2, STATS = aa, FUN = "-")
})
#        user      system      elapsed
#        4.69        0.16        4.84
system.time(expr = {
  bbb <- apply(X = x, MARGIN = 1, FUN = function(z) z - mean(x = z))
  bbb <- t(x = bbb)
})
#        user      system      elapsed
#        6.28        0.55        6.85
</code>```

Meaning that sweep is more efficient when applicable.

Body:
I'm brushing up on my R skills and finally feel like I've mastered the strange sweep function e.g.

df <- data.frame(a = 1:3, b = 2:4)
sweep(df, MARGIN = 2, STATS = c(5, 10), FUN = "*")

##    a  b
## 1  5 20
## 2 10 30
## 3 15 40

and more usefully here, on a tutorial I'm working on implementing a spatial interaction model in R.

They say that a sign you understand something is that you can say it in many ways, and I think this applies more in programming than almost anywhere else. Yet, despite the problem that sweep solves seeming apply-esque, I have NO IDEA whether they are to some degree interchangeable.

So, in order to improve my own understanding of R, is there any way to do the above procedure using apply?

Body:
As an additional information, since questions about sweep are recurring, quick benchmarking gives (on Intel i7-8700 with Windows)

x <- matrix(data = 20000*5000, nrow = 20000, ncol = 5000)
system.time(expr = {
  aa <- colMeans(x = x)
  bb <- sweep(x = x, MARGIN = 2, STATS = aa, FUN = "-")
})
#        user      system      elapsed
#        4.69        0.16        4.84
system.time(expr = {
  bbb <- apply(X = x, MARGIN = 1, FUN = function(z) z - mean(x = z))
  bbb <- t(x = bbb)
})
#        user      system      elapsed
#        6.28        0.55        6.85

Meaning that sweep is more efficient when applicable.


问:
django static files weird behaviour
in my settings.py I have:

```<code>import os
SITE_ROOT = os.path.realpath(os.path.dirname(__file__))
# ... #
STATIC_ROOT = os.path.join(SITE_ROOT, 'static')
# ... #
STATIC_URL = '/static/'
</code>```

in my urls.py I have:

```<code>urlpatterns = patterns('',
url(r'^', include('myapp.urls')),
url(r'^admin/', include(admin.site.urls)),
)

if settings.DEBUG:
urlpatterns += patterns('',
    url(r'^static/(?P<path>.*)', 'django.views.static.serve', {
        'document_root': settings.STATIC_ROOT,
    }),
</code>```

)

and in my template:

```<code><img src="{{ STATIC_URL }}images/myimage.png">
</code>```

Which doesn't work. The weird thing is that if I change my settings.py:

```<code>STATIC_URL = 'static/'
</code>```

and my template to:

```<code><img src="/{{ STATIC_URL }}images/myimage.png">
</code>```

does work!! I have been chasing round in circle to fix this, and I have looked at lots of forum posts, but I can't seem to figure out what I'm doing wrong.

答:
if you use staticfiles app you don't need this (assuming you are using Django 1.3):

```<code>if settings.DEBUG:
    urlpatterns += patterns('',
        url(r'^static/(?P<path>.*)', 'django.views.static.serve', {
            'document_root': settings.STATIC_ROOT,
    })
</code>```

Its handled by the app automatically. Try to remove and see what happens.

Title: django static files weird behaviour

Body:
in my settings.py I have:

import os
SITE_ROOT = os.path.realpath(os.path.dirname(__file__))
# ... #
STATIC_ROOT = os.path.join(SITE_ROOT, 'static')
# ... #
STATIC_URL = '/static/'

in my urls.py I have:

urlpatterns = patterns('',
url(r'^', include('myapp.urls')),
url(r'^admin/', include(admin.site.urls)),
)

if settings.DEBUG:
urlpatterns += patterns('',
    url(r'^static/(?P<path>.*)', 'django.views.static.serve', {
        'document_root': settings.STATIC_ROOT,
    }),

)

and in my template:

Which doesn't work. The weird thing is that if I change my settings.py:

STATIC_URL = 'static/'

and my template to:

does work!! I have been chasing round in circle to fix this, and I have looked at lots of forum posts, but I can't seem to figure out what I'm doing wrong.

Body:
if you use staticfiles app you don't need this (assuming you are using Django 1.3):

if settings.DEBUG:
    urlpatterns += patterns('',
        url(r'^static/(?P<path>.*)', 'django.views.static.serve', {
            'document_root': settings.STATIC_ROOT,
    })

Its handled by the app automatically. Try to remove and see what happens.


问:
I am trying to create_all() for a postgresql table but i am getting weird errors
My python flask code (quotes.py) is :

```<code>from flask import Flask, render_template, request, redirect, url_for
from flask_sqlalchemy import SQLAlchemy

app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'postgresql+psycopg2:// postgres:password@localhost/quotes'
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False

db = SQLAlchemy(app)

class Favquotes(db.Model):

    id = db.Column(db.Integer, primary_key = True)
    author = db.Column(db.String(30))
    quote = db.Column(db.String(2000))

@app.route('/')
def index():
    result = Favquotes.query.all()
    return render_template('index.html', result = result)

@app.route('/quotes')
def quotes():
    return render_template('quotes.html')

@app.route('/process', methods = ['POST'])
def process():
    author = request.form['author']
    quote = request.form['quote']
    quotedata = Favquotes(author = author , quote = quote)
    db.session.add(quotedata)
    db.session.commit()
    return redirect(url_for('index'))
</code>```

Getting the following errors :

```<code>>>> from quotes import db
>>> db.create_all()
Traceback (most recent call last):
  File "C:\Users\KIIT\Desktop\fav-quotes\venv\lib\site-packages\sqlalchemy\engine\base.py", line 3250, in _wrap_pool_connect
    return fn()
  File "C:\Users\KIIT\Desktop\fav-quotes\venv\lib\site-packages\sqlalchemy\pool\base.py", line 310, in connect
    return _ConnectionFairy._checkout(self)
  File "C:\Users\KIIT\Desktop\fav-quotes\venv\lib\site-packages\sqlalchemy\pool\base.py", line 868, in _checkout
    fairy = _ConnectionRecord.checkout(pool)
  File "C:\Users\KIIT\Desktop\fav-quotes\venv\lib\site-packages\sqlalchemy\pool\base.py", line 476, in checkout
    rec = pool._do_get()
  File "C:\Users\KIIT\Desktop\fav-quotes\venv\lib\site-packages\sqlalchemy\pool\impl.py", line 146, in _do_get
    self._dec_overflow()
  File "C:\Users\KIIT\Desktop\fav-quotes\venv\lib\site-packages\sqlalchemy\util\langhelpers.py", line 70, in __exit__
    compat.raise_(
  File "C:\Users\KIIT\Desktop\fav-quotes\venv\lib\site-packages\sqlalchemy\util\compat.py", line 207, in raise_
    raise exception
  File "C:\Users\KIIT\Desktop\fav-quotes\venv\lib\site-packages\sqlalchemy\pool\impl.py", line 143, in _do_get
    return self._create_connection()
  File "C:\Users\KIIT\Desktop\fav-quotes\venv\lib\site-packages\sqlalchemy\pool\base.py", line 256, in _create_connection
    return _ConnectionRecord(self)
  File "C:\Users\KIIT\Desktop\fav-quotes\venv\lib\site-packages\sqlalchemy\pool\base.py", line 371, in __init__
    self.__connect()
  File "C:\Users\KIIT\Desktop\fav-quotes\venv\lib\site-packages\sqlalchemy\pool\base.py", line 666, in __connect
    pool.logger.debug("Error on connect(): %s", e)
  File "C:\Users\KIIT\Desktop\fav-quotes\venv\lib\site-packages\sqlalchemy\util\langhelpers.py", line 70, in __exit__
    compat.raise_(
  File "C:\Users\KIIT\Desktop\fav-quotes\venv\lib\site-packages\sqlalchemy\util\compat.py", line 207, in raise_
    raise exception
  File "C:\Users\KIIT\Desktop\fav-quotes\venv\lib\site-packages\sqlalchemy\pool\base.py", line 661, in __connect
    self.dbapi_connection = connection = pool._invoke_creator(self)
  File "C:\Users\KIIT\Desktop\fav-quotes\venv\lib\site-packages\sqlalchemy\engine\create.py", line 590, in connect
    return dialect.connect(*cargs, **cparams)
  File "C:\Users\KIIT\Desktop\fav-quotes\venv\lib\site-packages\sqlalchemy\engine\default.py", line 597, in connect
    return self.dbapi.connect(*cargs, **cparams)
  File "C:\Users\KIIT\Desktop\fav-quotes\venv\lib\site-packages\psycopg2\__init__.py", line 122, in connect
    conn = _connect(dsn, connection_factory=connection_factory, **kwasync)
psycopg2.OperationalError: connection to server at "localhost" (::1), port 5432 failed: FATAL:  password authentication failed for user " postgres"
</code>```

my pip list contain :

```<code>(venv) PS C:\Users\KIIT\Desktop\fav-quotes> pip list
Package          Version
---------------- -------
 - click            8.0.3
 - colorama         0.4.4
 - Flask            2.0.2
 - Flask-SQLAlchemy 2.5.1
 - greenlet         1.1.2
 - gunicorn         20.1.0
 - itsdangerous     2.0.1
 - Jinja2           3.0.3
 - MarkupSafe       2.0.1
 - pip              22.0.3
 - psycopg2         2.9.3
 - python-dotenv    0.19.2
 - setuptools       47.1.0
 - SQLAlchemy       1.4.31
 - Werkzeug         2.0.2
</code>```

and as you can see i am using a virtual environment.

答:
the error is self explantory;

```<code>psycopg2.OperationalError: connection to server at "localhost" (::1), port 5432 failed: FATAL:  password authentication failed for user " postgres"
</code>```

i guess, there's an extra blank character in user name : postgres, so you should remove it in:

```<code>app.config['SQLALCHEMY_DATABASE_URI'] = 'postgresql+psycopg2://postgres:password@localhost/quotes'
</code>```

Body:
My python flask code (quotes.py) is :

from flask import Flask, render_template, request, redirect, url_for
from flask_sqlalchemy import SQLAlchemy

app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'postgresql+psycopg2:// postgres:password@localhost/quotes'
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False

db = SQLAlchemy(app)

class Favquotes(db.Model):

    id = db.Column(db.Integer, primary_key = True)
    author = db.Column(db.String(30))
    quote = db.Column(db.String(2000))

@app.route('/')
def index():
    result = Favquotes.query.all()
    return render_template('index.html', result = result)

@app.route('/quotes')
def quotes():
    return render_template('quotes.html')

@app.route('/process', methods = ['POST'])
def process():
    author = request.form['author']
    quote = request.form['quote']
    quotedata = Favquotes(author = author , quote = quote)
    db.session.add(quotedata)
    db.session.commit()
    return redirect(url_for('index'))

Getting the following errors :

>>> from quotes import db
>>> db.create_all()
Traceback (most recent call last):
  File "C:\Users\KIIT\Desktop\fav-quotes\venv\lib\site-packages\sqlalchemy\engine\base.py", line 3250, in _wrap_pool_connect
    return fn()
  File "C:\Users\KIIT\Desktop\fav-quotes\venv\lib\site-packages\sqlalchemy\pool\base.py", line 310, in connect
    return _ConnectionFairy._checkout(self)
  File "C:\Users\KIIT\Desktop\fav-quotes\venv\lib\site-packages\sqlalchemy\pool\base.py", line 868, in _checkout
    fairy = _ConnectionRecord.checkout(pool)
  File "C:\Users\KIIT\Desktop\fav-quotes\venv\lib\site-packages\sqlalchemy\pool\base.py", line 476, in checkout
    rec = pool._do_get()
  File "C:\Users\KIIT\Desktop\fav-quotes\venv\lib\site-packages\sqlalchemy\pool\impl.py", line 146, in _do_get
    self._dec_overflow()
  File "C:\Users\KIIT\Desktop\fav-quotes\venv\lib\site-packages\sqlalchemy\util\langhelpers.py", line 70, in __exit__
    compat.raise_(
  File "C:\Users\KIIT\Desktop\fav-quotes\venv\lib\site-packages\sqlalchemy\util\compat.py", line 207, in raise_
    raise exception
  File "C:\Users\KIIT\Desktop\fav-quotes\venv\lib\site-packages\sqlalchemy\pool\impl.py", line 143, in _do_get
    return self._create_connection()
  File "C:\Users\KIIT\Desktop\fav-quotes\venv\lib\site-packages\sqlalchemy\pool\base.py", line 256, in _create_connection
    return _ConnectionRecord(self)
  File "C:\Users\KIIT\Desktop\fav-quotes\venv\lib\site-packages\sqlalchemy\pool\base.py", line 371, in __init__
    self.__connect()
  File "C:\Users\KIIT\Desktop\fav-quotes\venv\lib\site-packages\sqlalchemy\pool\base.py", line 666, in __connect
    pool.logger.debug("Error on connect(): %s", e)
  File "C:\Users\KIIT\Desktop\fav-quotes\venv\lib\site-packages\sqlalchemy\util\langhelpers.py", line 70, in __exit__
    compat.raise_(
  File "C:\Users\KIIT\Desktop\fav-quotes\venv\lib\site-packages\sqlalchemy\util\compat.py", line 207, in raise_
    raise exception
  File "C:\Users\KIIT\Desktop\fav-quotes\venv\lib\site-packages\sqlalchemy\pool\base.py", line 661, in __connect
    self.dbapi_connection = connection = pool._invoke_creator(self)
  File "C:\Users\KIIT\Desktop\fav-quotes\venv\lib\site-packages\sqlalchemy\engine\create.py", line 590, in connect
    return dialect.connect(*cargs, **cparams)
  File "C:\Users\KIIT\Desktop\fav-quotes\venv\lib\site-packages\sqlalchemy\engine\default.py", line 597, in connect
    return self.dbapi.connect(*cargs, **cparams)
  File "C:\Users\KIIT\Desktop\fav-quotes\venv\lib\site-packages\psycopg2\__init__.py", line 122, in connect
    conn = _connect(dsn, connection_factory=connection_factory, **kwasync)
psycopg2.OperationalError: connection to server at "localhost" (::1), port 5432 failed: FATAL:  password authentication failed for user " postgres"

my pip list contain :

(venv) PS C:\Users\KIIT\Desktop\fav-quotes> pip list
Package          Version
---------------- -------
 - click            8.0.3
 - colorama         0.4.4
 - Flask            2.0.2
 - Flask-SQLAlchemy 2.5.1
 - greenlet         1.1.2
 - gunicorn         20.1.0
 - itsdangerous     2.0.1
 - Jinja2           3.0.3
 - MarkupSafe       2.0.1
 - pip              22.0.3
 - psycopg2         2.9.3
 - python-dotenv    0.19.2
 - setuptools       47.1.0
 - SQLAlchemy       1.4.31
 - Werkzeug         2.0.2

and as you can see i am using a virtual environment.

Body:
the error is self explantory;

psycopg2.OperationalError: connection to server at "localhost" (::1), port 5432 failed: FATAL:  password authentication failed for user " postgres"

i guess, there's an extra blank character in user name : postgres, so you should remove it in:

app.config['SQLALCHEMY_DATABASE_URI'] = 'postgresql+psycopg2://postgres:password@localhost/quotes'


问:
Handling error from async await syntax with axios
Here's my chunk of code:

```<code>  const getToken = async () => {
    try {
      const token = await axios.post(keys.sessionURL, {
        email: keys.verificationEmail,
        password: keys.verificationPassword,
      });
    } catch (err) {
      throw new Error('Unable to establish a login session.'); // here I'd like to send the error to the user instead
    }
  };
</code>```

So as you can see I'm connecting to external server in order to get a token. And that works. Now, I'd like to catch an error but this time not with 'throw new error' but I'd like to send it to the user, so I'd like to have something like this instead:

```<code>res.status(401).send('Unable to get a token');
</code>```

But because I'm not inside the route handler I cannot use 'res'. How can I send it to the user then?

Thank you!

答:
Elegant & with TypeScript.</p>
```<code>import axios, { AxiosResponse, AxiosError } from "axios";
...

const response: void | AxiosResponse<any, any> = await axios({
  headers: {
    Authorization: `Bearer ${XYZ}`,
    Accept: "application/json",
  },
  method: "GET",
  params: {
    ...
  },
  url: "https://api.abcd.com/...",
}).catch((error: AxiosError) => {
  if (error instanceof Error) {
    console.error(
      "Error with fetching ..., details: ",
      error
    );
  }
});
</code>```

Body:
Here's my chunk of code:

  const getToken = async () => {
    try {
      const token = await axios.post(keys.sessionURL, {
        email: keys.verificationEmail,
        password: keys.verificationPassword,
      });
    } catch (err) {
      throw new Error('Unable to establish a login session.'); // here I'd like to send the error to the user instead
    }
  };

So as you can see I'm connecting to external server in order to get a token. And that works. Now, I'd like to catch an error but this time not with 'throw new error' but I'd like to send it to the user, so I'd like to have something like this instead:

res.status(401).send('Unable to get a token');

But because I'm not inside the route handler I cannot use 'res'. How can I send it to the user then?

Thank you!

Body:
Elegant & with TypeScript.

import axios, { AxiosResponse, AxiosError } from "axios";
...

const response: void | AxiosResponse<any, any> = await axios({
  headers: {
    Authorization: `Bearer ${XYZ}`,
    Accept: "application/json",
  },
  method: "GET",
  params: {
    ...
  },
  url: "https://api.abcd.com/...",
}).catch((error: AxiosError) => {
  if (error instanceof Error) {
    console.error(
      "Error with fetching ..., details: ",
      error
    );
  }
});


问:
Could not parse the JSON file ,Error in Progam.cs asp.net core
I have some issues with the program.cs file, with the version of ASP.NetCORE 2.0

Here's my code

```<code>     public class Program
{
    public static void Main(string[] args)
    {
        BuildWebHost(args).Run();
    }

    public static IWebHost BuildWebHost(string[] args) =>
        WebHost.CreateDefaultBuilder(args)
            .UseContentRoot(Directory.GetCurrentDirectory())
            .UseIISIntegration()
            .UseKestrel()
            .UseStartup<Startup>()
            .UseConfiguration(new ConfigurationBuilder().AddCommandLine(args).Build())
            .Build();

}
</code>```

When I run the project, following error occurs.

```<code>System.FormatException: 'Could not parse the JSON file. Error on line number '0': ''.'
</code>```

How to resolve it?

答: for me, it was missing comma in appsettings.json</p>

Body:
I have some issues with the program.cs file, with the version of ASP.NetCORE 2.0

Here's my code

     public class Program
{
    public static void Main(string[] args)
    {
        BuildWebHost(args).Run();
    }

    public static IWebHost BuildWebHost(string[] args) =>
        WebHost.CreateDefaultBuilder(args)
            .UseContentRoot(Directory.GetCurrentDirectory())
            .UseIISIntegration()
            .UseKestrel()
            .UseStartup<Startup>()
            .UseConfiguration(new ConfigurationBuilder().AddCommandLine(args).Build())
            .Build();

}

When I run the project, following error occurs.

System.FormatException: 'Could not parse the JSON file. Error on line number '0': ''.'

How to resolve it?


问:
MS Word vba in MS Access
I'm trying to use ms Access to open up ms word, create formfield and tables but always end up empty. I tried using the same code but replacing the entire code between "with doc" to .formfields("TxtDate").result = me.txt2 and is able to transfer whatever i typed in txt2 into the formfield located in ms word. Thus I'm unsure which portion of the code went wrong. Would like to seek help on my code. Thanks</p>
```<code>Function FillWordForm()
Dim appword as Word.Application
Dim doc as Word.Document
Dim Path as String

On Error Resume Next
Error.Clear
Path = "H:\project delta\test.docx"
Set appword = GetObject(, "word.application")
If Err.Number <> 0 then
    Set appword = New Word.Application
    appword.Visible = true
End if
Set doc = appword.Documents.open(Path, , False)
With Doc
    Selection.TypeParagraph
    Selection.FormFields.Add Range:=Selection.Range, Type:= _
        WdFieldFormTextInput
    ActiveDocument.FormFields.Shaded = Not ActiveDocument.FormFields.Shaded
    ActiveDocument.Tables.Add Range:=Selection.Range, NumRows:=13, NumColumns:= _
        4, DefaultTableBehavior:=wdWord9TableBehavior, AutoFitBehavior:= _
        wdAutoFitFixed
    With Selection.Tables(1)
        If .Style <> "Table Grid" then
            .Style = "Table Grid"
        End If
        .ApplyStyleHeadingRows = True
        .ApplyStyleLastRow = False
        .ApplyStyleFirstColumn = True
        .ApplyStyleLastColumn = False
        .ApplyStyleRowBands = True
        .ApplyStyleColumnBands = True
        .Cell(1,1).Select
        Selection.TypeText Text:="S/N"
        .Cell(1,2).Select
        Selection.TypeText Text:="Package Title"
        .Cell(1,3).Select
        Selection.TypeText Text:="Reference"
        .Cell(1,4).Select
        Selection.TypeText Text:="Month"
    End With
appword.Visible = True
appword.Activate
End With
Set doc = Nothing
Set appword = Nothing

End Function
</code>```

答:
Considering comments, issue is likely due to a Word process still running in background even though not showing in Task Manager. This can be caused by unqualified references to Word objects.

Prefix appword. in front of every Selection and ActiveDocument usage and code should then run every time. It does for me now.

This can also happen with automation code for other Office apps - Excel, Outlook, PowerPoint, etc.

Title: MS Word vba in MS Access

Body:
I'm trying to use ms Access to open up ms word, create formfield and tables but always end up empty. I tried using the same code but replacing the entire code between "with doc" to .formfields("TxtDate").result = me.txt2 and is able to transfer whatever i typed in txt2 into the formfield located in ms word. Thus I'm unsure which portion of the code went wrong. Would like to seek help on my code. Thanks

Function FillWordForm()
Dim appword as Word.Application
Dim doc as Word.Document
Dim Path as String

On Error Resume Next
Error.Clear
Path = "H:\project delta\test.docx"
Set appword = GetObject(, "word.application")
If Err.Number <> 0 then
    Set appword = New Word.Application
    appword.Visible = true
End if
Set doc = appword.Documents.open(Path, , False)
With Doc
    Selection.TypeParagraph
    Selection.FormFields.Add Range:=Selection.Range, Type:= _
        WdFieldFormTextInput
    ActiveDocument.FormFields.Shaded = Not ActiveDocument.FormFields.Shaded
    ActiveDocument.Tables.Add Range:=Selection.Range, NumRows:=13, NumColumns:= _
        4, DefaultTableBehavior:=wdWord9TableBehavior, AutoFitBehavior:= _
        wdAutoFitFixed
    With Selection.Tables(1)
        If .Style <> "Table Grid" then
            .Style = "Table Grid"
        End If
        .ApplyStyleHeadingRows = True
        .ApplyStyleLastRow = False
        .ApplyStyleFirstColumn = True
        .ApplyStyleLastColumn = False
        .ApplyStyleRowBands = True
        .ApplyStyleColumnBands = True
        .Cell(1,1).Select
        Selection.TypeText Text:="S/N"
        .Cell(1,2).Select
        Selection.TypeText Text:="Package Title"
        .Cell(1,3).Select
        Selection.TypeText Text:="Reference"
        .Cell(1,4).Select
        Selection.TypeText Text:="Month"
    End With
appword.Visible = True
appword.Activate
End With
Set doc = Nothing
Set appword = Nothing

End Function