问:
Word document not displaying header, footer and images when using WordProcessingDocument
I am using WordprocessingDocument to Read and write content to a word document but when I am opening the document using MemoryStream, it is not showing me the images and header/footer which is already in the word document. Below is the code for the same.

```<code>private void AddReport(MainDocumentPart parent, MemoryStream report)
        {
            using (MemoryStream editingMemoryStream = new MemoryStream())
            {
                report.Position = 0;
                report.CopyTo(editingMemoryStream);
                editingMemoryStream.Position = 0;
                using (WordprocessingDocument newDoc = WordprocessingDocument.Open(editingMemoryStream, true))
                {
                    WP.Body Template = newDoc.MainDocumentPart.Document.Body;
                    var Main = newDoc.MainDocumentPart;
                    var cloneTemplate = Template.CloneNode(true);

                    parent.Document.Body.PrependChild(new WP.Paragraph(new WP.Run(cloneTemplate)));
                    parent.Document.Save();
                }
            }
        }
</code>```

Screenshot for the word document:
enter image description here
In this, the Parent document is the document where I am pre-pending the above document. Any help will be appreciated. Thanks in advance.

答:
The headers, footers and images are not part of the document body, so won't be carried over to another document in the described scenario.

All this information is stored in separate "xml parts" contained within the Word file's "zip package". The Body part contains only refereces (relationship IDs listed in a "rel" part that point/link to the relevant xml part contained in the package).

This can be seen by opening the document in the Open XML SDK Productivity Tool and inspecting the underlying Word Open XML.

In order to copy such content to another document it's necessary to clone not only the body, but also each and every relevant xml part with content you want to have, while dynamically generating the necessary relationships - not a trivial undertaking. There are posts here and elsewhere in the Internet (including my blog, the WordMeister) that demonstrate the basics of how this is done which you could use as starting points for understanding the required approach.

Or, depending on what the Parent document is, it might make more sense to start with a copy of the "new" document and edit it with the other content.

FWIW and mentioned here for the sake of completeness: The COM object model will do what is described - copy the body of the document and paste to another document does carry over all this information. But the Word application is doing all the "heavy lifting" that the developer needs to code when using the Open XML SDK.

Body:
I am using WordprocessingDocument to Read and write content to a word document but when I am opening the document using MemoryStream, it is not showing me the images and header/footer which is already in the word document. Below is the code for the same.

private void AddReport(MainDocumentPart parent, MemoryStream report)
        {
            using (MemoryStream editingMemoryStream = new MemoryStream())
            {
                report.Position = 0;
                report.CopyTo(editingMemoryStream);
                editingMemoryStream.Position = 0;
                using (WordprocessingDocument newDoc = WordprocessingDocument.Open(editingMemoryStream, true))
                {
                    WP.Body Template = newDoc.MainDocumentPart.Document.Body;
                    var Main = newDoc.MainDocumentPart;
                    var cloneTemplate = Template.CloneNode(true);

                    parent.Document.Body.PrependChild(new WP.Paragraph(new WP.Run(cloneTemplate)));
                    parent.Document.Save();
                }
            }
        }

Screenshot for the word document:
enter image description here
In this, the Parent document is the document where I am pre-pending the above document. Any help will be appreciated. Thanks in advance.


来源: stackexchange

问:
Having trouble with downloading a page using the requests function - returning the 410 html error code but works in browser
I've tried searching for this - can't seem to find the answer!

I'm trying to do a really simple scrape of an entire webpage so that I can look for key words. I'm using the following code:

```<code>import requests
Website = requests.get('http://www.somfy.com', {'User-Agent':'a'}, headers = {'Accept': '*/*'})
print (Website.text)
print (Website.status_code)
</code>```

When I visit this website in a browser (eg chrome or firefox) it works. When I run the python code I just get the result "Gone" (error code 410).

I'd like to be able to reliably put in a range of website urls, and pull back the raw html to be able to look for key-words.

Questions

 1. What have I done wrong, and how should I set this up to have the best chance of success in the future.

 2. Could you point me to any guidance on how to go about working out what is wrong?

Many thanks - and sorry for the beginner questions!

答:
You have an invalid User-Agent and you didn't include it in your headers.

I have fixed your code for you - it returns a 200 status code.

```<code>import requests
Website = requests.get('http://www.somfy.com', headers= {'User-Agent':'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/77.0.3835.0 Safari/537.36', 'Accept': '*/*'})
print (Website.text)
print (Website.status_code)
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I've tried searching for this - can't seem to find the answer!

I'm trying to do a really simple scrape of an entire webpage so that I can look for key words. I'm using the following code:

import requests
Website = requests.get('http://www.somfy.com', {'User-Agent':'a'}, headers = {'Accept': '*/*'})
print (Website.text)
print (Website.status_code)

When I visit this website in a browser (eg chrome or firefox) it works. When I run the python code I just get the result "Gone" (error code 410).

I'd like to be able to reliably put in a range of website urls, and pull back the raw html to be able to look for key-words.

Questions

 1. What have I done wrong, and how should I set this up to have the best chance of success in the future.

 2. Could you point me to any guidance on how to go about working out what is wrong?

Many thanks - and sorry for the beginner questions!

Body:
You have an invalid User-Agent and you didn't include it in your headers.

I have fixed your code for you - it returns a 200 status code.

import requests
Website = requests.get('http://www.somfy.com', headers= {'User-Agent':'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/77.0.3835.0 Safari/537.36', 'Accept': '*/*'})
print (Website.text)
print (Website.status_code)


问:
Embedding Layer in Keras: Vocab Size +1
From a number of examples I have seen, when we use text_tokenizer from keras, when specifying the input size for the input layer, we use vocab size +1.  This naturally yields an embedding space with +1 'rows'.

For example, I fit a simple model to estimate the embedding vectors for a vocab of size 3 = I like turtles.  The embedding space has length 5 per word in our vocabulary.

The embedding weights are:

```<code>0.01209533  0.034303080 -0.04666784 0.02803965  -0.03691160
-0.01302978 -0.030584216    -0.02506201 0.04771456  0.01906699
0.02800793  0.042204402 0.05223191  -0.01184921 0.02000498
0.02692273  -0.008792922    0.01560913  -0.02783649 0.02692282

</code>```

My question:  I assume that the first "row" in our matrix is the 0-based vector, such that rows 2, 3, and 4 would be associated with "I", "like", and "turtles" respectively.

Is this the case?  I want to ensure that I align my vocabulary properly, but I haven't been able to pin down any documentation to confirm this assumption.

答:
I understand that you are wanting to extract the embedding for each word, but I think the real question is: What is the output the tokenizer is producing.

Also, that tokenizer is a bit of a mess. You'll see what I mean below.

Because the tokenizer will filter words (assuming a non-trivial vocabulary), I don't want to assume that the words are stored in the order in which they are found. So here I programmatically determine the vocabulary using word_index. I then explicitly check what words are tokenized after filtering for the most frequently used words. (Word_index remembers all words; i.e. the pre-filtered values.)

import tensorflow as tf
from tensorflow.keras.preprocessing.text import Tokenizer
corpus = 'I like turtles'
num_words = len(corpus.split())
oov = 'OOV'
tokenizer = Tokenizer(num_words=num_words + 2, oov_token=oov)
tokenizer.fit_on_texts(corpus.split())
print(f'word_index: {tokenizer.word_index}')
print(f'vocabulary: {tokenizer.word_index.keys()}')
text = [key for key in tokenizer.word_index.keys()]
print(f'keys: {text}: {tokenizer.texts_to_sequences(text)}')

text = 'I like turtles'.split()
print(f'{text}: {tokenizer.texts_to_sequences(text)}')

text = 'I like marshmallows'.split()
print(f'{text}: {tokenizer.texts_to_sequences(text)}')
```

<p>This produces the following output:</p>

```word_index: {'OOV': 1, 'i': 2, 'like': 3, 'turtles': 4}
vocabulary: dict_keys(['OOV', 'i', 'like', 'turtles'])
keys: ['OOV', 'i', 'like', 'turtles']: [[1], [2], [3], [4]]
['I', 'like', 'turtles']: [[2], [3], [4]]
['I', 'like', 'marshmallows']: [[2], [3], [1]]
```

<p>However, if you specify oov_token, the output looks like this:</p>

```{'OOV': 1, 'i': 2, 'like': 3, 'turtles': 4}
```

Notice how I had to specify num_words=num_words + 2 instead of the expected '+1'.
That's because we're explicitly defining an OOV token, which gets added to the vocabulary, which is a bit nuts imo.

If you specify an OOV token and you set num_words=num_words + 1 (as documented), then 'I like turtles' gets the same encoding as 'I like marshmallows'. Also nuts.

Hopefully, you now have to tools to know what the tokenizer is feeding the encoding layer. Then hopefully, it'll be trivial to correlate the tokens with their embeddings.

Please let us know what you find. :)

(For more on the madness, check out this StackOverflow post.)

Title: Embedding Layer in Keras: Vocab Size +1

Body:
From a number of examples I have seen, when we use text_tokenizer from keras, when specifying the input size for the input layer, we use vocab size +1.  This naturally yields an embedding space with +1 'rows'.

For example, I fit a simple model to estimate the embedding vectors for a vocab of size 3 = I like turtles.  The embedding space has length 5 per word in our vocabulary.

The embedding weights are:

0.01209533  0.034303080 -0.04666784 0.02803965  -0.03691160
-0.01302978 -0.030584216    -0.02506201 0.04771456  0.01906699
0.02800793  0.042204402 0.05223191  -0.01184921 0.02000498
0.02692273  -0.008792922    0.01560913  -0.02783649 0.02692282

My question:  I assume that the first "row" in our matrix is the 0-based vector, such that rows 2, 3, and 4 would be associated with "I", "like", and "turtles" respectively.

Is this the case?  I want to ensure that I align my vocabulary properly, but I haven't been able to pin down any documentation to confirm this assumption.

Body:
I understand that you are wanting to extract the embedding for each word, but I think the real question is: What is the output the tokenizer is producing.

Also, that tokenizer is a bit of a mess. You'll see what I mean below.

Because the tokenizer will filter words (assuming a non-trivial vocabulary), I don't want to assume that the words are stored in the order in which they are found. So here I programmatically determine the vocabulary using word_index. I then explicitly check what words are tokenized after filtering for the most frequently used words. (Word_index remembers all words; i.e. the pre-filtered values.)

import tensorflow as tf
from tensorflow.keras.preprocessing.text import Tokenizer
corpus = 'I like turtles'
num_words = len(corpus.split())
oov = 'OOV'
tokenizer = Tokenizer(num_words=num_words + 2, oov_token=oov)
tokenizer.fit_on_texts(corpus.split())
print(f'word_index: {tokenizer.word_index}')
print(f'vocabulary: {tokenizer.word_index.keys()}')
text = [key for key in tokenizer.word_index.keys()]
print(f'keys: {text}: {tokenizer.texts_to_sequences(text)}')

text = 'I like turtles'.split()
print(f'{text}: {tokenizer.texts_to_sequences(text)}')

text = 'I like marshmallows'.split()
print(f'{text}: {tokenizer.texts_to_sequences(text)}')

This produces the following output:

word_index: {'OOV': 1, 'i': 2, 'like': 3, 'turtles': 4}
vocabulary: dict_keys(['OOV', 'i', 'like', 'turtles'])
keys: ['OOV', 'i', 'like', 'turtles']: [[1], [2], [3], [4]]
['I', 'like', 'turtles']: [[2], [3], [4]]
['I', 'like', 'marshmallows']: [[2], [3], [1]]

However, if you specify oov_token, the output looks like this:

{'OOV': 1, 'i': 2, 'like': 3, 'turtles': 4}

Notice how I had to specify num_words=num_words + 2 instead of the expected '+1'.
That's because we're explicitly defining an OOV token, which gets added to the vocabulary, which is a bit nuts imo.

If you specify an OOV token and you set num_words=num_words + 1 (as documented), then 'I like turtles' gets the same encoding as 'I like marshmallows'. Also nuts.

Hopefully, you now have to tools to know what the tokenizer is feeding the encoding layer. Then hopefully, it'll be trivial to correlate the tokens with their embeddings.

Please let us know what you find. :)

(For more on the madness, check out this StackOverflow post.)


问:
partial view was not found or no view engine supports the searched locations
I have following controller code:

```<code>public MyController:Controller
{
    public ActionResult Index()
    {
        return View();
    }

    [ChildActionOnly]
    public ActionResult MyPartialViewAction()
    {
        return PartialView("~/Views/Shared/MyCustomFolder/_MyPartialView",PartialViewModel);
    }
}
</code>```

and my Index view has the following code :

```<code>@HTML.Action("MyPartialViewAction")
</code>```

When I run the Web app I get HttpException with InnerExceptionMessage as :

InnerException    {"The partial view '~/Views/Shared/MyCustomFolder/_MyPartialView' was not found or no view engine supports the searched locations. The following locations were searched:\r\n~~/Views/Shared/MyCustomFolder/_MyPartialView"}    System.Exception {System.InvalidOperationException}

What I have tried till now :

Tried moving _MyPartialView from ~/Views/Shared/MyCustomFolder to ~/Views/Shared/ and ~/Views/MyControllerFolder but still error exists

Tried changing my Index View code to @HTML.RenderAction() but no luck.

Any inputs on where I'm going wrong ?

Thanks

答:
Hope, this code helps you (In ".cshtml" file)

```<code>@using Microsoft.AspNetCore.Mvc.ViewEngines
@inject ICompositeViewEngine Engine

....
string path = "../Themes/User/_head";

@if (Engine.FindView(ViewContext, path, isMainPage: false).Success)
{
    <partial name="@path" for="@Model" />
}
else
{
    <partial name="../Themes/Admin/_head" />
}
</code>```

Thanks

ContentLicense: CC BY-SA 3.0

Body:
I have following controller code:

public MyController:Controller
{
    public ActionResult Index()
    {
        return View();
    }

    [ChildActionOnly]
    public ActionResult MyPartialViewAction()
    {
        return PartialView("~/Views/Shared/MyCustomFolder/_MyPartialView",PartialViewModel);
    }
}

and my Index view has the following code :

@HTML.Action("MyPartialViewAction")

When I run the Web app I get HttpException with InnerExceptionMessage as :

InnerException    {"The partial view '~/Views/Shared/MyCustomFolder/_MyPartialView' was not found or no view engine supports the searched locations. The following locations were searched:\r\n~~/Views/Shared/MyCustomFolder/_MyPartialView"}    System.Exception {System.InvalidOperationException}

What I have tried till now :

Tried moving _MyPartialView from ~/Views/Shared/MyCustomFolder to ~/Views/Shared/ and ~/Views/MyControllerFolder but still error exists

Tried changing my Index View code to @HTML.RenderAction() but no luck.

Any inputs on where I'm going wrong ?

Thanks

Body:
Hope, this code helps you (In ".cshtml" file)

@using Microsoft.AspNetCore.Mvc.ViewEngines
@inject ICompositeViewEngine Engine

....
string path = "../Themes/User/_head";

@if (Engine.FindView(ViewContext, path, isMainPage: false).Success)
{
    <partial name="@path" for="@Model" />
}
else
{
    <partial name="../Themes/Admin/_head" />
}

Thanks


问:
Lookahead regex failing to find the same overlapping matches
Is it possible to find overlapping matches using regular expressions when searching again for the same pattern? I want to be able to find matches that occurs three times. For example babab occurs three times in babababab:

babababab

babababab

babababab

This is my current Python implementation:

```<code>import re
matches = re.findall(r'(?=(\w+).*\1).*\1', "babababab")
print(matches)
</code>```

My program find only baba instead of babab. Thanks!

答:
We can generalize the solution to any regex.

Let's say we have a valid regex pattern which you want to search for overlapping matches.

In order to get overlapping matches, we need to avoid consuming characters in each match, relying on the bump-along mechanism to evaluate the regex on every position of the string. This can be achieved by surrounding the whole regex in a look-ahead (?=<pattern>), and we can nest a capturing group to capture the match (?=(<pattern>)).

This technique works for Python re engine since after it found an empty match, it will simply bump-along and will not re-evaluate the regex at the same position but looking for non-empty match on the second try like PCRE engine.

Sample code:

```<code>import re

inp = '10.5.20.52.48.10'
matches = [m[0] if type(m) is tuple else m for m in re.findall(r'(?=(\d+(\.\d+){2}))', inp)]
</code>```

Output:

```<code>['10.5.20', '0.5.20', '5.20.52', '20.52.48', '0.52.48', '52.48.10', '2.48.10']
</code>```

If the original pattern doesn't have numbered backreferences then we can build the overlapping version of the regex with string concatenation.

However, if it does, the regex will need to be modified manually to correct the backreferences which have been shifted by the additional capturing group.

Do note that this method doesn't give you overlapping matches starting at the same index (e.g. looking for a+ in aaa will give you 3 matches instead of 6 matches). It's not possible to implement overlapping match starting at the same index in most regex flavors/library, except for Perl.

Body:
Is it possible to find overlapping matches using regular expressions when searching again for the same pattern? I want to be able to find matches that occurs three times. For example babab occurs three times in babababab:

babababab

babababab

babababab

This is my current Python implementation:

import re
matches = re.findall(r'(?=(\w+).*\1).*\1', "babababab")
print(matches)

My program find only baba instead of babab. Thanks!

Body:
We can generalize the solution to any regex.

Let's say we have a valid regex pattern which you want to search for overlapping matches.

In order to get overlapping matches, we need to avoid consuming characters in each match, relying on the bump-along mechanism to evaluate the regex on every position of the string. This can be achieved by surrounding the whole regex in a look-ahead (?=<pattern>), and we can nest a capturing group to capture the match (?=(<pattern>)).

This technique works for Python re engine since after it found an empty match, it will simply bump-along and will not re-evaluate the regex at the same position but looking for non-empty match on the second try like PCRE engine.

Sample code:

import re

inp = '10.5.20.52.48.10'
matches = [m[0] if type(m) is tuple else m for m in re.findall(r'(?=(\d+(\.\d+){2}))', inp)]

Output:

['10.5.20', '0.5.20', '5.20.52', '20.52.48', '0.52.48', '52.48.10', '2.48.10']

If the original pattern doesn't have numbered backreferences then we can build the overlapping version of the regex with string concatenation.

However, if it does, the regex will need to be modified manually to correct the backreferences which have been shifted by the additional capturing group.

Do note that this method doesn't give you overlapping matches starting at the same index (e.g. looking for a+ in aaa will give you 3 matches instead of 6 matches). It's not possible to implement overlapping match starting at the same index in most regex flavors/library, except for Perl.


问:
Does stream reused allowed in C#?
Here is my code.

```<code>using (FileStream zipToOpen = new FileStream(@"D:\test\1.txt", FileMode.Open))
            {
                using (ZipArchive archive = new ZipArchive(zipToOpen, ZipArchiveMode.Update))
                {
                    ZipArchiveEntry readmeEntry = archive.CreateEntry("Readme.txt");
                    using (StreamWriter writer = new StreamWriter(readmeEntry.Open()))
                    {
                        writer.WriteLine("Information about this package.");
                        writer.WriteLine("========================");
                    }
                }

                // I reused this stream again and below code just a sample.
                // It would get exception
                using (ZipArchive archive = new ZipArchive(zipToOpen, ZipArchiveMode.Update))
                {
                    //System.ArgumentException: 'Update mode requires a stream with read, write, and seek capabilities.'
                }
            }
</code>```

Is this exception caused by 'stream cannot be resued in C#' ?
If the answer is yes, any office documents can let me take a reference ?

Thanks in advance, it's appreciate if your guys can provide some help.

答: By default, ZipArchive assumes lifetime control of the Stream it is handed, and disposes it when it is disposed. To avoid this, set leaveOpen to true in the constructor overloads. However: you will also probably need to rewind the stream between usages, so you'll need zipToOpen.Position = 0; between the two using blocks. Anecdotally, it does seem unlikely that 1.txt is a zip file, but... I guess it could be!

Title: Does stream reused allowed in C#?

Body:
Here is my code.

using (FileStream zipToOpen = new FileStream(@"D:\test\1.txt", FileMode.Open))
            {
                using (ZipArchive archive = new ZipArchive(zipToOpen, ZipArchiveMode.Update))
                {
                    ZipArchiveEntry readmeEntry = archive.CreateEntry("Readme.txt");
                    using (StreamWriter writer = new StreamWriter(readmeEntry.Open()))
                    {
                        writer.WriteLine("Information about this package.");
                        writer.WriteLine("========================");
                    }
                }

                // I reused this stream again and below code just a sample.
                // It would get exception
                using (ZipArchive archive = new ZipArchive(zipToOpen, ZipArchiveMode.Update))
                {
                    //System.ArgumentException: 'Update mode requires a stream with read, write, and seek capabilities.'
                }
            }

Is this exception caused by 'stream cannot be resued in C#' ?
If the answer is yes, any office documents can let me take a reference ?

Thanks in advance, it's appreciate if your guys can provide some help.


问:
Can we create a simple thesaurus from a field in a dataframe?
I am trying to find synonyms and antonyms for one word, using strings from a field in a dataframe and not a standard wordnet.synsets lexical database.  I'm pretty sure this is possible, but I'm not sure how to feed in the appropriate data source (my specific field).

For instance, the code below works fine.

```<code>import nltk
from nltk.corpus import wordnet   #Import wordnet from the NLTK
syn = list()
ant = list()
for synset in wordnet.synsets("fake"):
   for lemma in synset.lemmas():
      syn.append(lemma.name())    #add the synonyms
      if lemma.antonyms():    #When antonyms are available, add them into the list
          ant.append(lemma.antonyms()[0].name())
print('Synonyms: ' + str(syn))
print('Antonyms: ' + str(ant))
</code>```

I tried to convert the field to an array, and use that...

```<code>import pandas  as pd
import nltk.corpus
from nltk.corpus import stopwords, wordnet
from nltk.tokenize import word_tokenize
from nltk.stem import PorterStemmer, WordNetLemmatizer

df = pd.read_csv("C:\\my_path\\dataset.csv")
df['review_text'] = df['review_text'].astype(str)
type(df)
df.dtypes

asarray = pd.array(df['review_text'])

import nltk
from nltk.corpus import wordnet   #Import wordnet from the NLTK
syn = list()
ant = list()
for synset in wordnet.asarray('fake'):
   for lemma in df['review_text'].iterrows():
      syn.append(lemma.name())    #add the synonyms
      if lemma.antonyms():        #When antonyms are available, add them into the list
          ant.append(lemma.antonyms()[0].name())
print('Synonyms: ' + str(syn))
print('Antonyms: ' + str(ant))
</code>```

When I run that, I get this error:

```<code>AttributeError: 'WordNetCorpusReader' object has no attribute 'asarray'
</code>```

The field in the dataframe looks like this:

```<code>feels comfortable i wear day!
package came end missing box. since itâ€™s gift i update actual fit.
birkenstock amazing shoe!!!! i wish i ten pairs!
delivered advertised.... shoe looks & fits expected. leather color seems bit lighter one seen store, still satisfactory.
second pair i had. nothing beats them.
</code>```

These are the first 5 rows.  Maybe the issue is related to this thing (not sure):  itâ€™s

答:
It's a typo or something.

Error happens on:

```<code>for synset in wordnet.asarray('fake'):
</code>```

Where wordnet is an object from nltk.corpus, thus a WordNetCorpusReader

And before the for loop, you have

```<code>asarray = pd.array(df['review_text'])
</code>```

that reads in a Pandas array/series into the asarray variable. But it's not related to WordNetCorpusReader

Body:
I am trying to find synonyms and antonyms for one word, using strings from a field in a dataframe and not a standard wordnet.synsets lexical database.  I'm pretty sure this is possible, but I'm not sure how to feed in the appropriate data source (my specific field).

For instance, the code below works fine.

import nltk
from nltk.corpus import wordnet   #Import wordnet from the NLTK
syn = list()
ant = list()
for synset in wordnet.synsets("fake"):
   for lemma in synset.lemmas():
      syn.append(lemma.name())    #add the synonyms
      if lemma.antonyms():    #When antonyms are available, add them into the list
          ant.append(lemma.antonyms()[0].name())
print('Synonyms: ' + str(syn))
print('Antonyms: ' + str(ant))

I tried to convert the field to an array, and use that...

import pandas  as pd
import nltk.corpus
from nltk.corpus import stopwords, wordnet
from nltk.tokenize import word_tokenize
from nltk.stem import PorterStemmer, WordNetLemmatizer

df = pd.read_csv("C:\\my_path\\dataset.csv")
df['review_text'] = df['review_text'].astype(str)
type(df)
df.dtypes

asarray = pd.array(df['review_text'])

import nltk
from nltk.corpus import wordnet   #Import wordnet from the NLTK
syn = list()
ant = list()
for synset in wordnet.asarray('fake'):
   for lemma in df['review_text'].iterrows():
      syn.append(lemma.name())    #add the synonyms
      if lemma.antonyms():        #When antonyms are available, add them into the list
          ant.append(lemma.antonyms()[0].name())
print('Synonyms: ' + str(syn))
print('Antonyms: ' + str(ant))

When I run that, I get this error:

AttributeError: 'WordNetCorpusReader' object has no attribute 'asarray'

The field in the dataframe looks like this:

feels comfortable i wear day!
package came end missing box. since itâ€™s gift i update actual fit.
birkenstock amazing shoe!!!! i wish i ten pairs!
delivered advertised.... shoe looks & fits expected. leather color seems bit lighter one seen store, still satisfactory.
second pair i had. nothing beats them.

These are the first 5 rows.  Maybe the issue is related to this thing (not sure):  itâ€™s

Body:
It's a typo or something.

Error happens on:

for synset in wordnet.asarray('fake'):

Where wordnet is an object from nltk.corpus, thus a WordNetCorpusReader

And before the for loop, you have

asarray = pd.array(df['review_text'])

that reads in a Pandas array/series into the asarray variable. But it's not related to WordNetCorpusReader


问:
How do I get Swashbuckle to work in Asp.net Core 3.1 when using VersionByNamespaceConvention?
I'm using VersionByNamespaceConvention. In Startup.cs in ConfigureServices I added:

```<code>        services.AddApiVersioning(options =>
        {
            options.Conventions.Add(new VersionByNamespaceConvention());
        });

        services.AddSwaggerGen(c =>
        {
            c.SwaggerDoc("v1", new OpenApiInfo { Title = "My API", Version = "v1" });
            c.SwaggerDoc("v2", new OpenApiInfo { Title = "My API", Version = "v2" });
        });
</code>```

and in Configure

```<code>        app.UseSwagger();

        // Enable middleware to serve swagger-ui (HTML, JS, CSS, etc.),
        // specifying the Swagger JSON endpoint.
        app.UseSwaggerUI(c =>
        {
            c.SwaggerEndpoint("/swagger/v1/swagger.json", "My API V1");
            c.SwaggerEndpoint("/swagger/v2/swagger.json", "My API V2");
        });
</code>```

In the root of the project I have folders v1 and v2 and under those I have a Controllers folder. The code of the controllers (v2 is identical to v1, except for the namespace and the return value).

```<code>namespace WebApitest.v1.Controllers
{
    [ApiController]
    [Route("v{version:apiVersion}/[controller]")]
    public class WeatherForecastController : ControllerBase
    {
        [HttpGet]
        public string Get()
        {
            return "v1";
        }
    }
}
</code>```

The api itself is working good, but Swagger rendering is not working as expected.

When opening https://localhost:44307/swagger/index.html it shows a dropdown in the top right corner showing "My API V1" and "My API V2" but the middle of the screen is showing

Fetch error - undefined /swagger/v1/swagger.json

This works if I only have controllers in the v1 version. But then it is showing the version number like in the image below, even though the version number here is already selected.

The solution

I added the nuget package Microsoft.AspNetCore.Mvc.Versioning.ApiExplorer v4.x and added the following code to ConfigureServices and now it's working as expected.

```<code>        services.AddVersionedApiExplorer(o =>
        {
            o.GroupNameFormat = "'v'VVV";
            o.SubstituteApiVersionInUrl = true;
        });
</code>```

答:
You need to use services.AddVersionedApiExplorer and set options.SubstituteApiVersionInUrl=true to tell swagger to replace the version in the controller route and configure the api version:

```<code>services.AddVersionedApiExplorer(o =>
{
      o.GroupNameFormat = "'v'VVV";
      o.SubstituteApiVersionInUrl = true;
});
</code>```

Result:

Body:
I'm using VersionByNamespaceConvention. In Startup.cs in ConfigureServices I added:

        services.AddApiVersioning(options =>
        {
            options.Conventions.Add(new VersionByNamespaceConvention());
        });

        services.AddSwaggerGen(c =>
        {
            c.SwaggerDoc("v1", new OpenApiInfo { Title = "My API", Version = "v1" });
            c.SwaggerDoc("v2", new OpenApiInfo { Title = "My API", Version = "v2" });
        });

and in Configure

        app.UseSwagger();

        // Enable middleware to serve swagger-ui (HTML, JS, CSS, etc.),
        // specifying the Swagger JSON endpoint.
        app.UseSwaggerUI(c =>
        {
            c.SwaggerEndpoint("/swagger/v1/swagger.json", "My API V1");
            c.SwaggerEndpoint("/swagger/v2/swagger.json", "My API V2");
        });

In the root of the project I have folders v1 and v2 and under those I have a Controllers folder. The code of the controllers (v2 is identical to v1, except for the namespace and the return value).

namespace WebApitest.v1.Controllers
{
    [ApiController]
    [Route("v{version:apiVersion}/[controller]")]
    public class WeatherForecastController : ControllerBase
    {
        [HttpGet]
        public string Get()
        {
            return "v1";
        }
    }
}

The api itself is working good, but Swagger rendering is not working as expected.

When opening https://localhost:44307/swagger/index.html it shows a dropdown in the top right corner showing "My API V1" and "My API V2" but the middle of the screen is showing

Fetch error - undefined /swagger/v1/swagger.json

This works if I only have controllers in the v1 version. But then it is showing the version number like in the image below, even though the version number here is already selected.

The solution

I added the nuget package Microsoft.AspNetCore.Mvc.Versioning.ApiExplorer v4.x and added the following code to ConfigureServices and now it's working as expected.

        services.AddVersionedApiExplorer(o =>
        {
            o.GroupNameFormat = "'v'VVV";
            o.SubstituteApiVersionInUrl = true;
        });

Body:
You need to use services.AddVersionedApiExplorer and set options.SubstituteApiVersionInUrl=true to tell swagger to replace the version in the controller route and configure the api version:

services.AddVersionedApiExplorer(o =>
{
      o.GroupNameFormat = "'v'VVV";
      o.SubstituteApiVersionInUrl = true;
});

Result:


问:
Extract the green boxes from the picture and store into the folder
the code to extract the green boxes from the picture   "Python-Interview.jpg" and copy them to a folder.
  I have tried not working please provide some solution with this code

```<code>            # Import relevant libraries
   ''' image = cv.imread(fpath, -1)
    # convert to gray and binarize
    gray_img = cv.cvtColor(image, cv.COLOR_BGR2GRAY)
    binary_img = cv.adaptiveThreshold(gray_img, 255, cv.ADAPTIVE_THRESH_MEAN_C, cv.THRESH_BINARY, 9, 9)
     # note: erosion and dilation works on white forground
    binary_img = cv.bitwise_not(binary_img)
     # dilate the image
    kernel = cv.getStructuringElement(cv.MORPH_RECT, (1,1))
    dilated_img = cv.morphologyEx(binary_img, cv.MORPH_DILATE, kernel,iterations=1)

    # find contours, discard contours which do not belong to a rectangle
    (cnts, _) = cv.findContours(dilated_img.copy(), cv.RETR_LIST, cv.CHAIN_APPROX_SIMPLE)
    sq_cnts = []  # contours of interest to us
    for cnt in cnts:
        approx = cv.approxPolyDP(cnt,0.01*cv.arcLength(cnt,True),True)
        if len(approx) == 4:
            (x, y, w, h) = cv.boundingRect(cnt)
    #///////// fill remaining code here

    for i in range(len(sq_cnts)):
        # find squares
        (x, y, w, h) = cv.boundingRect(sq_cnts[i])
        newimg = image[y:y+h,x:x+w] # crop the image
        # Write the image
    '''
</code>```

The image is

答:
```<code>import cv2 as cv

image = cv.imread(r"----Path--\img1.jpg", -1)

gray_img = cv.cvtColor(image, cv.COLOR_BGR2GRAY)
binary_img = cv.adaptiveThreshold(gray_img, 255, cv.ADAPTIVE_THRESH_MEAN_C, cv.THRESH_BINARY, 9, 9)

binary_img = cv.bitwise_not(binary_img)

kernel = cv.getStructuringElement(cv.MORPH_RECT, (1,1))
dilated_img = cv.morphologyEx(binary_img, cv.MORPH_DILATE, kernel,iterations=1)

(cnts, _)= cv.findContours(dilated_img.copy(), cv.RETR_LIST, cv.CHAIN_APPROX_SIMPLE)
print("Number of countours = "+ str(len(cnts)))

sq_cnts = []

for cnt in cnts:
    approx = cv.approxPolyDP(cnt,0.01*cv.arcLength(cnt,True),True)

    if len(approx) == 4:
      (x, y, w, h) = cv.boundingRect(cnt)

      aspectRatio = float(w) / h
      print (aspectRatio,"Aspectratio")

      if aspectRatio > 1.0 and aspectRatio <= 1.08:
          cv.drawContours(image,[cnt], 0, (0,255,0), 3)
          sq_cnts.append(cnt)

          for i in range(len(sq_cnts)):

            (x, y, w, h) = cv.boundingRect(sq_cnts[i])
            newimg = image[y:y+h,x:x+w]

            cv.imwrite(str(i)+'.jpg',newimg)
            cv.imshow('img.jpg', newimg)

cv.waitKey(0)
cv.destroyAllWindows()
</code>```

Body:
the code to extract the green boxes from the picture   "Python-Interview.jpg" and copy them to a folder.
  I have tried not working please provide some solution with this code

            # Import relevant libraries
   ''' image = cv.imread(fpath, -1)
    # convert to gray and binarize
    gray_img = cv.cvtColor(image, cv.COLOR_BGR2GRAY)
    binary_img = cv.adaptiveThreshold(gray_img, 255, cv.ADAPTIVE_THRESH_MEAN_C, cv.THRESH_BINARY, 9, 9)
     # note: erosion and dilation works on white forground
    binary_img = cv.bitwise_not(binary_img)
     # dilate the image
    kernel = cv.getStructuringElement(cv.MORPH_RECT, (1,1))
    dilated_img = cv.morphologyEx(binary_img, cv.MORPH_DILATE, kernel,iterations=1)

    # find contours, discard contours which do not belong to a rectangle
    (cnts, _) = cv.findContours(dilated_img.copy(), cv.RETR_LIST, cv.CHAIN_APPROX_SIMPLE)
    sq_cnts = []  # contours of interest to us
    for cnt in cnts:
        approx = cv.approxPolyDP(cnt,0.01*cv.arcLength(cnt,True),True)
        if len(approx) == 4:
            (x, y, w, h) = cv.boundingRect(cnt)
    #///////// fill remaining code here

    for i in range(len(sq_cnts)):
        # find squares
        (x, y, w, h) = cv.boundingRect(sq_cnts[i])
        newimg = image[y:y+h,x:x+w] # crop the image
        # Write the image
    '''

The image is


问:
How do you represent this character in python? 
The empty box character shows up in a text, in place of a non-ascii character, so I need to replace that character in python, but I get an error:

SyntaxError: Non-ASCII character '\xef' in file pyautoGuiTiReg/main.py on line 197, but no encoding declared; see http://python.org/dev/peps/pep-0263/ for details.

I am not sure what encoding to use as this is a very weird symbol:

答:
For replace it try this</p>

```<code>ToBytes = str.encode('yourString', encoding='utf-8')
ReplaceBytes = ToBytes.replace(b'\xef',b'').decode('utf-8')
</code>```

Body:
For replace it try this

ToBytes = str.encode('yourString', encoding='utf-8')
ReplaceBytes = ToBytes.replace(b'\xef',b'').decode('utf-8')


问:
ATS policy issue when using a redirect url in Swift
I am using this link for example to load the link. Although the link is a http link it will be redirected to a https link. It works in the browser.
However, as soon as I let my iOS Application load the resource it will say "The resource could not be loaded because the App Transport Security policy requires the use of a secure connection.".

I am using this library to load the picture. Is it not supported that Swift loads the https resource? I could think of that ATS blocks the connection to the server so the redirect can't even be received.

I would be very thankful for any thoughts on this.

Christian

答:
Go to info.plist add a term called App Transport Security Settings.

And under that add Allow Arbitrary Loads


问:
Is there a setting where we can specify which field the cursor lands in for Harmon.ie
Users are asking if we can manage where the cursor lands for harmon.ie checkins of emails and/or attachments. </p>

答:
There is no way to control on which field the focus will in our edit properties window.
The logic is as follow.
In case there is no required fields:
-The focus will be on the first empty field
In case there are required fields:
-The focus will be on the first empty required fields.

---- Jean


问:
Is there any way to make Node2Vec faster?
I have a graph with 480k nodes and 34M edges. I want to create node embeddings using Node2Vec on this graph. But, It is not even able to calculate transition probabilities. I am using a Google Cloud Machine with 32 cores and 120 GB RAM. Infrastructure is not the problem, the problem is that the function _precompute_probabilities in the node2vec pip library is not paraller. It is using only a single thread to calculate the transition probabilities. Is there a way to make this parallel or is they any other parallel version of Node2Vec ?</p>

答:
I found a library Graph2Vec, it uses a CSR Matrix to generate walks instead of jumping from node to node in memory. It is way faster than Node2Vec.

Link: https://www.singlelunch.com/2019/08/01/700x-faster-node2vec-models-fastest-random-walks-on-a-graph/

Github: https://github.com/VHRanger/graph2vec

Also, you can refer to this issue and try the mentioned libraries:
https://github.com/aditya-grover/node2vec/issues/10


问:
How to implement usage of multiple strategies at runtime
I need to process a list of records returned from a service.

However the processing algorithm for a record changes completely based on a certain field on the record.

To implement this , I have defined an IProcessor interface which has just one method :

```<code>public interface IProcessor
{
    ICollection<OutputEntity> Process(ICollection<InputEntity>> entities);
}
</code>```

And I have two concrete implementations of IProcessor for the different types of processing.

The issue is that I need to use all implementations of IProcessor at the same time .. so how do I inject the IProcessor into my Engine class which drives the whole thing:

```<code>public class Engine
{
    public void ProcessRecords(IService service)
    {
        var records = service.GetRecords();
        var type1Records = records.Where(x => x.SomeField== "Type1").ToList();
        var type2Records = records.Where(x => x.SomeField== "Type2").ToList();

        IProcessor processor1 = new Type1Processor();
        processor.Process(type1Records);

        IProcessor processor2 = new Type2Processor();
        processor.Process(type2Records);
    }
}
</code>```

This is what I'm doing at present .. and it doesn't look nice and clean.

Any ideas as to how I could improve this design .. using IoC perhaps ?

答:
This might look a little bit complicated, but you can use attributes to mark your processors, and at runtime read the attributes and see what processor you have and build a dictionary out of it:</p>

```<code>public interface IProcessor
{
    ICollection<OutputEntity> Process(ICollection<InputEntity>> entities);
}

[Processor("Type1")]
public class Processor1 : IProcessor
{
}

[Processor("Type2")]
public class Processor1 : IProcessor
{
}

public class Engine
{
  Dictionary<string, IProcessor> processors;

  public Engine()
  {
     // use reflection to check the types marked with ProcessorAttribute and that implement IProcessor
     // put them in the processors dictionary
     // RegisterService(type, processor);
  }

  public RegisterService(string type, IProcessor processor)
  {
    processor[type] = processor;
  }

  public void ProcessRecords(IService service)
  {
     var records = service.GetRecords();
     foreach(var kvp in processors)
     {
        kvp.Value.Process(records.Where(record => record.SomeField == kvp.Key));
     }
  }
}
</code>```

Body:
I need to process a list of records returned from a service.

However the processing algorithm for a record changes completely based on a certain field on the record.

To implement this , I have defined an IProcessor interface which has just one method :

public interface IProcessor
{
    ICollection<OutputEntity> Process(ICollection<InputEntity>> entities);
}

And I have two concrete implementations of IProcessor for the different types of processing.

The issue is that I need to use all implementations of IProcessor at the same time .. so how do I inject the IProcessor into my Engine class which drives the whole thing:

public class Engine
{
    public void ProcessRecords(IService service)
    {
        var records = service.GetRecords();
        var type1Records = records.Where(x => x.SomeField== "Type1").ToList();
        var type2Records = records.Where(x => x.SomeField== "Type2").ToList();

        IProcessor processor1 = new Type1Processor();
        processor.Process(type1Records);

        IProcessor processor2 = new Type2Processor();
        processor.Process(type2Records);
    }
}

This is what I'm doing at present .. and it doesn't look nice and clean.

Any ideas as to how I could improve this design .. using IoC perhaps ?

Body:
This might look a little bit complicated, but you can use attributes to mark your processors, and at runtime read the attributes and see what processor you have and build a dictionary out of it:

public interface IProcessor
{
    ICollection<OutputEntity> Process(ICollection<InputEntity>> entities);
}

[Processor("Type1")]
public class Processor1 : IProcessor
{
}

[Processor("Type2")]
public class Processor1 : IProcessor
{
}

public class Engine
{
  Dictionary<string, IProcessor> processors;

  public Engine()
  {
     // use reflection to check the types marked with ProcessorAttribute and that implement IProcessor
     // put them in the processors dictionary
     // RegisterService(type, processor);
  }

  public RegisterService(string type, IProcessor processor)
  {
    processor[type] = processor;
  }

  public void ProcessRecords(IService service)
  {
     var records = service.GetRecords();
     foreach(var kvp in processors)
     {
        kvp.Value.Process(records.Where(record => record.SomeField == kvp.Key));
     }
  }
}


问:
PosgreSQL - loop syntax
I have the following loop (simplified for an example):

```<code>DO $$
  DECLARE
    l record;

  BEGIN
    FOR l IN SELECT id, country_id FROM logo LOOP
      WITH cs AS (
        INSERT INTO logo_settings (targeted) VALUES (true)
        RETURNING id
      )
      INSERT INTO logo_settings_targeted (logo_settings_id, country_id)
      VALUES
      ( (SELECT id FROM cs),
        logo.country_id,
      );
    END LOOP;
  END;
END $$;
</code>```

The body of a loop works fine. But if I wrap it into a loop (I would like to make records for all records from logo table) - it shows an error saying:

```<code>ERROR: syntax error at or near "END"
  Position: 712

END;
^
</code>```

meaning the last EnND before END $$; which does not give much sense to me. I do not know what to fix to make it running. Any hints?

答:
Additionally to answer of @Andronicus, this is one possible way to do this without PL/pgsql:

Click: demo:db<>fiddle

```<code>WITH countries AS  (
    SELECT id, country_id,
        row_number() OVER ()                                        -- 1
    FROM logo
), ins_settings AS (
    INSERT INTO logo_settings(targeted)
    SELECT true FROM countries c
    RETURNING id
)
INSERT INTO logo_settings_targeted (logo_settings_id, country_id)
SELECT
  ins.id, c.country_id
FROM
  (SELECT id, row_number() OVER () FROM ins_settings) ins            -- 2
JOIN countries c ON c.row_number = ins.row_number
</code>```

Put the first SELECT query (which you used for the loop) into a second CTE at the top.

The trick is, that you can join the outputs from the logo SELECT statement and the first insert. You can use the fact, that both outputs have the same number of rows. Simply add a column with a row count to both outputs. This can be done, for example, using the row_number() window function. As you can see, for the logo SELECT I already did this directly in the CTE (1), for the INSERT output I added this in a subquery (2). Now there are the same identifiers on both tables, which can be used for the join.

The join is the basis for the second INSERT.

Title: PosgreSQL - loop syntax

Body:
I have the following loop (simplified for an example):

DO $$
  DECLARE
    l record;

  BEGIN
    FOR l IN SELECT id, country_id FROM logo LOOP
      WITH cs AS (
        INSERT INTO logo_settings (targeted) VALUES (true)
        RETURNING id
      )
      INSERT INTO logo_settings_targeted (logo_settings_id, country_id)
      VALUES
      ( (SELECT id FROM cs),
        logo.country_id,
      );
    END LOOP;
  END;
END $$;

The body of a loop works fine. But if I wrap it into a loop (I would like to make records for all records from logo table) - it shows an error saying:

ERROR: syntax error at or near "END"
  Position: 712

END;
^

meaning the last EnND before END $$; which does not give much sense to me. I do not know what to fix to make it running. Any hints?

Body:
Additionally to answer of @Andronicus, this is one possible way to do this without PL/pgsql:

Click: demo:db<>fiddle

WITH countries AS  (
    SELECT id, country_id,
        row_number() OVER ()                                        -- 1
    FROM logo
), ins_settings AS (
    INSERT INTO logo_settings(targeted)
    SELECT true FROM countries c
    RETURNING id
)
INSERT INTO logo_settings_targeted (logo_settings_id, country_id)
SELECT
  ins.id, c.country_id
FROM
  (SELECT id, row_number() OVER () FROM ins_settings) ins            -- 2
JOIN countries c ON c.row_number = ins.row_number

Put the first SELECT query (which you used for the loop) into a second CTE at the top.

The trick is, that you can join the outputs from the logo SELECT statement and the first insert. You can use the fact, that both outputs have the same number of rows. Simply add a column with a row count to both outputs. This can be done, for example, using the row_number() window function. As you can see, for the logo SELECT I already did this directly in the CTE (1), for the INSERT output I added this in a subquery (2). Now there are the same identifiers on both tables, which can be used for the join.

The join is the basis for the second INSERT.


问:
File element on context menu is undefined - why?
I trying to rebuild my context menu (part 2 today). Now i have issue with undefined value of mu file element. I can't delete, rename or anything because of it.

HTML

```<code>    <mat-list-item *ngFor="let element of fileElements" (click)="navigate(element)" (contextmenu)="onContextMenu($event, element)" >
        [...]
    </mat-list-item>
[...]
<div style="visibility: hidden; position: fixed"
    [style.left]="contextMenuPosition.x"
    [style.top]="contextMenuPosition.y"
    [matMenuTriggerFor]="contextMenuTag">
</div>
<mat-menu #contextMenuTag="matMenu">
    <ng-template matMenuContent let-item>
    <div *ngFor="let element of contextMenu">
      <button *ngIf="!element.seperator" mat-menu-item (click)="callFunction(element, item)">
        {{element.name}}
      </button>
      <mat-divider *ngIf="element.seperator"></mat-divider>
    </div>
    </ng-template>
</mat-menu>
</code>```

ts

```<code>public callFunction(menu: MenuElement, file?: FileElement): void {
    console.log(file);  // <-- UNDEFINED THERE
    switch(menu.action) {
      case 'delete': {
        this.deleteElement(file);
        break;
      }
      [...]
    }
  }

private deleteElement(element: FileElement): void {
    this.elementRemoved.emit(element);
  }
</code>```

Before i changed my first implementation of UGLY context menu, delete action works. I think is fail at passing by (contextmenu)="onContextMenu($event, element)" to mat-menu on bottom. Maybe somebody know the issue?

答:
First, this is the forgotten event that the variable didn't name item.It seems like modified with sample code that you would found out the matMenuTriggerData would bind the data to your ng-template.

```

<p>In Addition, keep in mind to set the <code>let-item</code> to your variable, the variable would be defined in ts somehow. Otherwise, the item would bind to <code>$implict</code>.</p>

<pre class="lang-html prettyprint-override"><code><ng-template matMenuContent let-item="item">
[...]
</ng-template>
</code>```

Body:
I trying to rebuild my context menu (part 2 today). Now i have issue with undefined value of mu file element. I can't delete, rename or anything because of it.

HTML

    <mat-list-item *ngFor="let element of fileElements" (click)="navigate(element)" (contextmenu)="onContextMenu($event, element)" >
        [...]
    </mat-list-item>
[...]

<mat-menu #contextMenuTag="matMenu">
    <ng-template matMenuContent let-item>

      <button *ngIf="!element.seperator" mat-menu-item (click)="callFunction(element, item)">
        {{element.name}}
      </button>
      <mat-divider *ngIf="element.seperator"></mat-divider>

    </ng-template>
</mat-menu>

ts

public callFunction(menu: MenuElement, file?: FileElement): void {
    console.log(file);  // <-- UNDEFINED THERE
    switch(menu.action) {
      case 'delete': {
        this.deleteElement(file);
        break;
      }
      [...]
    }
  }

private deleteElement(element: FileElement): void {
    this.elementRemoved.emit(element);
  }

Before i changed my first implementation of UGLY context menu, delete action works. I think is fail at passing by (contextmenu)="onContextMenu($event, element)" to mat-menu on bottom. Maybe somebody know the issue?

Body:
First, this is the forgotten event that the variable didn't name item.It seems like modified with sample code that you would found out the matMenuTriggerData would bind the data to your ng-template.

<div style="visibility: hidden; position: fixed"
    [style.left]="contextMenuPosition.x"
    [style.top]="contextMenuPosition.y"
    [matMenuTriggerFor]="contextMenuTag"
    [matMenuTriggerData]="{item:theitemfromyourcode}" >
</div>

In Addition, keep in mind to set the let-item to your variable, the variable would be defined in ts somehow. Otherwise, the item would bind to $implict.

<ng-template matMenuContent let-item="item">
[...]
</ng-template>


问:
@Types/Sequelize Error TS1086: An accessor cannot be declared in ambient context
I have a project that shows this error when I run 'tsc':

```<code>../modules/node_modules/sequelize/types/lib/transaction.d.ts:33:14 - error TS1086: An accessor cannot be declared in an ambient context.

33   static get LOCK(): LOCK;
                ~~~~

../modules/node_modules/sequelize/types/lib/transaction.d.ts:40:7 - error TS1086: An accessor cannot be declared in an ambient context.

40   get LOCK(): LOCK;
         ~~~~
</code>```

My versions are:

"@types/sequelize": "^4.28.6"

"sequelize": "^5.8.10"

"sequelize-typescript": "1.0.0-beta.4"

The project works fine with nodemon but fails when I try to compile the typescript. Anyone knows this error?

Thanks.

答:
I have Angular 8. it is working with typescript version of 3.4.5. so solve this issue do below steps.

step 1) go to the tsconfig.json file

step 2) add skipLibCheck: true in "compilerOptions" object. It works for me.

```<code>"compilerOptions": {
    "module": "commonjs",
    "moduleResolution": "node",
    "strict": true,
    "target": "es5",
    "declaration": true,
    "declarationDir": "dist-debug/",
    "skipLibCheck": true, /// Needs to be true to fix wrong alias types being used

  },
</code>```

Body:
I have a project that shows this error when I run 'tsc':

../modules/node_modules/sequelize/types/lib/transaction.d.ts:33:14 - error TS1086: An accessor cannot be declared in an ambient context.

33   static get LOCK(): LOCK;
                ~~~~

../modules/node_modules/sequelize/types/lib/transaction.d.ts:40:7 - error TS1086: An accessor cannot be declared in an ambient context.

40   get LOCK(): LOCK;
         ~~~~

My versions are:

"@types/sequelize": "^4.28.6"

"sequelize": "^5.8.10"

"sequelize-typescript": "1.0.0-beta.4"

The project works fine with nodemon but fails when I try to compile the typescript. Anyone knows this error?

Thanks.

Body:
I have Angular 8. it is working with typescript version of 3.4.5. so solve this issue do below steps.

step 1) go to the tsconfig.json file

step 2) add skipLibCheck: true in "compilerOptions" object. It works for me.

"compilerOptions": {
    "module": "commonjs",
    "moduleResolution": "node",
    "strict": true,
    "target": "es5",
    "declaration": true,
    "declarationDir": "dist-debug/",
    "skipLibCheck": true, /// Needs to be true to fix wrong alias types being used

  },


问:
How to use grep function to separate multiple column with common name in R?
For the following data set, I would like to separate columns with beta1 only.

```<code>mydata
         beta1_C1 beta2_C2 beta1_C2 beta2_C1 beta3_C1 beta4_C2 beta4_C1 beta21_C1 beta21_C2 beta10_C1
    [1,]        1        9       17       25       33       41       49        57        65        73
    [2,]        2       10       18       26       34       42       50        58        66        74
    [3,]        3       11       19       27       35       43       51        59        67        75
    [4,]        4       12       20       28       36       44       52        60        68        76
    [5,]        5       13       21       29       37       45       53        61        69        77
    [6,]        6       14       22       30       38       46       54        62        70        78
    [7,]        7       15       23       31       39       47       55        63        71        79
    [8,]        8       16       24       32       40       48       56        64        72        80
</code>```

I am using the following code but beta10 is showing in the output which I do not want. In my expected data, I should have only beta1_C1 and beta1_C2 columns.

```<code> dat1=mydata[,grep("beta1",colnames(mydata))]
 dat1
         beta1_C1 beta1_C2 beta10_C1
    [1,]        1       17        73
    [2,]        2       18        74
    [3,]        3       19        75
    [4,]        4       20        76
    [5,]        5       21        77
    [6,]        6       22        78
    [7,]        7       23        79
    [8,]        8       24        80
</code>```

Any help is appreciated.

答:
If you just add underscore (_) in your current pattern, it will solve the issue for the data shared.

```<code>mydata[,grep("beta1_",colnames(mydata))]
</code>```

However, to be more specific you can do

```<code>mydata[,grep("^beta1_C\\d+",colnames(mydata))]
</code>```

This will select columns which start with "beta1_C" followed by a number.

Body:
For the following data set, I would like to separate columns with beta1 only.

mydata
         beta1_C1 beta2_C2 beta1_C2 beta2_C1 beta3_C1 beta4_C2 beta4_C1 beta21_C1 beta21_C2 beta10_C1
    [1,]        1        9       17       25       33       41       49        57        65        73
    [2,]        2       10       18       26       34       42       50        58        66        74
    [3,]        3       11       19       27       35       43       51        59        67        75
    [4,]        4       12       20       28       36       44       52        60        68        76
    [5,]        5       13       21       29       37       45       53        61        69        77
    [6,]        6       14       22       30       38       46       54        62        70        78
    [7,]        7       15       23       31       39       47       55        63        71        79
    [8,]        8       16       24       32       40       48       56        64        72        80

I am using the following code but beta10 is showing in the output which I do not want. In my expected data, I should have only beta1_C1 and beta1_C2 columns.

 dat1=mydata[,grep("beta1",colnames(mydata))]
 dat1
         beta1_C1 beta1_C2 beta10_C1
    [1,]        1       17        73
    [2,]        2       18        74
    [3,]        3       19        75
    [4,]        4       20        76
    [5,]        5       21        77
    [6,]        6       22        78
    [7,]        7       23        79
    [8,]        8       24        80

Any help is appreciated.

Body:
If you just add underscore (_) in your current pattern, it will solve the issue for the data shared.

mydata[,grep("beta1_",colnames(mydata))]

However, to be more specific you can do

mydata[,grep("^beta1_C\\d+",colnames(mydata))]

This will select columns which start with "beta1_C" followed by a number.


问:
Setting Environment variables for using Windows MAVEN for ANdroid
I want to use maven for Android. what Environment Variables should i set, such mvn command work. First i setted JAVA_HOME to jdk folder and ANDROID_HOME to ANdroid-sdk folder using set command.

but still mvn command  not working.

答:
Perhaps you have not updated PATH variable with the location of mvn.bat.

For example

```<code>set PATH=%PATH%;C:\apache-maven-3.0.3\bin
</code>```

Body:
Perhaps you have not updated PATH variable with the location of mvn.bat.

For example

set PATH=%PATH%;C:\apache-maven-3.0.3\bin


问:
error linking uWSGI
i'm trying to compile uwsgi from pip on rhel6, but i get a linking error: can someone help please?</p>

```<code>$ sudo /usr/bin/pip  install uwsgi
...
*** uWSGI linking ***

gcc -pthread -o /usr/bin/uwsgi -L/usr/lib64 core/utils.o core/protocol.o core/socket.o core/logging.o core/master.o core/master_utils.o core/emperor.o core/notify.o core/mule.o core/subscription.o core/stats.o core/sendfile.o core/async.o core/master_checks.o core/fifo.o core/offload.o core/io.o core/static.o core/websockets.o core/spooler.o core/snmp.o core/exceptions.o core/config.o core/setup_utils.o core/clock.o core/init.o core/buffer.o core/reader.o core/writer.o core/alarm.o core/cron.o core/hooks.o core/plugins.o core/lock.o core/cache.o core/daemons.o core/errors.o core/hash.o core/master_events.o core/chunked.o core/queue.o core/event.o core/signal.o core/strings.o core/progress.o core/timebomb.o core/ini.o core/fsmon.o core/mount.o core/metrics.o/usr/bin/ld: skipping incompatible /usr/lib/gcc/x86_64-redhat-linux/4.4.7/../../../libz.so when searching for -lz

/usr/bin/ld: skipping incompatible /usr/lib/libz.so when searching for -lz

/usr/bin/ld: cannot find -lz

collect2: ld returned 1 exit status

 core/plugins_builder.o core/sharedarea.o core/rpc.o core/gateway.o core/loop.o core/cookie.o core/querystring.o core/rb_timers.o core/transformations.o core/uwsgi.o proto/base.o proto/uwsgi.o proto/http.o proto/fastcgi.o proto/scgi.o proto/puwsgi.o lib/linux_ns.o core/zlib.o core/yaml.o core/dot_h.o core/config_py.o plugins/python/python_plugin.o plugins/python/pyutils.o plugins/python/pyloader.o plugins/python/wsgi_handlers.o plugins/python/wsgi_headers.o plugins/python/wsgi_subhandler.o plugins/python/web3_subhandler.o plugins/python/pump_subhandler.o plugins/python/gil.o plugins/python/uwsgi_pymodule.o plugins/python/profiler.o plugins/python/symimporter.o plugins/python/tracebacker.o plugins/python/raw.o plugins/gevent/gevent.o plugins/gevent/hooks.o plugins/ping/ping_plugin.o plugins/cache/cache.o plugins/nagios/nagios.o plugins/rrdtool/rrdtool.o plugins/carbon/carbon.o plugins/rpc/rpc_plugin.o plugins/corerouter/cr_common.o plugins/corerouter/cr_map.o plugins/corerouter/corerouter.o plugins/fastrouter/fastrouter.o plugins/http/http.o plugins/http/keepalive.o plugins/http/https.o plugins/http/spdy3.o plugins/ugreen/ugreen.o plugins/signal/signal_plugin.o plugins/syslog/syslog_plugin.o plugins/rsyslog/rsyslog_plugin.o plugins/logsocket/logsocket_plugin.o plugins/router_uwsgi/router_uwsgi.o plugins/router_redirect/router_redirect.o plugins/router_basicauth/router_basicauth.o plugins/zergpool/zergpool.o plugins/redislog/redislog_plugin.o plugins/mongodblog/mongodblog_plugin.o plugins/router_rewrite/router_rewrite.o plugins/router_http/router_http.o plugins/logfile/logfile.o plugins/router_cache/router_cache.o plugins/rawrouter/rawrouter.o plugins/router_static/router_static.o plugins/sslrouter/sslrouter.o plugins/spooler/spooler_plugin.o plugins/cheaper_busyness/cheaper_busyness.o plugins/symcall/symcall_plugin.o plugins/transformation_tofile/tofile.o plugins/transformation_gzip/gzip.o plugins/transformation_chunked/chunked.o plugins/transformation_offload/offload.o plugins/router_memcached/router_memcached.o plugins/router_redis/router_redis.o plugins/router_hash/router_hash.o plugins/router_expires/expires.o plugins/router_metrics/plugin.o plugins/transformation_template/tt.o plugins/stats_pusher_socket/plugin.o -lpthread -lm -rdynamic -ldl -lz -lpthread -ldl -lutil -lm -lpython2.6 -lcrypt

*** error linking uWSGI ***
</code>```

答:
A big red error warning, the main error content is:

```<code>error: lto-wrapper failed

collect2: error: ld returned 1 exit status
</code>```

The reason behind it is that the version of gcc is high. Here is the fix:

```<code>ls /usr/bin/gcc* -l

sudo apt-get  install gcc-4.8

sudo rm /usr/bin/gcc

sudo ln -s /usr/bin/gcc-4.8 /usr/bin/gcc
</code>```

Hope this helps!

Title: error linking uWSGI

Body:
i'm trying to compile uwsgi from pip on rhel6, but i get a linking error: can someone help please?

$ sudo /usr/bin/pip  install uwsgi
...
*** uWSGI linking ***

gcc -pthread -o /usr/bin/uwsgi -L/usr/lib64 core/utils.o core/protocol.o core/socket.o core/logging.o core/master.o core/master_utils.o core/emperor.o core/notify.o core/mule.o core/subscription.o core/stats.o core/sendfile.o core/async.o core/master_checks.o core/fifo.o core/offload.o core/io.o core/static.o core/websockets.o core/spooler.o core/snmp.o core/exceptions.o core/config.o core/setup_utils.o core/clock.o core/init.o core/buffer.o core/reader.o core/writer.o core/alarm.o core/cron.o core/hooks.o core/plugins.o core/lock.o core/cache.o core/daemons.o core/errors.o core/hash.o core/master_events.o core/chunked.o core/queue.o core/event.o core/signal.o core/strings.o core/progress.o core/timebomb.o core/ini.o core/fsmon.o core/mount.o core/metrics.o/usr/bin/ld: skipping incompatible /usr/lib/gcc/x86_64-redhat-linux/4.4.7/../../../libz.so when searching for -lz

/usr/bin/ld: skipping incompatible /usr/lib/libz.so when searching for -lz

/usr/bin/ld: cannot find -lz

collect2: ld returned 1 exit status

 core/plugins_builder.o core/sharedarea.o core/rpc.o core/gateway.o core/loop.o core/cookie.o core/querystring.o core/rb_timers.o core/transformations.o core/uwsgi.o proto/base.o proto/uwsgi.o proto/http.o proto/fastcgi.o proto/scgi.o proto/puwsgi.o lib/linux_ns.o core/zlib.o core/yaml.o core/dot_h.o core/config_py.o plugins/python/python_plugin.o plugins/python/pyutils.o plugins/python/pyloader.o plugins/python/wsgi_handlers.o plugins/python/wsgi_headers.o plugins/python/wsgi_subhandler.o plugins/python/web3_subhandler.o plugins/python/pump_subhandler.o plugins/python/gil.o plugins/python/uwsgi_pymodule.o plugins/python/profiler.o plugins/python/symimporter.o plugins/python/tracebacker.o plugins/python/raw.o plugins/gevent/gevent.o plugins/gevent/hooks.o plugins/ping/ping_plugin.o plugins/cache/cache.o plugins/nagios/nagios.o plugins/rrdtool/rrdtool.o plugins/carbon/carbon.o plugins/rpc/rpc_plugin.o plugins/corerouter/cr_common.o plugins/corerouter/cr_map.o plugins/corerouter/corerouter.o plugins/fastrouter/fastrouter.o plugins/http/http.o plugins/http/keepalive.o plugins/http/https.o plugins/http/spdy3.o plugins/ugreen/ugreen.o plugins/signal/signal_plugin.o plugins/syslog/syslog_plugin.o plugins/rsyslog/rsyslog_plugin.o plugins/logsocket/logsocket_plugin.o plugins/router_uwsgi/router_uwsgi.o plugins/router_redirect/router_redirect.o plugins/router_basicauth/router_basicauth.o plugins/zergpool/zergpool.o plugins/redislog/redislog_plugin.o plugins/mongodblog/mongodblog_plugin.o plugins/router_rewrite/router_rewrite.o plugins/router_http/router_http.o plugins/logfile/logfile.o plugins/router_cache/router_cache.o plugins/rawrouter/rawrouter.o plugins/router_static/router_static.o plugins/sslrouter/sslrouter.o plugins/spooler/spooler_plugin.o plugins/cheaper_busyness/cheaper_busyness.o plugins/symcall/symcall_plugin.o plugins/transformation_tofile/tofile.o plugins/transformation_gzip/gzip.o plugins/transformation_chunked/chunked.o plugins/transformation_offload/offload.o plugins/router_memcached/router_memcached.o plugins/router_redis/router_redis.o plugins/router_hash/router_hash.o plugins/router_expires/expires.o plugins/router_metrics/plugin.o plugins/transformation_template/tt.o plugins/stats_pusher_socket/plugin.o -lpthread -lm -rdynamic -ldl -lz -lpthread -ldl -lutil -lm -lpython2.6 -lcrypt

*** error linking uWSGI ***

Body:
A big red error warning, the main error content is:

error: lto-wrapper failed

collect2: error: ld returned 1 exit status

The reason behind it is that the version of gcc is high. Here is the fix:

ls /usr/bin/gcc* -l

sudo apt-get  install gcc-4.8

sudo rm /usr/bin/gcc

sudo ln -s /usr/bin/gcc-4.8 /usr/bin/gcc

Hope this helps!


问:
Azure function app ETIMEDOUT error works sometimes but not others
I have the below code:

```<code>var request = require('request');
var rp = require('request-promise');
module.exports = async function(context, req) {
    var arr = [[url1],[url2]]
    for (i = 0; i < arr.length; i++) {
        func(context, arr[i]);
    }
}
function func(context, urls) {
    const promises = urls.map(item => {
        return rp({
            uri: item,
            simple: false,
            resolveWithFullResponse: true
        }).then(response => {
            if (response.statusCode == 403) {

                var msg = "hello";
                return msg;
            } else {
                return null;
            }
        });
    });

    return Promise.all(promises).then(data => {
        // remove null results from array
        return data.filter(item => item !== null);
    });
}
</code>```

And I keep getting this error. Sometimes it works, sometimes it doesn't. How can I fix this, and why does it work sometimes and sometimes not.

```<code>Result: Failure
Exception: RequestError: Error: connect ETIMEDOUT
</code>```

Do I need to inclue a pool option? Or perhaps a timeout? The error seems to be due to the size of arr.

答:
This is an issue on the network level and has most likely to do with your proxy configuration. And also you may get this error when requesting to a server using https (port 443) that didn't have a valid certificate. So, using the the following configuration could solve your problem.

```<code>return rp({
       uri: item,
       simple: false,
       resolveWithFullResponse: true,
       proxy: 'http://<your.proxy.info>:8080',
       strictSSL :false
})
</code>```

Update:

No proxy, no streaming, just single request which starts several async request, setting this options:

```<code>agent: false, pool: {maxSockets: 8}
</code>```

Body:
I have the below code:

var request = require('request');
var rp = require('request-promise');
module.exports = async function(context, req) {
    var arr = [[url1],[url2]]
    for (i = 0; i < arr.length; i++) {
        func(context, arr[i]);
    }
}
function func(context, urls) {
    const promises = urls.map(item => {
        return rp({
            uri: item,
            simple: false,
            resolveWithFullResponse: true
        }).then(response => {
            if (response.statusCode == 403) {

                var msg = "hello";
                return msg;
            } else {
                return null;
            }
        });
    });

    return Promise.all(promises).then(data => {
        // remove null results from array
        return data.filter(item => item !== null);
    });
}

And I keep getting this error. Sometimes it works, sometimes it doesn't. How can I fix this, and why does it work sometimes and sometimes not.

Result: Failure
Exception: RequestError: Error: connect ETIMEDOUT

Do I need to inclue a pool option? Or perhaps a timeout? The error seems to be due to the size of arr.

Body:
This is an issue on the network level and has most likely to do with your proxy configuration. And also you may get this error when requesting to a server using https (port 443) that didn't have a valid certificate. So, using the the following configuration could solve your problem.

return rp({
       uri: item,
       simple: false,
       resolveWithFullResponse: true,
       proxy: 'http://<your.proxy.info>:8080',
       strictSSL :false
})

Update:

No proxy, no streaming, just single request which starts several async request, setting this options:

agent: false, pool: {maxSockets: 8}


问:
Mysql query returns duplicate rows when joining tables
I have a table that stores user_avatar filepath :

```<code>id | userid | file         | last_update |
1  | 23     | myphoto.png  | x_timestamp |
2  | 23     | myphoto2.png | x_timestamp |
3  | 25     | myavatar.png | x_timestamp |
</code>```

I have a table that returns user_score :

```<code>id | gamerid | score | last_update |
1  | 23      | 44    | x_timestamp |
2  | 25      | 99    | x_timestamp |
</code>```

This is the query I use to display user scores with their avatar

```<code>SELECT * FROM user_score us LEFT JOIN user_avatar ua ON us.gamerid=ua.userid
</code>```

Above query will return 2 duplicate rows for user 23 because he as downloaded 2 different photos in the user_avatar table. Right now it outputs like this:

```<code>GAMER SCORES RESULTS
myphoto.png  | 44
myphoto2.png | 44
myavatar.png | 99
</code>```

In reality, only one row should be returned for each user and the last avatar downloaded should be used as primary avatar. How can I fix this?

答:
You can try below -</p>

```<code>SELECT * FROM user_score us LEFT JOIN user_avatar ua ON us.gamerid=ua.userid
and ua.last_update =
   (select max(last_update) from user_avatar ua1 where ua.userid=ua1.userid)
</code>```

Body:
I have a table that stores user_avatar filepath :

id | userid | file         | last_update |
1  | 23     | myphoto.png  | x_timestamp |
2  | 23     | myphoto2.png | x_timestamp |
3  | 25     | myavatar.png | x_timestamp |

I have a table that returns user_score :

id | gamerid | score | last_update |
1  | 23      | 44    | x_timestamp |
2  | 25      | 99    | x_timestamp |

This is the query I use to display user scores with their avatar

SELECT * FROM user_score us LEFT JOIN user_avatar ua ON us.gamerid=ua.userid

Above query will return 2 duplicate rows for user 23 because he as downloaded 2 different photos in the user_avatar table. Right now it outputs like this:

GAMER SCORES RESULTS
myphoto.png  | 44
myphoto2.png | 44
myavatar.png | 99

In reality, only one row should be returned for each user and the last avatar downloaded should be used as primary avatar. How can I fix this?

Body:
You can try below -

SELECT * FROM user_score us LEFT JOIN user_avatar ua ON us.gamerid=ua.userid
and ua.last_update =
   (select max(last_update) from user_avatar ua1 where ua.userid=ua1.userid)


问:
Why use different type and constructor when instantiating a class?
Suppose we have a class ProductA that inherited another class called Product. What's the meaning of

```<code>Product product = new ProductA();
</code>```

And what's the difference between that and

```<code>ProductA product = new ProductA();
</code>```

答:
When initializing, no difference. It is just like saying "ProductA is a Product type of thing".

In object-oriented programming, the concept of IS-A is a based on Inheritance, which can be of two types Class Inheritance or Interface Inheritance.

Then under what circumstances can these two syntaxes have a
  difference?

Why to use Polymorphism?

Why and when use polymorphism?

Additional reading : The difference between virtual, override, new and sealed override

Body:
Suppose we have a class ProductA that inherited another class called Product. What's the meaning of

Product product = new ProductA();

And what's the difference between that and

ProductA product = new ProductA();


问:
Create an instance, execute a long script and then kill it
I'm starting to use Google Cloud Engine, what I need to do is to use the python-api to:

Create a new instance (i'm already doing this)

Execute a python script, a very long one taking about 12 hours

Once the execution is finished, delete the instance

Now im using a startup-script, but I'm having some problems as it's not loading conda correctly, and I need to run 'conda activate'. I'm actually thinking a startup script might not be the best way...

Also, is there any way to monitor the progress of the script on the instance? I found this getSerialPort method, but seems I need to do a sort of busy-waiting calling it all the time and printing the output till it finishes.

Thanks,
Marcelo

答:
You need to enable interactive serial console access for a specific instance (there is also a project wide setting):

```<code>gcloud compute instances add-metadata instance-name \
    --metadata serial-port-enable=TRUE
</code>```

Then listen to the logging on the serial port:

```<code>gcloud compute connect-to-serial-port instance-name
</code>```

Body:
You need to enable interactive serial console access for a specific instance (there is also a project wide setting):

gcloud compute instances add-metadata instance-name \
    --metadata serial-port-enable=TRUE

Then listen to the logging on the serial port:

gcloud compute connect-to-serial-port instance-name


问:
React-Redux: Actions must be plain objects. Use custom middleware for async actions

Unhandled Rejection (Error): Actions must be plain objects. Use custom middleware for async actions.

I wanted to add comments with every posts. So when fetch posts are run I want to call fetch comment API for all post.

```<code>export function bindComments(postId) {
  return API.fetchComments(postId).then(comments => {
    return {
      type: BIND_COMMENTS,
      comments,
      postId
    }
  })
}
</code>```

答:
For future seekers who might have dropped simple details like me, in my case I just have forgotten to call my action function with parentheses.

actions.js:

```<code>export function addNewComponent() {
  return {
    type: ADD_NEW_COMPONENT,
  };
}
</code>```

myComponent.js:

```<code>import React, { useEffect } from 'react';
import { addNewComponent } from '../../redux/actions';

  useEffect(() => {
    dispatch(refreshAllComponents); // <= Here was what I've missed.
  }, []);
</code>```

I've forgotten to dispatch the action function with (). So doing this solved my issue.

```<code>  useEffect(() => {
    dispatch(refreshAllComponents());
  }, []);
</code>```

Again this might have nothing to do with OP's problem, but I hope I helps people with the same problem as mine.

Body:
Unhandled Rejection (Error): Actions must be plain objects. Use custom middleware for async actions.

I wanted to add comments with every posts. So when fetch posts are run I want to call fetch comment API for all post.

export function bindComments(postId) {
  return API.fetchComments(postId).then(comments => {
    return {
      type: BIND_COMMENTS,
      comments,
      postId
    }
  })
}

Body:
For future seekers who might have dropped simple details like me, in my case I just have forgotten to call my action function with parentheses.

actions.js:

export function addNewComponent() {
  return {
    type: ADD_NEW_COMPONENT,
  };
}

myComponent.js:

import React, { useEffect } from 'react';
import { addNewComponent } from '../../redux/actions';

  useEffect(() => {
    dispatch(refreshAllComponents); // <= Here was what I've missed.
  }, []);

I've forgotten to dispatch the action function with (). So doing this solved my issue.

  useEffect(() => {
    dispatch(refreshAllComponents());
  }, []);

Again this might have nothing to do with OP's problem, but I hope I helps people with the same problem as mine.


问:
How to handle return null with custom exception
For the below code getDriver() method is asking to return null by default. Can we handle it with a custom exception?

```<code>public AppiumDriver<WebElement> getDriver() {

    desiredCapabilities.setCapability("app", TestConstants.appPath);
    desiredCapabilities.setCapability("deviceName", TestConstants.deviceName);
    desiredCapabilities.setCapability("appPackage", TestConstants.appPackage);
    desiredCapabilities.setCapability("appActivity", TestConstants.appActivity);
    try {

        AppiumDriver<WebElement> driver = new AndroidDriver<WebElement>(new URL("http://127.0.0.1:4723/wd/hub"), desiredCapabilities);
        driver.resetApp();
        return driver;
    } catch (Exception e) {
        System.out.println("error is -  " + e.getMessage());
        e.printStackTrace();
    }
}
</code>```

答:
This method will not be compiled since there is a branch without returning expression (in catch).

To fix that you can just add return null as the last line in the catch block to meet the expectations.

Body:
For the below code getDriver() method is asking to return null by default. Can we handle it with a custom exception?

public AppiumDriver<WebElement> getDriver() {

    desiredCapabilities.setCapability("app", TestConstants.appPath);
    desiredCapabilities.setCapability("deviceName", TestConstants.deviceName);
    desiredCapabilities.setCapability("appPackage", TestConstants.appPackage);
    desiredCapabilities.setCapability("appActivity", TestConstants.appActivity);
    try {

        AppiumDriver<WebElement> driver = new AndroidDriver<WebElement>(new URL("http://127.0.0.1:4723/wd/hub"), desiredCapabilities);
        driver.resetApp();
        return driver;
    } catch (Exception e) {
        System.out.println("error is -  " + e.getMessage());
        e.printStackTrace();
    }
}


问:
Is there a board for manager to check the progress of all test plans?
When I open the dashboard, I can see the progress of test run which assigned to me. But as a test manager, I want to check the progress of all test plans which assigned to the testers. Now, I have to open each test plan to check the processing. So do TCMS have a similar function board for the manager?</p>

答:
Based on the latest comment it looks like you are looking for what we call:
Individual or team performance telemetry, see
https://kiwitcms.org/blog/kiwi-tcms-team/2019/03/03/legacy-reports-become-telemetry/

At the time of writing this is still not implemented, however it is on our backlog to do so. All of the mentioned reports in the blog post above will be implemented as part of the first batch of testing telemetry.


问:
SQLSTATE[42P01]: Undefined table: 7 ERROR: relation "categories" does not exist LINE 1: select * from "categories" ^ (SQL: select * from "categories")
I just deployed on Heroku yesterday and connected to a Postgresql db and since then I have this fun error showing up on my screen (and terminal) on Heroku:

SQLSTATE[42P01]: Undefined table: 7 ERROR: relation "categories" does not exist LINE 1: select * from "categories" ^ (SQL: select * from "categories")

In my terminal, below this error, I have an Undefined table error stating that my categories table doesn't exist. This so frustrating because it does exist and it's right there! Can someone help with this? Has anyone had a similar Issue?

Tried:

Rollback tables: heroku run php artisan migrate:rollback

migrate fresh: heroku run php artisan migrate:fresh

migrate reset: heroku run php artisan migrate:reset

The migrations run up until the stories table where the relationship is located and then stop running. Right below stories is the categories table. I don't know how much this helps in fining a solution.

stories table:

        <?php

    use Illuminate\Database\Migrations\Migration;
    use Illuminate\Database\Schema\Blueprint;
    use Illuminate\Support\Facades\Schema;

    class CreateStoriesTable extends Migration
    {
        /**
         * Run the migrations.
         *
         * @return void
         */
        public function up()
        {
            Schema::create('stories', function (Blueprint $table) {
                $table->bigIncrements('id');
                $table->string('title');
                $table->text('story');
                $table->date('published_on');
                $table->integer('count_views')->default(0);
                $table->unsignedBigInteger('user_id');
                $table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');
                $table->unsignedBigInteger("category_id");
                $table->foreign('category_id')->references('id')->on('categories')->ondDelete('cascade');
                $table->timestamps();
            });
        }

        /**
         * Reverse the migrations.
         *
         * @return void
         */
        public function down()
        {
            Schema::dropIfExists('stories');
        }
    }

```

<p>categories table: </p>

<pre class="lang-php prettyprint-override"><code>    <?php

    use Illuminate\Database\Migrations\Migration;
    use Illuminate\Database\Schema\Blueprint;
    use Illuminate\Support\Facades\Schema;

    class CreateCategoriesTable extends Migration
    {
        /**
         * Run the migrations.
         *
         * @return void
         */
        public function up()
        {
            Schema::create('categories', function (Blueprint $table) {
                $table->bigIncrements('id');
                $table->string('category');
                $table->string('title')->nullable();
                $table->string('img')->nullable();
                $table->timestamps();
            });
        }

        /**
         * Reverse the migrations.
         *
         * @return void
         */
        public function down()
        {
            Schema::dropIfExists('categories');
        }
    }
</code>```

Story model:

        <?php

    namespace App;

    use Illuminate\Database\Eloquent\Model;
    use App\Reviews;
    use App\User;
    use App\Category;
    use App\ReadingList;

    class Story extends Model
    {

        protected $guarded = [];

        public function readingList()
        {
            return $this->belongsTo(ReadingList::class);
        }

        public function category()
        {
            return $this->belongsTo(Category::class);
        }

        public function reviews() {
            return $this->hasMany(Reviews::class);
        }

        public function user() {
            return $this->belongsTo(User::class);
        }

    }
```

<p>Category model: </p>

<pre class="lang-php prettyprint-override"><code>    <?php

    namespace App;

    use Illuminate\Database\Eloquent\Model;

    use App\Story;

    class Category extends Model
    {
        protected $guarded = [];

        public function story()
        {
            return $this->hasMany(Story::class);
        }

    }

</code>```

Been fixated on this for days, maybe you guys can see something I don't. Thank you so much in advance.

答:
That's because your categories table migration runs after stories table however stories table depends on categories because of the foreign keys. What you have to do is :

Rename the categories table migration and move it to top of the stories table migration

Drop all tables in the the DB

Run your migration again

Body:
I just deployed on Heroku yesterday and connected to a Postgresql db and since then I have this fun error showing up on my screen (and terminal) on Heroku:

SQLSTATE[42P01]: Undefined table: 7 ERROR: relation "categories" does not exist LINE 1: select * from "categories" ^ (SQL: select * from "categories")

In my terminal, below this error, I have an Undefined table error stating that my categories table doesn't exist. This so frustrating because it does exist and it's right there! Can someone help with this? Has anyone had a similar Issue?

Tried:

Rollback tables: heroku run php artisan migrate:rollback

migrate fresh: heroku run php artisan migrate:fresh

migrate reset: heroku run php artisan migrate:reset

The migrations run up until the stories table where the relationship is located and then stop running. Right below stories is the categories table. I don't know how much this helps in fining a solution.

stories table:

        <?php

    use Illuminate\Database\Migrations\Migration;
    use Illuminate\Database\Schema\Blueprint;
    use Illuminate\Support\Facades\Schema;

    class CreateStoriesTable extends Migration
    {
        /**
         * Run the migrations.
         *
         * @return void
         */
        public function up()
        {
            Schema::create('stories', function (Blueprint $table) {
                $table->bigIncrements('id');
                $table->string('title');
                $table->text('story');
                $table->date('published_on');
                $table->integer('count_views')->default(0);
                $table->unsignedBigInteger('user_id');
                $table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');
                $table->unsignedBigInteger("category_id");
                $table->foreign('category_id')->references('id')->on('categories')->ondDelete('cascade');
                $table->timestamps();
            });
        }

        /**
         * Reverse the migrations.
         *
         * @return void
         */
        public function down()
        {
            Schema::dropIfExists('stories');
        }
    }

categories table:

    <?php

    use Illuminate\Database\Migrations\Migration;
    use Illuminate\Database\Schema\Blueprint;
    use Illuminate\Support\Facades\Schema;

    class CreateCategoriesTable extends Migration
    {
        /**
         * Run the migrations.
         *
         * @return void
         */
        public function up()
        {
            Schema::create('categories', function (Blueprint $table) {
                $table->bigIncrements('id');
                $table->string('category');
                $table->string('title')->nullable();
                $table->string('img')->nullable();
                $table->timestamps();
            });
        }

        /**
         * Reverse the migrations.
         *
         * @return void
         */
        public function down()
        {
            Schema::dropIfExists('categories');
        }
    }

Story model:

        <?php

    namespace App;

    use Illuminate\Database\Eloquent\Model;
    use App\Reviews;
    use App\User;
    use App\Category;
    use App\ReadingList;

    class Story extends Model
    {

        protected $guarded = [];

        public function readingList()
        {
            return $this->belongsTo(ReadingList::class);
        }

        public function category()
        {
            return $this->belongsTo(Category::class);
        }

        public function reviews() {
            return $this->hasMany(Reviews::class);
        }

        public function user() {
            return $this->belongsTo(User::class);
        }

    }

Category model:

    <?php

    namespace App;

    use Illuminate\Database\Eloquent\Model;

    use App\Story;

    class Category extends Model
    {
        protected $guarded = [];

        public function story()
        {
            return $this->hasMany(Story::class);
        }

    }

Been fixated on this for days, maybe you guys can see something I don't. Thank you so much in advance.


问:
Implementation of discardable events in Java?
I would like to know are there something already available in Java, which will allow me to

submit an action

if action doesn't match the constraint, then discard the action

otherwise execute the action

constraint might be: "if the action with the same arguments was executed more than 5 seconds ago", and action itself "log the message to file" or "send message to the JMS queue"

It's easy to implement the solution, but I don't want to reinvent the wheel :)

答: I'm not sure that I fully understand where you are going to use it, or how you are going to use it. But parts of it can be done with Apache Camel. </p>


问:
415 Error On Ajax jQuery Call - Spring MVC Controller
I am facing 415-Unsupported Media Type error on the ajax call.

I tried proposed solutions on Stackoverflow for similar questions, like adding a header to ajax call or passing dataType as json, but still the same response.

Following is my code, please guide me if I am missing anything:

AJAX jQuery:

```<code>var contentTypeJSON = "application/json; charset=utf-8";

var selectedFolderShareOrgs = [];
 $.each($("input[name='shareFolderOrg']:checked"), function(){
     var sharedOrgObj = new Object();
     sharedOrgObj.org = new Object();
     sharedOrgObj.org.id = $(this).val()
     selectedFolderShareOrgs.push(sharedOrgObj);
 });

var folderToCreate = new Object();
folderToCreate.shared = new Object();
folderToCreate.shared.name = folderName;
folderToCreate.parentId = parentFolderId;
folderToCreate.validUntil = null== folderValidUntilVal ? null : new Date(folderValidUntilVal);
folderToCreate.accessType = accessTypeVal;
folderToCreate.sharedGroupId = groupType;
folderToCreate.entityId = currentEntityId;
folderToCreate.entityType = currentEntityType;
folderToCreate.orgSharedAccess = selectedFolderShareOrgs;

// Sample JSON: "{"shared":{"name":"test folder"},"parentId":"-1","validUntil":"2020-01-31T19:59:59.000Z","accessType":"2","sharedGroupId":2,"entityId":"1","entityType":"Organization","orgSharedAccess":[]}"

$.ajax({
    type : "POST",
    url : contextPath+ "/secure/sharedFiles/createSharedFolder",
    data : JSON.stringify(folderToCreate),
    contentType : contentTypeJSON,
    success : function(data) {
        alert("uploaded!");
    },
    error : function(response, textStatus) {
        alert("error!");
    }
});

</code>```

Controller:

```<code>@RequestMapping(value="/createSharedFolder")
public @ResponseBody boolean createSharedFolder(HttpServletRequest request,Principal principal,
        HttpSession session,Locale locale,ModelAndView mav, @RequestBody SharedFile folderToCreate){
    return createFolderUtil(request, principal, session, locale,mav, folderToCreate);
}
</code>```

Java Object:

```<code>public class SharedFile implements java.io.Serializable {

    private Shared shared;
    private Documents document;
    private Chairman chairman;
    private Organization org;
    private Sector sector;
    private Division division;
    private Section section;
    private BigDecimal parentId;
    private Date validUntil;
    private BigDecimal accessType;
    private BigDecimal sharedGroupId;
    private BigDecimal entityId;
    private String entityType;
    private BigDecimal active;
    private Set<OrganizationSharedAccess> orgSharedAccess;
    private BigDecimal status;

    //getters and setters...
}
</code>```

答:
you can try this. assuming you are having a form id called 'uploadForm' and a submit button id called 'btn-save'.

```<code>     $("#btn-save").click(function(event) {
         event.preventDefault();
         var folderToCreate= new FormData($('#uploadForm')[0]);
         $.ajax({type : "POST",
                 url : contextPath+ "/secure/sharedFiles/createSharedFolder",
                 data : folderToCreate,
                 contentType : false,
                 processData : false,
                 success : function(data) {
                      alert("uploaded!");
                 },
                 error : function(response, textStatus) {
                   alert("error!");
             }
      });
</code>```

in controller:
remove @RequestBody just use SharedFile folderToCreate

Body:
I am facing 415-Unsupported Media Type error on the ajax call.

I tried proposed solutions on Stackoverflow for similar questions, like adding a header to ajax call or passing dataType as json, but still the same response.

Following is my code, please guide me if I am missing anything:

AJAX jQuery:

var contentTypeJSON = "application/json; charset=utf-8";

var selectedFolderShareOrgs = [];
 $.each($("input[name='shareFolderOrg']:checked"), function(){
     var sharedOrgObj = new Object();
     sharedOrgObj.org = new Object();
     sharedOrgObj.org.id = $(this).val()
     selectedFolderShareOrgs.push(sharedOrgObj);
 });

var folderToCreate = new Object();
folderToCreate.shared = new Object();
folderToCreate.shared.name = folderName;
folderToCreate.parentId = parentFolderId;
folderToCreate.validUntil = null== folderValidUntilVal ? null : new Date(folderValidUntilVal);
folderToCreate.accessType = accessTypeVal;
folderToCreate.sharedGroupId = groupType;
folderToCreate.entityId = currentEntityId;
folderToCreate.entityType = currentEntityType;
folderToCreate.orgSharedAccess = selectedFolderShareOrgs;

// Sample JSON: "{"shared":{"name":"test folder"},"parentId":"-1","validUntil":"2020-01-31T19:59:59.000Z","accessType":"2","sharedGroupId":2,"entityId":"1","entityType":"Organization","orgSharedAccess":[]}"

$.ajax({
    type : "POST",
    url : contextPath+ "/secure/sharedFiles/createSharedFolder",
    data : JSON.stringify(folderToCreate),
    contentType : contentTypeJSON,
    success : function(data) {
        alert("uploaded!");
    },
    error : function(response, textStatus) {
        alert("error!");
    }
});

Controller:

@RequestMapping(value="/createSharedFolder")
public @ResponseBody boolean createSharedFolder(HttpServletRequest request,Principal principal,
        HttpSession session,Locale locale,ModelAndView mav, @RequestBody SharedFile folderToCreate){
    return createFolderUtil(request, principal, session, locale,mav, folderToCreate);
}

Java Object:

public class SharedFile implements java.io.Serializable {

    private Shared shared;
    private Documents document;
    private Chairman chairman;
    private Organization org;
    private Sector sector;
    private Division division;
    private Section section;
    private BigDecimal parentId;
    private Date validUntil;
    private BigDecimal accessType;
    private BigDecimal sharedGroupId;
    private BigDecimal entityId;
    private String entityType;
    private BigDecimal active;
    private Set<OrganizationSharedAccess> orgSharedAccess;
    private BigDecimal status;

    //getters and setters...
}

Body:
you can try this. assuming you are having a form id called 'uploadForm' and a submit button id called 'btn-save'.

     $("#btn-save").click(function(event) {
         event.preventDefault();
         var folderToCreate= new FormData($('#uploadForm')[0]);
         $.ajax({type : "POST",
                 url : contextPath+ "/secure/sharedFiles/createSharedFolder",
                 data : folderToCreate,
                 contentType : false,
                 processData : false,
                 success : function(data) {
                      alert("uploaded!");
                 },
                 error : function(response, textStatus) {
                   alert("error!");
             }
      });

in controller:
remove @RequestBody just use SharedFile folderToCreate