问:
Value cannot be null when deserializing JSON
I have a db table which has column in which content is stored in JSON format, I am retrieving JSON but I am getting this error.

Value cannot be null

Here is my code snippet.

```<code>var stuff = (JObject)JsonConvert.DeserializeObject(commentId);

string name = stuff["Name"].Value<string>();
string email = stuff["Email"].Value<string>();
string company = stuff["Company"].Value<string>();
string phone = stuff["Phone"].Value<string>();
string message = stuff["Message"].Value<string>();
string emails = stuff["Emails"].Value<string>();
</code>```

My sample JSON:

```<code>{
  "2": {
    "label": "",
    "value": "",
    "type": null,
    "validation": null,
    "required": null,
    "min": null,
    "max": null,
    "tooltip": null,
    "custom": null,
    "custom2": null,
    "custom3": "zz",
    "custom4": null,
    "custom5": null
  },
  "3": {
    "label": "location",
    "value": "http://someurl.com/",
    "type": "hidden",
    "validation": "",
    "required": "0",
    "min": "0",
    "max": "1000",
    "tooltip": "",
    "custom": null,
    "custom2": null,
    "custom3": "zz",
    "custom4": null,
    "custom5": null
  },
  "4": {
    "label": "Name*",
    "value": "Farrukh",
    "type": "text",
    "validation": "alphabets",
    "required": "1",
    "min": "0",
    "max": "300",
    "tooltip": "field0",
    "custom": "",
    "custom2": null,
    "custom3": "zz",
    "custom4": null,
    "custom5": null
  },
  "5": {
    "label": "Email*",
    "value": "abc@a.com",
    "type": "email",
    "validation": "email",
    "required": "1",
    "min": "",
    "max": "",
    "tooltip": "field1",
    "custom": "autoreply",
    "custom2": "replyto",
    "custom3": "zz",
    "custom4": "",
    "custom5": ""
  },
  "6": {
    "label": "Company",
    "value": "Abc",
    "type": "text",
    "validation": "",
    "required": "1",
    "min": "0",
    "max": "300",
    "tooltip": "field2",
    "custom": "",
    "custom2": null,
    "custom3": "zz",
    "custom4": null,
    "custom5": null
  },
  "7": {
    "label": "Phone",
    "value": "0000000000",
    "type": "text",
    "validation": "integers",
    "required": "0",
    "min": "0",
    "max": "300",
    "tooltip": "field3",
    "custom": "",
    "custom2": null,
    "custom3": "zz",
    "custom4": null,
    "custom5": null
  },
  "8": {
    "label": "Country",
    "value": "Some country",
    "type": "dropdown",
    "validation": "",
    "required": "1",
    "min": "",
    "max": "",
    "tooltip": "field4",
    "custom": null,
    "custom2": null,
    "custom3": "zz",
    "custom4": null,
    "custom5": null
  },
  "9": {
    "label": "Message*",
    "value": "hello",
    "type": "para",
    "validation": "",
    "required": "1",
    "min": "0",
    "max": "3000",
    "tooltip": "field5",
    "custom": "",
    "custom2": null,
    "custom3": "zz",
    "custom4": null,
    "custom5": null
  },
  "10": {
    "label": "name",
    "value": "",
    "type": null,
    "validation": null,
    "required": null,
    "min": null,
    "max": null,
    "tooltip": null,
    "custom": null,
    "custom2": null,
    "custom3": "zz",
    "custom4": null,
    "custom5": null
  },
  "11": {
    "label": "title",
    "value": "",
    "type": null,
    "validation": null,
    "required": null,
    "min": null,
    "max": null,
    "tooltip": null,
    "custom": null,
    "custom2": null,
    "custom3": "zz",
    "custom4": null,
    "custom5": null
  },
  "12": {
    "label": "emails",
    "value": ",a@a.com,b@b.com,c@c.com,d@d.com",
    "type": null,
    "validation": null,
    "required": null,
    "min": null,
    "max": null,
    "tooltip": null,
    "custom": null,
    "custom2": null,
    "custom3": "zz",
    "custom4": null,
    "custom5": null
  },
  "13": {
    "label": "multi",
    "value": "true",
    "type": null,
    "validation": null,
    "required": null,
    "min": null,
    "max": null,
    "tooltip": null,
    "custom": null,
    "custom2": null,
    "custom3": "zz",
    "custom4": null,
    "custom5": null
  },
  "0": {
    "custom3": "zz",
    "value": "",
    "label": ""
  },
  "1": {
    "custom3": "zz",
    "value": "",
    "label": ""
  }
}
</code>```

答:
Pretty old topic, but I am using:

string name = stuff["Name"]?.Value<string>() ?? "undefined";
string email = stuff["Email"]?.Value<string>() ?? "undefined";

Concise and simple and also provides your own default value.

Body:
I have a db table which has column in which content is stored in JSON format, I am retrieving JSON but I am getting this error.

Value cannot be null

Here is my code snippet.

var stuff = (JObject)JsonConvert.DeserializeObject(commentId);

string name = stuff["Name"].Value<string>();
string email = stuff["Email"].Value<string>();
string company = stuff["Company"].Value<string>();
string phone = stuff["Phone"].Value<string>();
string message = stuff["Message"].Value<string>();
string emails = stuff["Emails"].Value<string>();

My sample JSON:

{
  "2": {
    "label": "",
    "value": "",
    "type": null,
    "validation": null,
    "required": null,
    "min": null,
    "max": null,
    "tooltip": null,
    "custom": null,
    "custom2": null,
    "custom3": "zz",
    "custom4": null,
    "custom5": null
  },
  "3": {
    "label": "location",
    "value": "http://someurl.com/",
    "type": "hidden",
    "validation": "",
    "required": "0",
    "min": "0",
    "max": "1000",
    "tooltip": "",
    "custom": null,
    "custom2": null,
    "custom3": "zz",
    "custom4": null,
    "custom5": null
  },
  "4": {
    "label": "Name*",
    "value": "Farrukh",
    "type": "text",
    "validation": "alphabets",
    "required": "1",
    "min": "0",
    "max": "300",
    "tooltip": "field0",
    "custom": "",
    "custom2": null,
    "custom3": "zz",
    "custom4": null,
    "custom5": null
  },
  "5": {
    "label": "Email*",
    "value": "abc@a.com",
    "type": "email",
    "validation": "email",
    "required": "1",
    "min": "",
    "max": "",
    "tooltip": "field1",
    "custom": "autoreply",
    "custom2": "replyto",
    "custom3": "zz",
    "custom4": "",
    "custom5": ""
  },
  "6": {
    "label": "Company",
    "value": "Abc",
    "type": "text",
    "validation": "",
    "required": "1",
    "min": "0",
    "max": "300",
    "tooltip": "field2",
    "custom": "",
    "custom2": null,
    "custom3": "zz",
    "custom4": null,
    "custom5": null
  },
  "7": {
    "label": "Phone",
    "value": "0000000000",
    "type": "text",
    "validation": "integers",
    "required": "0",
    "min": "0",
    "max": "300",
    "tooltip": "field3",
    "custom": "",
    "custom2": null,
    "custom3": "zz",
    "custom4": null,
    "custom5": null
  },
  "8": {
    "label": "Country",
    "value": "Some country",
    "type": "dropdown",
    "validation": "",
    "required": "1",
    "min": "",
    "max": "",
    "tooltip": "field4",
    "custom": null,
    "custom2": null,
    "custom3": "zz",
    "custom4": null,
    "custom5": null
  },
  "9": {
    "label": "Message*",
    "value": "hello",
    "type": "para",
    "validation": "",
    "required": "1",
    "min": "0",
    "max": "3000",
    "tooltip": "field5",
    "custom": "",
    "custom2": null,
    "custom3": "zz",
    "custom4": null,
    "custom5": null
  },
  "10": {
    "label": "name",
    "value": "",
    "type": null,
    "validation": null,
    "required": null,
    "min": null,
    "max": null,
    "tooltip": null,
    "custom": null,
    "custom2": null,
    "custom3": "zz",
    "custom4": null,
    "custom5": null
  },
  "11": {
    "label": "title",
    "value": "",
    "type": null,
    "validation": null,
    "required": null,
    "min": null,
    "max": null,
    "tooltip": null,
    "custom": null,
    "custom2": null,
    "custom3": "zz",
    "custom4": null,
    "custom5": null
  },
  "12": {
    "label": "emails",
    "value": ",a@a.com,b@b.com,c@c.com,d@d.com",
    "type": null,
    "validation": null,
    "required": null,
    "min": null,
    "max": null,
    "tooltip": null,
    "custom": null,
    "custom2": null,
    "custom3": "zz",
    "custom4": null,
    "custom5": null
  },
  "13": {
    "label": "multi",
    "value": "true",
    "type": null,
    "validation": null,
    "required": null,
    "min": null,
    "max": null,
    "tooltip": null,
    "custom": null,
    "custom2": null,
    "custom3": "zz",
    "custom4": null,
    "custom5": null
  },
  "0": {
    "custom3": "zz",
    "value": "",
    "label": ""
  },
  "1": {
    "custom3": "zz",
    "value": "",
    "label": ""
  }
}


来源: stackexchange

问:
Batch file that aborts action if current date is not between specific dates
I need an if else statement that aborts or continues the batch scripts.

if current date is between specified 2 dates it continues to work
if not, batch file aborts

for example i set the dates as 01.01.2019 to 01.03.2019, if the date is 15.02.2019 batch file works if 01.04.2019 it aborts

the closest answers are from here; In a batch file, how would I check if today's date is after a set date?

```<code>@ECHO OFF

SET FirstDate=2015-01-24

REM These indexes assume %DATE% is in format:
REM   Abr MM/DD/YYYY - ex. Sun 01/25/2015
SET TodayYear=%DATE:~10,4%
SET TodayMonth=%DATE:~4,2%
SET TodayDay=%DATE:~7,2%

REM Construct today's date to be in the same format as the FirstDate.
REM Since the format is a comparable string, it will evaluate date orders.
IF %TodayYear%-%TodayMonth%-%TodayDay% GTR %FirstDate% (
    ECHO Today is after the first date.
) ELSE (
    ECHO Today is on or before the first date.
)

and / or

@ECHO OFF
SETLOCAL ENABLEEXTENSIONS

REM -- 2 digit day
SET "_day=%DATE:~-10,2%" & REM day goes first (dd/mm/yyyy); if not, remove this line
SET "_day=%DATE:~-7,2%" & REM day goes second (mm/dd/yyyy); if not, remove this line
REM -- 2 digit month
SET "_month=%DATE:~-10,2%" & REM month goes first (mm/dd/yyyy); if not, remove this line
SET "_month=%DATE:~-7,2%" & REM month goes second (dd/mm/yyyy); if not, remove this line
REM -- 4 digit year
SET "_year=%DATE:~-10,4%" & REM year goes first (yyyy/##/##); if not, remove this line
SET "_year=%DATE:~-4%" & REM year goes last (##/##/yyyy); if not, remove this line

REM -- The variables below are set to year-month-day without separators (yyyymmdd)
SET "today=%_year%%_month%%_day%" & REM today's date based on your selections above
SET "compareDate=20180727" & REM the date you are comparing with today

REM -- Here's where the magic happens with comparing the two dates
IF %compareDate% LSS %today% ECHO The comparison date is in the past.
IF %compareDate% EQU %today% ECHO The comparison date is today.
IF %compareDate% GTR %today% ECHO The comparison date is in the future.
GOTO :EOF
</code>```

答:
The problem with %DATE% is that it returns the current date using the short date format, that is fully (endlessly) customizable. One user may configure its system to return Fri053119, and another user may choose 31/05/2019, which is a complete nightmare for a BAT programmer.

One possible solution is to use WMIC, the command line interface to WMI. See wikipedia's Windows Management Instrumentation.

wmic OS Get localdatetime returns the date in a convenient format to directly parse it with a FOR command.

So, for example, you could,

```<code>for /f "delims=" %%a in ('wmic OS Get localdatetime  ^| find "."') do set wldt=%%a
set today=%wldt:~0,8%
</code>```

to obtain the current date in a convenient format to use it for dates comparison

so you later can

```<code>if %today% gtr 20190101 (
  if %today% lss 20190630 (
    echo Yes!
  )
)
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I need an if else statement that aborts or continues the batch scripts.

if current date is between specified 2 dates it continues to work
if not, batch file aborts

for example i set the dates as 01.01.2019 to 01.03.2019, if the date is 15.02.2019 batch file works if 01.04.2019 it aborts

the closest answers are from here; In a batch file, how would I check if today's date is after a set date?

@ECHO OFF

SET FirstDate=2015-01-24

REM These indexes assume %DATE% is in format:
REM   Abr MM/DD/YYYY - ex. Sun 01/25/2015
SET TodayYear=%DATE:~10,4%
SET TodayMonth=%DATE:~4,2%
SET TodayDay=%DATE:~7,2%

REM Construct today's date to be in the same format as the FirstDate.
REM Since the format is a comparable string, it will evaluate date orders.
IF %TodayYear%-%TodayMonth%-%TodayDay% GTR %FirstDate% (
    ECHO Today is after the first date.
) ELSE (
    ECHO Today is on or before the first date.
)

and / or

@ECHO OFF
SETLOCAL ENABLEEXTENSIONS

REM -- 2 digit day
SET "_day=%DATE:~-10,2%" & REM day goes first (dd/mm/yyyy); if not, remove this line
SET "_day=%DATE:~-7,2%" & REM day goes second (mm/dd/yyyy); if not, remove this line
REM -- 2 digit month
SET "_month=%DATE:~-10,2%" & REM month goes first (mm/dd/yyyy); if not, remove this line
SET "_month=%DATE:~-7,2%" & REM month goes second (dd/mm/yyyy); if not, remove this line
REM -- 4 digit year
SET "_year=%DATE:~-10,4%" & REM year goes first (yyyy/##/##); if not, remove this line
SET "_year=%DATE:~-4%" & REM year goes last (##/##/yyyy); if not, remove this line

REM -- The variables below are set to year-month-day without separators (yyyymmdd)
SET "today=%_year%%_month%%_day%" & REM today's date based on your selections above
SET "compareDate=20180727" & REM the date you are comparing with today

REM -- Here's where the magic happens with comparing the two dates
IF %compareDate% LSS %today% ECHO The comparison date is in the past.
IF %compareDate% EQU %today% ECHO The comparison date is today.
IF %compareDate% GTR %today% ECHO The comparison date is in the future.
GOTO :EOF

Body:
The problem with %DATE% is that it returns the current date using the short date format, that is fully (endlessly) customizable. One user may configure its system to return Fri053119, and another user may choose 31/05/2019, which is a complete nightmare for a BAT programmer.

One possible solution is to use WMIC, the command line interface to WMI. See wikipedia's Windows Management Instrumentation.

wmic OS Get localdatetime returns the date in a convenient format to directly parse it with a FOR command.

So, for example, you could,

for /f "delims=" %%a in ('wmic OS Get localdatetime  ^| find "."') do set wldt=%%a
set today=%wldt:~0,8%

to obtain the current date in a convenient format to use it for dates comparison

so you later can

if %today% gtr 20190101 (
  if %today% lss 20190630 (
    echo Yes!
  )
)


问:
AttributeError: 'list' object has no attribute 'h3' ( Beautifulsoup )
I am a beginner in Web-scraping and I am following this tutorial ( https://www.dataquest.io/blog/web-scraping-beautifulsoup/ ) to extract movie data, I think that I have badly defined " first_movie " !

this is the code

```<code>  from requests import get
  from bs4 import BeautifulSoup

  first_movie =[]

  url = 'http://www.imdb.com/search/title?
  release_date=2017&sort=num_votes,desc&page=1'
  response = get(url)
  html_soup = BeautifulSoup(response.text, 'html.parser')
  type(html_soup)

  movie_containers = html_soup.find_all('div', class_ = 'lister-item mode-advanced')

  first_name = first_movie.h3.a.text
</code>```

I get this error :

```<code>Traceback (most recent call last):
File "mov1.py", line 13, in <module>
first_name = first_movie.h3.a.text
AttributeError: 'list' object has no attribute 'h3'
</code>```

答:
A nice short selector leveraging adjacent sibling combinator to get a tag next to class

```<code>import requests
from bs4 import BeautifulSoup as bs

r = requests.get('https://www.imdb.com/search/title?release_date=2017&sort=num_votes,desc&page=1')
soup = bs(r.content, 'lxml')
titles = [item.text for item in soup.select('.lister-item-index + a')]
print(titles)
</code>```

Body:
I am a beginner in Web-scraping and I am following this tutorial ( https://www.dataquest.io/blog/web-scraping-beautifulsoup/ ) to extract movie data, I think that I have badly defined " first_movie " !

this is the code

  from requests import get
  from bs4 import BeautifulSoup

  first_movie =[]

  url = 'http://www.imdb.com/search/title?
  release_date=2017&sort=num_votes,desc&page=1'
  response = get(url)
  html_soup = BeautifulSoup(response.text, 'html.parser')
  type(html_soup)

  movie_containers = html_soup.find_all('div', class_ = 'lister-item mode-advanced')

  first_name = first_movie.h3.a.text

I get this error :

Traceback (most recent call last):
File "mov1.py", line 13, in <module>
first_name = first_movie.h3.a.text
AttributeError: 'list' object has no attribute 'h3'

Body:
A nice short selector leveraging adjacent sibling combinator to get a tag next to class

import requests
from bs4 import BeautifulSoup as bs

r = requests.get('https://www.imdb.com/search/title?release_date=2017&sort=num_votes,desc&page=1')
soup = bs(r.content, 'lxml')
titles = [item.text for item in soup.select('.lister-item-index + a')]
print(titles)


问:
Linkify Html text with Dart
I'm trying to linkify an HTML code using Dart / Flutter and get the same result as a Javascript function I already use.

It is important to note that the received text can be a mixture of plain text and HTML.

Basically I would like to transform this:

Hello

Visit this link: http://www.link1.com

And this:
http://www.link2.com
```

<p>Into this: </p>

<pre class="lang-html prettyprint-override"><code><h1>Hello</h1>
Visit this link: http://www.link1.com<br />

And <strong>this</strong>:
http://www.link2.com
</code>```

I've tried this plugin, but it only works with plain text: https://github.com/blossom/linkify-dart

The javascript code below works exactly as expected

```<code>function linkify(text) {
        var url_pattern = /(\()((?:ht|f)tps?:\/\/[a-z0-9\-._~!$&'()*+,;=:\/?#[\]@%]+)(\))|(\[)((?:ht|f)tps?:\/\/[a-z0-9\-._~!$&'()*+,;=:\/?#[\]@%]+)(\])|(\{)((?:ht|f)tps?:\/\/[a-z0-9\-._~!$&'()*+,;=:\/?#[\]@%]+)(\})|(<|&(?:lt|#60|#x3c);)((?:ht|f)tps?:\/\/[a-z0-9\-._~!$&'()*+,;=:\/?#[\]@%]+)(>|&(?:gt|#62|#x3e);)|((?:^|[^=\s'"\]])\s*['"]?|[^=\s]\s+)(\b(?:ht|f)tps?:\/\/[a-z0-9\-._~!$'()*+,;=:\/?#[\]@%]+(?:(?!&(?:gt|#0*62|#x0*3e);|&(?:amp|apos|quot|#0*3[49]|#x0*2[27]);[.!&',:?;]?(?:[^a-z0-9\-._~!$&'()*+,;=:\/?#[\]@%]|$))&[a-z0-9\-._~!$'()*+,;=:\/?#[\]@%]*)*[a-z0-9\-_~$()*+=\/#[\]@%])/img;
        var url_replace = '$1$4$7$10$13<a href="$2$5$8$11$14" target="_blank">$2$5$8$11$14</a>$3$6$9$12';
        return text.replace(url_pattern, url_replace);
    }

    function _linkify_html_callback(m0, m1, m2) {
        if (m2) {
            return m2;
        }
        return linkify(m1);
    }

    /**
     * Original from https://github.com/jmrware/LinkifyURL
     */
    function linkifyHtm() {
        var text = this.replace(/'/g, ''');
        var section_html_pattern = /([^<]+(?:(?!<a\b)<[^<]*)*|(?:(?!<a\b)<[^<]*)+)|(<a\b[^>]*>[^<]*(?:(?!<\/a\b)<[^<]*)*<\/a\s*>)/ig;
        return text.replace(section_html_pattern, _linkify_html_callback);
    };
</code>```

答:
Here, we are having a complicated expression, which we could start with a list of constraints before and the same after the URLs, and maybe adding them in a char class. For example, we can start with an expression such as:

```<code>\s+(https?.+?)(<|\s)
</code>```

which (https?.+?) would capture our URLs, before that we add \s+ boundary for instance, then after, we would be adding (<|\s). We then would work on these two left and right boundaries for other cases that we might be having.

DEMO

Test

const regex = /\s+(https?.+?)(<|\s)/gm;
const str = `
Hello

Visit this link: http://www.link1.com

Visit this link: http://www.link1.com

Visit this link: http://www.link1.com/some_other_words

And this:
http://www.link2.com`;
const subst = ` $1$2`;

// The substituted value will be contained in the result variable
const result = str.replace(regex, subst);

console.log(result);```

RegEx

If this expression wasn't desired, it can be modified/changed in regex101.com.

RegEx Circuit

jex.im visualizes regular expressions:

Title: Linkify Html text with Dart

Body:
I'm trying to linkify an HTML code using Dart / Flutter and get the same result as a Javascript function I already use.

It is important to note that the received text can be a mixture of plain text and HTML.

Basically I would like to transform this:

Hello

Visit this link: http://www.link1.com

And this:
http://www.link2.com

Into this:

Hello

Visit this link: http://www.link1.com

And this:
http://www.link2.com

I've tried this plugin, but it only works with plain text: https://github.com/blossom/linkify-dart

The javascript code below works exactly as expected

function linkify(text) {
        var url_pattern = /(\()((?:ht|f)tps?:\/\/[a-z0-9\-._~!$&'()*+,;=:\/?#[\]@%]+)(\))|(\[)((?:ht|f)tps?:\/\/[a-z0-9\-._~!$&'()*+,;=:\/?#[\]@%]+)(\])|(\{)((?:ht|f)tps?:\/\/[a-z0-9\-._~!$&'()*+,;=:\/?#[\]@%]+)(\})|(<|&(?:lt|#60|#x3c);)((?:ht|f)tps?:\/\/[a-z0-9\-._~!$&'()*+,;=:\/?#[\]@%]+)(>|&(?:gt|#62|#x3e);)|((?:^|[^=\s'"\]])\s*['"]?|[^=\s]\s+)(\b(?:ht|f)tps?:\/\/[a-z0-9\-._~!$'()*+,;=:\/?#[\]@%]+(?:(?!&(?:gt|#0*62|#x0*3e);|&(?:amp|apos|quot|#0*3[49]|#x0*2[27]);[.!&',:?;]?(?:[^a-z0-9\-._~!$&'()*+,;=:\/?#[\]@%]|$))&[a-z0-9\-._~!$'()*+,;=:\/?#[\]@%]*)*[a-z0-9\-_~$()*+=\/#[\]@%])/img;
        var url_replace = '$1$4$7$10$13$2$5$8$11$14$3$6$9$12';
        return text.replace(url_pattern, url_replace);
    }

    function _linkify_html_callback(m0, m1, m2) {
        if (m2) {
            return m2;
        }
        return linkify(m1);
    }

    /**
     * Original from https://github.com/jmrware/LinkifyURL
     */
    function linkifyHtm() {
        var text = this.replace(/&apos;/g, ''');
        var section_html_pattern = /([^<]+(?:(?!<a\b)<[^<]*)*|(?:(?!<a\b)<[^<]*)+)|(]*>[^<]*(?:(?!<\/a\b)<[^<]*)*<\/a\s*>)/ig;
        return text.replace(section_html_pattern, _linkify_html_callback);
    };

Body:
Here, we are having a complicated expression, which we could start with a list of constraints before and the same after the URLs, and maybe adding them in a char class. For example, we can start with an expression such as:

\s+(https?.+?)(<|\s)

which (https?.+?) would capture our URLs, before that we add \s+ boundary for instance, then after, we would be adding (<|\s). We then would work on these two left and right boundaries for other cases that we might be having.

DEMO

Test

const regex = /\s+(https?.+?)(<|\s)/gm;
const str = `<h1>Hello</h1>
Visit this link: http://www.link1.com<br />
Visit this link: http://www.link1.com <br />
Visit this link: http://www.link1.com/some_other_words <br />
And <strong>this</strong>:
<a href="http://www.link2.com">http://www.link2.com</a>`;
const subst = ` <a href="$1">$1</a>$2`;

// The substituted value will be contained in the result variable
const result = str.replace(regex, subst);

console.log(result);

RegEx

If this expression wasn't desired, it can be modified/changed in regex101.com.

RegEx Circuit

jex.im visualizes regular expressions:


问:
Spring controller not working when the last PathVariable in RequestMapping has only
I am trying to map a request to Spring controller but it is not working as expected

I get 404 error when I am trying /simple/test/something/.....
and my mapping is as follows @RequestMapping(path="/simple/test/{string1}/{string2}")

Below is my code

```<code>@RequestMapping(path = "/search/test/{string1}/{string2}", produces = APPLICATION_JSON_UTF8_VALUE)
@ResponseBody
public SearchResult search( @PathVariable String string1, @PathVariable Optional string2) {
    if (!query.isPresent()) {
        return service.getLastQueries(string1, string2);
    }
}
</code>```

when the {string2} contains / or only .... then I am getting 404 error.
For example {string2} is ....... or some/thing

答:
It's not enough to make input parameter as Optional, you should also set required=false in @PathVariable annotation.

```<code>@PathVariable(required=false) Optional<String> string2
</code>```

Body:
I am trying to map a request to Spring controller but it is not working as expected

I get 404 error when I am trying /simple/test/something/.....
and my mapping is as follows @RequestMapping(path="/simple/test/{string1}/{string2}")

Below is my code

@RequestMapping(path = "/search/test/{string1}/{string2}", produces = APPLICATION_JSON_UTF8_VALUE)
@ResponseBody
public SearchResult search( @PathVariable String string1, @PathVariable Optional string2) {
    if (!query.isPresent()) {
        return service.getLastQueries(string1, string2);
    }
}

when the {string2} contains / or only .... then I am getting 404 error.
For example {string2} is ....... or some/thing

Body:
It's not enough to make input parameter as Optional, you should also set required=false in @PathVariable annotation.

@PathVariable(required=false) Optional<String> string2


问:
GCP: What is the best option to setup a periodic Data pipeline from Spanner to Big Query
Task: We have to setup a periodic sync of records from Spanner to Big Query. Our Spanner database has a relational table hierarchy.

Option Considered I was thinking of using Dataflow templates to setup this data pipeline.

Option1: Setup a job with Dataflow template 'Cloud Spanner to Cloud Storage Text' and then another with Dataflow template 'Cloud Storage
Text to BigQuery'. Con: The first template works only on a single table and we have many tables to export.

Option2: Use 'Cloud Spanner to Cloud Storage Avro' template which exports the entire database. Con: I only need to export selected tables within a database and I don't see a template to import Avro into Big Query.

Questions: Please suggest what is the best option for setting up this pipeline

答:
Use a single Dataflow pipeline to do it in one shot/pass. Here's an example I wrote using the Java SDK to help get you started. It reads from Spanner, transforms it to a BigQuery TableRow using a ParDo, and then writes to BigQuery at the end. Under the hood it's using GCS, but that's all abstracted away from you as a user.

```<code>package org.polleyg;

import com.google.api.services.bigquery.model.TableFieldSchema;
import com.google.api.services.bigquery.model.TableRow;
import com.google.api.services.bigquery.model.TableSchema;
import com.google.cloud.spanner.Struct;
import org.apache.beam.runners.dataflow.options.DataflowPipelineOptions;
import org.apache.beam.sdk.Pipeline;
import org.apache.beam.sdk.io.gcp.bigquery.BigQueryIO;
import org.apache.beam.sdk.io.gcp.spanner.SpannerIO;
import org.apache.beam.sdk.options.PipelineOptionsFactory;
import org.apache.beam.sdk.transforms.DoFn;
import org.apache.beam.sdk.transforms.ParDo;
import org.apache.beam.sdk.values.PCollection;

import java.util.ArrayList;
import java.util.List;

import static org.apache.beam.sdk.io.gcp.bigquery.BigQueryIO.Write.CreateDisposition.CREATE_IF_NEEDED;
import static org.apache.beam.sdk.io.gcp.bigquery.BigQueryIO.Write.WriteDisposition.WRITE_TRUNCATE;

/**
 * Do some randomness
 */
public class TemplatePipeline {
    public static void main(String[] args) {
        PipelineOptionsFactory.register(DataflowPipelineOptions.class);
        DataflowPipelineOptions options = PipelineOptionsFactory.fromArgs(args).withValidation().as(DataflowPipelineOptions.class);
        Pipeline pipeline = Pipeline.create(options);
        PCollection<Struct> records = pipeline.apply("read_from_spanner",
                SpannerIO.read()
                        .withInstanceId("spanner-to-dataflow-to-bq")
                        .withDatabaseId("the-dude")
                        .withQuery("SELECT * FROM Singers"));
        records.apply("convert-2-bq-row", ParDo.of(new DoFn<Struct, TableRow>() {
            @ProcessElement
            public void processElement(ProcessContext c) throws Exception {
                TableRow row = new TableRow();
                row.set("id", c.element().getLong("SingerId"));
                row.set("first", c.element().getString("FirstName"));
                row.set("last", c.element().getString("LastName"));
                c.output(row);
            }
        })).apply("write-to-bq", BigQueryIO.writeTableRows()
                .to(String.format("%s:spanner_to_bigquery.singers", options.getProject()))
                .withCreateDisposition(CREATE_IF_NEEDED)
                .withWriteDisposition(WRITE_TRUNCATE)
                .withSchema(getTableSchema()));
        pipeline.run();
    }

    private static TableSchema getTableSchema() {
        List<TableFieldSchema> fields = new ArrayList<>();
        fields.add(new TableFieldSchema().setName("id").setType("INTEGER"));
        fields.add(new TableFieldSchema().setName("first").setType("STRING"));
        fields.add(new TableFieldSchema().setName("last").setType("STRING"));
        return new TableSchema().setFields(fields);
    }
}
</code>```

Output logs:

```<code>00:10:54,011 0    [direct-runner-worker] INFO  org.apache.beam.sdk.io.gcp.bigquery.BatchLoads - Writing BigQuery temporary files to gs://spanner-dataflow-bq/tmp/BigQueryWriteTemp/beam_load_templatepipelinegrahampolley0531141053eff9d0d4_3dd2ba3a1c0347cf860241ddcd310a12/ before loading them.
00:10:59,332 5321 [direct-runner-worker] INFO  org.apache.beam.sdk.io.gcp.bigquery.TableRowWriter - Opening TableRowWriter to gs://spanner-dataflow-bq/tmp/BigQueryWriteTemp/beam_load_templatepipelinegrahampolley0531141053eff9d0d4_3dd2ba3a1c0347cf860241ddcd310a12/c374d44a-a7db-407e-aaa4-fe6aa5f6a9ef.
00:11:01,178 7167 [direct-runner-worker] INFO  org.apache.beam.sdk.io.gcp.bigquery.WriteTables - Loading 1 files into {datasetId=spanner_to_bigquery, projectId=grey-sort-challenge, tableId=singers} using job {jobId=beam_load_templatepipelinegrahampolley0531141053eff9d0d4_3dd2ba3a1c0347cf860241ddcd310a12_b4b4722df4326c6f5a93d7824981dc73_00001_00000-0, location=australia-southeast1, projectId=grey-sort-challenge}, attempt 0
00:11:02,495 8484 [direct-runner-worker] INFO  org.apache.beam.sdk.io.gcp.bigquery.BigQueryServicesImpl - Started BigQuery job: {jobId=beam_load_templatepipelinegrahampolley0531141053eff9d0d4_3dd2ba3a1c0347cf860241ddcd310a12_b4b4722df4326c6f5a93d7824981dc73_00001_00000-0, location=australia-southeast1, projectId=grey-sort-challenge}.
bq show -j --format=prettyjson --project_id=grey-sort-challenge beam_load_templatepipelinegrahampolley0531141053eff9d0d4_3dd2ba3a1c0347cf860241ddcd310a12_b4b4722df4326c6f5a93d7824981dc73_00001_00000-0
00:11:02,495 8484 [direct-runner-worker] INFO  org.apache.beam.sdk.io.gcp.bigquery.WriteTables - Load job {jobId=beam_load_templatepipelinegrahampolley0531141053eff9d0d4_3dd2ba3a1c0347cf860241ddcd310a12_b4b4722df4326c6f5a93d7824981dc73_00001_00000-0, location=australia-southeast1, projectId=grey-sort-challenge} started
00:11:03,183 9172 [direct-runner-worker] INFO  org.apache.beam.sdk.io.gcp.bigquery.BigQueryServicesImpl - Still waiting for BigQuery job beam_load_templatepipelinegrahampolley0531141053eff9d0d4_3dd2ba3a1c0347cf860241ddcd310a12_b4b4722df4326c6f5a93d7824981dc73_00001_00000-0, currently in status {"state":"RUNNING"}
bq show -j --format=prettyjson --project_id=grey-sort-challenge beam_load_templatepipelinegrahampolley0531141053eff9d0d4_3dd2ba3a1c0347cf860241ddcd310a12_b4b4722df4326c6f5a93d7824981dc73_00001_00000-0
00:11:05,043 11032 [direct-runner-worker] INFO  org.apache.beam.sdk.io.gcp.bigquery.BigQueryServicesImpl - BigQuery job {jobId=beam_load_templatepipelinegrahampolley0531141053eff9d0d4_3dd2ba3a1c0347cf860241ddcd310a12_b4b4722df4326c6f5a93d7824981dc73_00001_00000-0, location=australia-southeast1, projectId=grey-sort-challenge} completed in state DONE
00:11:05,044 11033 [direct-runner-worker] INFO  org.apache.beam.sdk.io.gcp.bigquery.WriteTables - Load job {jobId=beam_load_templatepipelinegrahampolley0531141053eff9d0d4_3dd2ba3a1c0347cf860241ddcd310a12_b4b4722df4326c6f5a93d7824981dc73_00001_00000-0, location=australia-southeast1, projectId=grey-sort-challenge} succeeded. Statistics: {"completionRatio":1.0,"creationTime":"1559311861461","endTime":"1559311863323","load":{"badRecords":"0","inputFileBytes":"81","inputFiles":"1","outputBytes":"45","outputRows":"2"},"startTime":"1559311862043","totalSlotMs":"218","reservationUsage":[{"name":"default-pipeline","slotMs":"218"}]}
</code>```

Body:
Use a single Dataflow pipeline to do it in one shot/pass. Here's an example I wrote using the Java SDK to help get you started. It reads from Spanner, transforms it to a BigQuery TableRow using a ParDo, and then writes to BigQuery at the end. Under the hood it's using GCS, but that's all abstracted away from you as a user.

package org.polleyg;

import com.google.api.services.bigquery.model.TableFieldSchema;
import com.google.api.services.bigquery.model.TableRow;
import com.google.api.services.bigquery.model.TableSchema;
import com.google.cloud.spanner.Struct;
import org.apache.beam.runners.dataflow.options.DataflowPipelineOptions;
import org.apache.beam.sdk.Pipeline;
import org.apache.beam.sdk.io.gcp.bigquery.BigQueryIO;
import org.apache.beam.sdk.io.gcp.spanner.SpannerIO;
import org.apache.beam.sdk.options.PipelineOptionsFactory;
import org.apache.beam.sdk.transforms.DoFn;
import org.apache.beam.sdk.transforms.ParDo;
import org.apache.beam.sdk.values.PCollection;

import java.util.ArrayList;
import java.util.List;

import static org.apache.beam.sdk.io.gcp.bigquery.BigQueryIO.Write.CreateDisposition.CREATE_IF_NEEDED;
import static org.apache.beam.sdk.io.gcp.bigquery.BigQueryIO.Write.WriteDisposition.WRITE_TRUNCATE;

/**
 * Do some randomness
 */
public class TemplatePipeline {
    public static void main(String[] args) {
        PipelineOptionsFactory.register(DataflowPipelineOptions.class);
        DataflowPipelineOptions options = PipelineOptionsFactory.fromArgs(args).withValidation().as(DataflowPipelineOptions.class);
        Pipeline pipeline = Pipeline.create(options);
        PCollection<Struct> records = pipeline.apply("read_from_spanner",
                SpannerIO.read()
                        .withInstanceId("spanner-to-dataflow-to-bq")
                        .withDatabaseId("the-dude")
                        .withQuery("SELECT * FROM Singers"));
        records.apply("convert-2-bq-row", ParDo.of(new DoFn<Struct, TableRow>() {
            @ProcessElement
            public void processElement(ProcessContext c) throws Exception {
                TableRow row = new TableRow();
                row.set("id", c.element().getLong("SingerId"));
                row.set("first", c.element().getString("FirstName"));
                row.set("last", c.element().getString("LastName"));
                c.output(row);
            }
        })).apply("write-to-bq", BigQueryIO.writeTableRows()
                .to(String.format("%s:spanner_to_bigquery.singers", options.getProject()))
                .withCreateDisposition(CREATE_IF_NEEDED)
                .withWriteDisposition(WRITE_TRUNCATE)
                .withSchema(getTableSchema()));
        pipeline.run();
    }

    private static TableSchema getTableSchema() {
        List<TableFieldSchema> fields = new ArrayList<>();
        fields.add(new TableFieldSchema().setName("id").setType("INTEGER"));
        fields.add(new TableFieldSchema().setName("first").setType("STRING"));
        fields.add(new TableFieldSchema().setName("last").setType("STRING"));
        return new TableSchema().setFields(fields);
    }
}

Output logs:

00:10:54,011 0    [direct-runner-worker] INFO  org.apache.beam.sdk.io.gcp.bigquery.BatchLoads - Writing BigQuery temporary files to gs://spanner-dataflow-bq/tmp/BigQueryWriteTemp/beam_load_templatepipelinegrahampolley0531141053eff9d0d4_3dd2ba3a1c0347cf860241ddcd310a12/ before loading them.
00:10:59,332 5321 [direct-runner-worker] INFO  org.apache.beam.sdk.io.gcp.bigquery.TableRowWriter - Opening TableRowWriter to gs://spanner-dataflow-bq/tmp/BigQueryWriteTemp/beam_load_templatepipelinegrahampolley0531141053eff9d0d4_3dd2ba3a1c0347cf860241ddcd310a12/c374d44a-a7db-407e-aaa4-fe6aa5f6a9ef.
00:11:01,178 7167 [direct-runner-worker] INFO  org.apache.beam.sdk.io.gcp.bigquery.WriteTables - Loading 1 files into {datasetId=spanner_to_bigquery, projectId=grey-sort-challenge, tableId=singers} using job {jobId=beam_load_templatepipelinegrahampolley0531141053eff9d0d4_3dd2ba3a1c0347cf860241ddcd310a12_b4b4722df4326c6f5a93d7824981dc73_00001_00000-0, location=australia-southeast1, projectId=grey-sort-challenge}, attempt 0
00:11:02,495 8484 [direct-runner-worker] INFO  org.apache.beam.sdk.io.gcp.bigquery.BigQueryServicesImpl - Started BigQuery job: {jobId=beam_load_templatepipelinegrahampolley0531141053eff9d0d4_3dd2ba3a1c0347cf860241ddcd310a12_b4b4722df4326c6f5a93d7824981dc73_00001_00000-0, location=australia-southeast1, projectId=grey-sort-challenge}.
bq show -j --format=prettyjson --project_id=grey-sort-challenge beam_load_templatepipelinegrahampolley0531141053eff9d0d4_3dd2ba3a1c0347cf860241ddcd310a12_b4b4722df4326c6f5a93d7824981dc73_00001_00000-0
00:11:02,495 8484 [direct-runner-worker] INFO  org.apache.beam.sdk.io.gcp.bigquery.WriteTables - Load job {jobId=beam_load_templatepipelinegrahampolley0531141053eff9d0d4_3dd2ba3a1c0347cf860241ddcd310a12_b4b4722df4326c6f5a93d7824981dc73_00001_00000-0, location=australia-southeast1, projectId=grey-sort-challenge} started
00:11:03,183 9172 [direct-runner-worker] INFO  org.apache.beam.sdk.io.gcp.bigquery.BigQueryServicesImpl - Still waiting for BigQuery job beam_load_templatepipelinegrahampolley0531141053eff9d0d4_3dd2ba3a1c0347cf860241ddcd310a12_b4b4722df4326c6f5a93d7824981dc73_00001_00000-0, currently in status {"state":"RUNNING"}
bq show -j --format=prettyjson --project_id=grey-sort-challenge beam_load_templatepipelinegrahampolley0531141053eff9d0d4_3dd2ba3a1c0347cf860241ddcd310a12_b4b4722df4326c6f5a93d7824981dc73_00001_00000-0
00:11:05,043 11032 [direct-runner-worker] INFO  org.apache.beam.sdk.io.gcp.bigquery.BigQueryServicesImpl - BigQuery job {jobId=beam_load_templatepipelinegrahampolley0531141053eff9d0d4_3dd2ba3a1c0347cf860241ddcd310a12_b4b4722df4326c6f5a93d7824981dc73_00001_00000-0, location=australia-southeast1, projectId=grey-sort-challenge} completed in state DONE
00:11:05,044 11033 [direct-runner-worker] INFO  org.apache.beam.sdk.io.gcp.bigquery.WriteTables - Load job {jobId=beam_load_templatepipelinegrahampolley0531141053eff9d0d4_3dd2ba3a1c0347cf860241ddcd310a12_b4b4722df4326c6f5a93d7824981dc73_00001_00000-0, location=australia-southeast1, projectId=grey-sort-challenge} succeeded. Statistics: {"completionRatio":1.0,"creationTime":"1559311861461","endTime":"1559311863323","load":{"badRecords":"0","inputFileBytes":"81","inputFiles":"1","outputBytes":"45","outputRows":"2"},"startTime":"1559311862043","totalSlotMs":"218","reservationUsage":[{"name":"default-pipeline","slotMs":"218"}]}


问:
com.apple.WebKit.WebContent drops 113 error: Could not find specified service
I am using WKWebView for viewing custom HTML.

Regardless of HTML content, when testing on real device, I receive the following error Could not signal service com.apple.WebKit.WebContent: 113: Could not find specified service in 29 sec after WKWebView content loaded, sometimes I even receive this error twice. Clearly, it is a configuration issue. I have checked cookies as proposed in Could not signal service com.apple.WebKit.WebContent, however it doesn't help

Another question is whether there exist a list of all error codes that might pop up in WKWebView

答: Just for others reference, I seemed to have this issue too if I tried to load a URL that had whitespace at the end (was being pulled from user input).</p>

ContentLicense: CC BY-SA 3.0


问:
Build an restful api backend with node.js - problem how and where to start
I got an assignment to make a backend for the website with a Node.js framework of my choice to build a RESTful API of which the endpoints match the below specifications:
-pagination in batches of 30
-get 5 movies

-Add a filter to the above, which will allow the api to return either male or female characters.
- Make sure all the characters can be sorted by height in ascending and
descending order.

I had no knowledge of node.js (isn't it weird assignment for a front end position?) so what I did is: I googled a little and watched some tutorials: built an api in express and fetched and displayed/filtered data in React (only solutions I knew how to did it). But now I'd like to do it again but onlly backend. My problem is I got no idea how and where to start. Should I learn about databases and do it with databases? If Sb can help me and give me hints where to start and what steps I should take!
Thanks!

答:
I created a simple CLI to help me to create project nac new my-project --javascript and generate files (Model / Controller / Service / Route ) for node.js / MongoDB project's nac generate model user --javascript

You can find the full documentation here and how to install the CLI : node-cli

NB : you need to lean javascript/node.js first


问:
C#, calling an instance of a class from a string
I've been struggling for a while to find a way of calling an instance of a class from a user defined input.

Essentially I want to call an instance from my StandardVehicle class that has already been defined, however the problem is that the name of the instance that I'm calling is defined by a users selection on a combo box on a form.

This is how I assumed it would be formatted, however I get an error when I try calling the instance saying that I cannot complicitly convert from string to StandardVehicle.

```<code>        StandardVehicle VauxhallB = new StandardVehicle();
        VauxhallB.Model = "B";
        VauxhallB.Manufacturer = "Vauxhall";
        VauxhallB.Doors = 5;
        VauxhallB.HorsePower = 200;
        VauxhallB.Transmission = "Manual";
        VauxhallB.Year = 2009;
        VauxhallB.Cylinders = 6;
        VauxhallB.Seats = 7;
        VauxhallB.Price = 17000;
        VauxhallB.Registration = "abc1243";

        StandardVehicle objname = comboBox1.Text;
</code>```

I'm assuming it's just a case of formatting the string, but I've been searching for hours and can't figure out what format it needs to be in to define it as an instance.

Any help would be appreciated.

Regards,
S.

答:
You cannot convert string to an object unless you have

Constructor that takes string and    creates required object

An explicit/implicit cast operator

and another option

Use Activator.CreateInstace

3rd option is only valid if string contains valid type name, for your example you can do

```<code>Type type = Type.GetType(comboBox1.Text);
StandardVehicle objname = Activator.CreateInstace(type);
</code>```

this will work if comboBox1.Text == "StandardVehicle".

More information here:

http://msdn.microsoft.com/en-us/library/w3f99sx1.aspx

http://msdn.microsoft.com/en-us/library/wccyzw83.aspx

Body:
I've been struggling for a while to find a way of calling an instance of a class from a user defined input.

Essentially I want to call an instance from my StandardVehicle class that has already been defined, however the problem is that the name of the instance that I'm calling is defined by a users selection on a combo box on a form.

This is how I assumed it would be formatted, however I get an error when I try calling the instance saying that I cannot complicitly convert from string to StandardVehicle.

        StandardVehicle VauxhallB = new StandardVehicle();
        VauxhallB.Model = "B";
        VauxhallB.Manufacturer = "Vauxhall";
        VauxhallB.Doors = 5;
        VauxhallB.HorsePower = 200;
        VauxhallB.Transmission = "Manual";
        VauxhallB.Year = 2009;
        VauxhallB.Cylinders = 6;
        VauxhallB.Seats = 7;
        VauxhallB.Price = 17000;
        VauxhallB.Registration = "abc1243";

        StandardVehicle objname = comboBox1.Text;

I'm assuming it's just a case of formatting the string, but I've been searching for hours and can't figure out what format it needs to be in to define it as an instance.

Any help would be appreciated.

Regards,
S.

Body:
You cannot convert string to an object unless you have

Constructor that takes string and    creates required object

An explicit/implicit cast operator

and another option

Use Activator.CreateInstace

3rd option is only valid if string contains valid type name, for your example you can do

Type type = Type.GetType(comboBox1.Text);
StandardVehicle objname = Activator.CreateInstace(type);

this will work if comboBox1.Text == "StandardVehicle".

More information here:

http://msdn.microsoft.com/en-us/library/w3f99sx1.aspx

http://msdn.microsoft.com/en-us/library/wccyzw83.aspx


问:
Adding roles to Angular SPA and MSAL when using using Azure AD B2C
Using Angular 7 with MSAL.js and Azure AD B2C.

Implementing a role-based authentication is not directly supported by Azure AD B2C and requires the use of Azure Ad Graph API.

https://feedback.azure.com/forums/169401-azure-active-directory/suggestions/10123836-get-user-membership-groups-in-the-claims-with-ad-b

Authorize By Group in Azure Active Directory B2C

Is there a way to use MSAL with Azure AD Graph API to support roles (through claims or Azure AD B2C security groups)?

答:
You can add roles in the manifest of an application registration, that way you will get a roles claim with those roles defined.

Here is an article on how to create roles: How to add app roles in AAD.

If you are using groups instead you can associate a role to each group.


问:
Can't access elements of an array using request limiter for API requests
First of all, thanks for your time here.

I am using node.js to make API calls programmatically. I have an array filled with numbers and I would like to loop over it to send API requests to check if the number is valid. The problem is that I need to manage the throughput of my API requests to avoid an HTTP 429 (due to the API provider restrictions). I am also keeping the HTTP connection alive to speed up the requests rate.

I am using an external request limiter https://www.npmjs.com/package/limiter.

For simplicity, I will include numbercheck as a dependency, which doesn't exist but it's to avoid getting things more complicated.

My code is the following:

```<code>    var RateLimiter = require('limiter').RateLimiter;
    var http = require('http');
    var Checknumber = require('numbercheck')
    var agent = new http.Agent({
    keepAlive: true,
    maxSockets: 1,
    keepAliveMsecs: 3000
    })

//final is the array containing 100 phone numbers
var final = [xxxxxxxx, xxxxx, .......,];

//This limit the API requests to 1 per second
 var limiter = new RateLimiter(1, 'second');

for  (x=0; x<final.length; x++){

   limiter.removeTokens(1, function() {

    console.log(final[x], x);
//This console.log is to debug

Checknumber.get({ number: final[x]}, (error, response) => {
      if (error) {
        console.error(error)
      }
      else {
        console.log(response)

      }

    }
)}
)}

</code>```

The result that I get is that final[x] is undefined and therefore the API requests fail

console.log(final[x], x)  returns : undefined 100

It seems that somehow, I can't access final[x] by index.

Could you please help here?

Regards

I've also tried to pass final[x] in limiter.removeTokens(1, function(final[x]) {...
but I get

SyntaxError: Unexpected token [

答:
You have missed the variable assignment in the for loop:
(var x = 0; x < final.length; x++)

Other things I've noticed:

It's down to your coding style and preference but most of the time when looping I prefer using iterator's such as .forEach() or .map(), as it makes the code much more declarative. In this instance .forEach would be the correct iterator to use.

I find it easier to debug code if it is consistent, consider sticking to an ECMAScript Versions Syntax, so if you are going to commit to ES6 (You're using arrow functions), then use that throughout. Also consider using const and let over using var.

```<code>final.forEach((item, index) => {
  limiter.removeTokens(1, () => {
     console.log(item, index);
     Checknumber.get({ number: item}, (error, response) => {
       if (error) {
         console.error(error)
       } else {
         console.log(response)
       }
     })
   })
 }
</code>```

Body:
First of all, thanks for your time here.

I am using node.js to make API calls programmatically. I have an array filled with numbers and I would like to loop over it to send API requests to check if the number is valid. The problem is that I need to manage the throughput of my API requests to avoid an HTTP 429 (due to the API provider restrictions). I am also keeping the HTTP connection alive to speed up the requests rate.

I am using an external request limiter https://www.npmjs.com/package/limiter.

For simplicity, I will include numbercheck as a dependency, which doesn't exist but it's to avoid getting things more complicated.

My code is the following:

    var RateLimiter = require('limiter').RateLimiter;
    var http = require('http');
    var Checknumber = require('numbercheck')
    var agent = new http.Agent({
    keepAlive: true,
    maxSockets: 1,
    keepAliveMsecs: 3000
    })

//final is the array containing 100 phone numbers
var final = [xxxxxxxx, xxxxx, .......,];

//This limit the API requests to 1 per second
 var limiter = new RateLimiter(1, 'second');

for  (x=0; x<final.length; x++){

   limiter.removeTokens(1, function() {

    console.log(final[x], x);
//This console.log is to debug

Checknumber.get({ number: final[x]}, (error, response) => {
      if (error) {
        console.error(error)
      }
      else {
        console.log(response)

      }

    }
)}
)}

The result that I get is that final[x] is undefined and therefore the API requests fail

console.log(final[x], x)  returns : undefined 100

It seems that somehow, I can't access final[x] by index.

Could you please help here?

Regards

I've also tried to pass final[x] in limiter.removeTokens(1, function(final[x]) {...
but I get

SyntaxError: Unexpected token [

Body:
You have missed the variable assignment in the for loop:
(var x = 0; x < final.length; x++)

Other things I've noticed:

It's down to your coding style and preference but most of the time when looping I prefer using iterator's such as .forEach() or .map(), as it makes the code much more declarative. In this instance .forEach would be the correct iterator to use.

I find it easier to debug code if it is consistent, consider sticking to an ECMAScript Versions Syntax, so if you are going to commit to ES6 (You're using arrow functions), then use that throughout. Also consider using const and let over using var.

final.forEach((item, index) => {
  limiter.removeTokens(1, () => {
     console.log(item, index);
     Checknumber.get({ number: item}, (error, response) => {
       if (error) {
         console.error(error)
       } else {
         console.log(response)
       }
     })
   })
 }


问:
ALTER DATABASE failed because a lock could not be placed on database
I need to restart a database because some processes are not working. My plan is to take it offline and back online again.

I am trying to do this in Sql Server Management Studio 2008:

```<code>use master;
go
alter database qcvalues
set single_user
with rollback immediate;
alter database qcvalues
set multi_user;
go
</code>```

I am getting these errors:

```<code>Msg 5061, Level 16, State 1, Line 1
ALTER DATABASE failed because a lock could not be placed on database 'qcvalues'. Try again later.
Msg 5069, Level 16, State 1, Line 1
ALTER DATABASE statement failed.
Msg 5061, Level 16, State 1, Line 4
ALTER DATABASE failed because a lock could not be placed on database 'qcvalues'. Try again later.
Msg 5069, Level 16, State 1, Line 4
ALTER DATABASE statement failed.
</code>```

What am I doing wrong?

答:
In my scenario, there was no process blocking the database under sp_who2. However, we discovered because the database is much larger than our other databases that pending processes were still running which is why the database under the availability group still displayed as red/offline after we tried to 'resume data'by right clicking the paused database.

To check if you still have processes running just execute this command:
select percent complete from sys.dm_exec_requests
where percent_complete > 0

Body:
I need to restart a database because some processes are not working. My plan is to take it offline and back online again.

I am trying to do this in Sql Server Management Studio 2008:

use master;
go
alter database qcvalues
set single_user
with rollback immediate;
alter database qcvalues
set multi_user;
go

I am getting these errors:

Msg 5061, Level 16, State 1, Line 1
ALTER DATABASE failed because a lock could not be placed on database 'qcvalues'. Try again later.
Msg 5069, Level 16, State 1, Line 1
ALTER DATABASE statement failed.
Msg 5061, Level 16, State 1, Line 4
ALTER DATABASE failed because a lock could not be placed on database 'qcvalues'. Try again later.
Msg 5069, Level 16, State 1, Line 4
ALTER DATABASE statement failed.

What am I doing wrong?


问:
Modified JUnit xml reporter for jasmine giving RangeError: Maximum call stack size exceeded
I am using a modified version of Jasmine JUnit Reports (found here: https://github.com/angular/protractor-cookbook/tree/master/jasmine-junit-reports) and am getting an error for RangeError: Maximum call stack size exceeded

The reason I modified the report is that I needed the xml reports generated at the suiteDone step, not the jasmineDone step. So basically I moved all the code from jasmineDone into suiteDone function, which is now causing the error I am seeing. I am relatively new to js so not exactly sure if some asynchronous issue or something of the sort.

This is the stack trace and related bits of code:

```<code>- RangeError: Maximum call stack size exceeded
        at getSuite (C:\Users\AutomationUser\application\admin\adminui\e2e\common-pages\reporter.js:248:26)
        at exportObject.QmetryReporter.self.suiteDone (C:\Users\AutomationUser\application\admin\adminui\e2e\common-pages\reporter.js:312:21)
        at exportObject.QmetryReporter.self.suiteDone (C:\Users\AutomationUser\application\admin\adminui\e2e\common-pages\reporter.js:322:22)
</code>```

getSuite function (line 248):

```<code>function getSuite(suite) {
    __suites[suite.id] = extend(__suites[suite.id] || {}, suite);
    return __suites[suite.id];
}
</code>```

Chunk of suiteDone function:

```<code>self.suiteDone = function (suite) {
    suite = getSuite(suite); // this is line 312 from stacktrace
    if (suite._parent === UNDEFINED) {
        // disabled suite (xdescribe) -- suiteStarted was never called
        self.suiteStarted(suite);
    }
    suite._endTime = new Date();
    currentSuite = suite._parent;
    // below this line is the start of jasmineDone function that I moved into this function
    if (currentSuite) {
        // focused spec (fit) -- suiteDone was never called
        self.suiteDone(fakeFocusedSuite); // this is line 322 from stacktrace
    }
</code>```

The issue seems to only happen when running a larger grouping of test specs. If just running a single test file, I do not get the issue.

答:
I've run into this plenty of times. The solution that works for me is to use the increase-memory-limit package. Just install it globally and then run increase-memory-limit in the root of your project (where your package.json is). You should run this command after you have installed all your dependencies and before you start the tests. You will see a bunch of output that looks similar to the following

```<code>'~/app/node_modules/.bin/webdriver-manager' written successfully.
'~/app/node_modules/.bin/webdriver-manager.cmd' written successfully.
'~/app/node_modules/.bin/webpack' written successfully.
'~/app/node_modules/.bin/webpack-cli' written successfully.
'~/app/node_modules/.bin/webpack-cli.cmd' written successfully.
'~/app/node_modules/.bin/webpack-dev-server' written successfully.
'~/app/node_modules/.bin/webpack-dev-server.cmd' written successfully.
'~/app/node_modules/.bin/webpack.cmd' written successfully.
'~/app/node_modules/.bin/which' written successfully.
'~/app/node_modules/.bin/which.cmd' written successfully.
</code>```

After that, you shouldn't see this error again. My full regression suite is very large and I used to always see the same error when I tried to run the full suite all at once. The above packaged fixed it for me and I haven't had an issue since I started using it.

Body:
I am using a modified version of Jasmine JUnit Reports (found here: https://github.com/angular/protractor-cookbook/tree/master/jasmine-junit-reports) and am getting an error for RangeError: Maximum call stack size exceeded

The reason I modified the report is that I needed the xml reports generated at the suiteDone step, not the jasmineDone step. So basically I moved all the code from jasmineDone into suiteDone function, which is now causing the error I am seeing. I am relatively new to js so not exactly sure if some asynchronous issue or something of the sort.

This is the stack trace and related bits of code:

- RangeError: Maximum call stack size exceeded
        at getSuite (C:\Users\AutomationUser\application\admin\adminui\e2e\common-pages\reporter.js:248:26)
        at exportObject.QmetryReporter.self.suiteDone (C:\Users\AutomationUser\application\admin\adminui\e2e\common-pages\reporter.js:312:21)
        at exportObject.QmetryReporter.self.suiteDone (C:\Users\AutomationUser\application\admin\adminui\e2e\common-pages\reporter.js:322:22)

getSuite function (line 248):

function getSuite(suite) {
    __suites[suite.id] = extend(__suites[suite.id] || {}, suite);
    return __suites[suite.id];
}

Chunk of suiteDone function:

self.suiteDone = function (suite) {
    suite = getSuite(suite); // this is line 312 from stacktrace
    if (suite._parent === UNDEFINED) {
        // disabled suite (xdescribe) -- suiteStarted was never called
        self.suiteStarted(suite);
    }
    suite._endTime = new Date();
    currentSuite = suite._parent;
    // below this line is the start of jasmineDone function that I moved into this function
    if (currentSuite) {
        // focused spec (fit) -- suiteDone was never called
        self.suiteDone(fakeFocusedSuite); // this is line 322 from stacktrace
    }

The issue seems to only happen when running a larger grouping of test specs. If just running a single test file, I do not get the issue.

Body:
I've run into this plenty of times. The solution that works for me is to use the increase-memory-limit package. Just install it globally and then run increase-memory-limit in the root of your project (where your package.json is). You should run this command after you have installed all your dependencies and before you start the tests. You will see a bunch of output that looks similar to the following

'~/app/node_modules/.bin/webdriver-manager' written successfully.
'~/app/node_modules/.bin/webdriver-manager.cmd' written successfully.
'~/app/node_modules/.bin/webpack' written successfully.
'~/app/node_modules/.bin/webpack-cli' written successfully.
'~/app/node_modules/.bin/webpack-cli.cmd' written successfully.
'~/app/node_modules/.bin/webpack-dev-server' written successfully.
'~/app/node_modules/.bin/webpack-dev-server.cmd' written successfully.
'~/app/node_modules/.bin/webpack.cmd' written successfully.
'~/app/node_modules/.bin/which' written successfully.
'~/app/node_modules/.bin/which.cmd' written successfully.

After that, you shouldn't see this error again. My full regression suite is very large and I used to always see the same error when I tried to run the full suite all at once. The above packaged fixed it for me and I haven't had an issue since I started using it.


问:
Spring neo4j best place to start/stop a long running process [Java]
I have a Spring Neo4J server

I want to have an endpoint in this server that starts a thread to save tweets of a twitterstream to the neo4j database.

I also want to have an endpoint that stops this thread.

Is the best way to do this through the TaskExecutor object, or should I create a Runnable object and save it to the service bean, that I can interact with?

How would I do this in the context of a rest API endpoint in my Spring Data server?

答:
The way they recommend is to use a shared variable as a flag which asks the background thread to stop. This variable can then be set by a different object requesting the thread terminate.

Coming from How do you kill a Thread in Java?


问:
Is const keyword still better to have in Flutter (Dart 2) for performance?
I have read many articles and Stack Overflow questions/answers for const discussion.

People say if you create a const instance, that instance will be only created once. If you later try to create the same instance, the old one will be returned and no new memory allocation is required. This sounds better in performance. For example:

child: Column(
  children: <Widget>[
    Container(padding: const EdgeInsets.symmetric(horizontal: 8.0)),
    Container(padding: const EdgeInsets.symmetric(horizontal: 8.0)),
   ]
)
```

<p>The above code just shows the idea. The <code>const EdgeInsets.symmetric(horizontal: 8.0))</code> doesn't have to be inside the same widget class.</p>

<p>Now, when I read the official Dart 2 announcement, it has an opposite example. I just copy the code block from that article here:</p>

<pre class="lang-dart prettyprint-override"><code>// Before Dart 2
Widget build(BuildContext context) {
  return new Container(
    height: 56.0,
    padding: const EdgeInsets.symmetric(horizontal: 8.0),
    decoration: new BoxDecoration(color: Colors.blue[500]),
    child: new Row(
      ...
    ),
  );
}

// After Dart 2
Widget build(BuildContext context) =>
  Container(
    height: 56.0,
    padding: EdgeInsets.symmetric(horizontal: 8.0),
    decoration: BoxDecoration(color: Colors.blue[500]),
    child: Row(
      ...
    ),
  );
</code>```

Thus, should I still add const keyword or not in Dart 2?

At the beginning, I am removing all my const keywords. But when I read people suggest to add const keywords for performance, I am adding const keywords back. But today, when I read this article by accident, I am totally confused. Will the const auto imply in Dart 2 Flutter engine for such case? OR will this matter in Flutter?

答:
Will the const auto imply in Dart 2 flutter engine

No. Dart 2 does not imply const keyword. It removes the redundant ones.

```<code>Foo()
</code>```

and

```<code>const Foo()
</code>```

are not equivalent.

On the other hand:

```<code>const Foo(Bar())
</code>```

and

```<code>const Foo(const Bar())
</code>```

are indeed equivalent.

So yes, the const keyword is still somehow required for performance optimization.

Body:
I have read many articles and Stack Overflow questions/answers for const discussion.

People say if you create a const instance, that instance will be only created once. If you later try to create the same instance, the old one will be returned and no new memory allocation is required. This sounds better in performance. For example:

child: Column(
  children: <Widget>[
    Container(padding: const EdgeInsets.symmetric(horizontal: 8.0)),
    Container(padding: const EdgeInsets.symmetric(horizontal: 8.0)),
   ]
)

The above code just shows the idea. The const EdgeInsets.symmetric(horizontal: 8.0)) doesn't have to be inside the same widget class.

Now, when I read the official Dart 2 announcement, it has an opposite example. I just copy the code block from that article here:

// Before Dart 2
Widget build(BuildContext context) {
  return new Container(
    height: 56.0,
    padding: const EdgeInsets.symmetric(horizontal: 8.0),
    decoration: new BoxDecoration(color: Colors.blue[500]),
    child: new Row(
      ...
    ),
  );
}

// After Dart 2
Widget build(BuildContext context) =>
  Container(
    height: 56.0,
    padding: EdgeInsets.symmetric(horizontal: 8.0),
    decoration: BoxDecoration(color: Colors.blue[500]),
    child: Row(
      ...
    ),
  );

Thus, should I still add const keyword or not in Dart 2?

At the beginning, I am removing all my const keywords. But when I read people suggest to add const keywords for performance, I am adding const keywords back. But today, when I read this article by accident, I am totally confused. Will the const auto imply in Dart 2 Flutter engine for such case? OR will this matter in Flutter?

Body:
Will the const auto imply in Dart 2 flutter engine

No. Dart 2 does not imply const keyword. It removes the redundant ones.

Foo()

and

const Foo()

are not equivalent.

On the other hand:

const Foo(Bar())

and

const Foo(const Bar())

are indeed equivalent.

So yes, the const keyword is still somehow required for performance optimization.


问:
Update props from other component in react native
I have a Main class which I show an array to user, then in detail page user can edit each element which I'm passing using react navigation parameter. I want to edit my array in the detail class and save it using async storage.

```<code>//Main.jsimport React from 'react';
import {
    StyleSheet ,
     Text,
     View,
     TextInput,
     ScrollView,
     TouchableOpacity,
     KeyboardAvoidingView,
     AsyncStorage
    } from 'react-native'
import Note from './Note'
import detail from './Details'
import { createStackNavigator, createAppContainer } from "react-navigation";

export default class Main extends React.Component {

  static navigationOptions = {
    title: 'To do list',
    headerStyle: {
      backgroundColor: '#f4511e',
    },
  };

  constructor(props){
    super(props);
    this.state = {
      noteArray: [],
      noteText: '',
      dueDate: ''
    };
  }

  async saveUserTasks(value) {
    try {
      await AsyncStorage.setItem('@MySuperStore:userTask',JSON.stringify(value));
    } catch (error) {
      console.log("Error saving data" + error);
    }
  }
   getUserTasks = async() =>{
    try {
      const value = await AsyncStorage.getItem('@MySuperStore:userTask');
      if (value !== null){
        this.setState({ noteArray: JSON.parse(value)});
      }
    } catch (error) {
      console.log("Error retrieving data" + error);
    }
  }

render() {
  this.getUserTasks()
    let notes = this.state.noteArray.map((val,key) => {
      return <Note key={key} keyval={key} val={val}
      deleteMethod={ () => this.deleteNote(key)}
      goToDetailPage= {() => this.goToNoteDetail(key)}
       />
    });
    const { navigation } = this.props;
    return(
      <KeyboardAvoidingView behavior='padding' style={styles.keyboard}>
        <View style={styles.container}>
            <ScrollView style={styles.scrollContainer}>
                {notes}
            </ScrollView>
            <View style={styles.footer}>
                <TextInput
                onChangeText={(noteText) => this.setState({noteText})}
                style={styles.textInput}
                placeholder='What is your next Task?'
                placeholderTextColor='white'
                underlineColorAndroid = 'transparent'
                >
                </TextInput>
            </View>
            <TouchableOpacity onPress={this.addNote.bind(this)} style={styles.addButton}>
                <Text style={styles.addButtonText}> + </Text>
            </TouchableOpacity>
        </View>
   </KeyboardAvoidingView>
      );
    }
    addNote(){
      if (this.state.noteText){
        var d = new Date();
        this.state.noteArray.push({
        'creationDate': d.getFullYear() + "/" + (d.getMonth()+1) + "/" + d.getDay(), 'taskName': this.state.noteText,'dueDate':'YYYY/MM/DD'
        });
        this.setState({noteArray:this.state.noteArray})
        this.setState({noteText: ''});
        this.saveUserTasks(this.state.noteArray)
      }
    }
    deleteNote(key){
      this.state.noteArray.splice(key,1);
      this.setState({noteArray: this.state.noteArray})
      this.saveUserTasks(this.state.noteArray)
    }
    goToNoteDetail=(key)=>{
      this.props.navigation.navigate('DetailsScreen', {
        selectedTask: this.state.noteArray[key],
      });
    }
}
</code>```

in detail view I have this method which is similar to add note in main class:

```<code>export default class Details extends React.Component {
  render() {
    const { navigation } = this.props;
    const selectedTask = navigation.getParam('selectedTask', 'task');
    return(
     <View key={this.props.keyval} style={styles.container}>
      <TouchableOpacity onPress={this.saveEdit.bind(this)} style={styles.saveButton}>
                <Text style={styles.saveButtonText}> save </Text>
      </TouchableOpacity>
    </View>
    );
  }
  saveEdit(){

    let selectedItem = { 'creationDate': selectedTask['creationDate'],
    'taskName': selectedTask['taskName'],
    'dueDate': this.state.dueData}

this.props.navigation.state.params.saveEdit(selectedItem)
      }
    }
</code>```

How can I change my props in any component?

答:
First of all you shouldn't call this.getUserTasks() in the render method because the function has this.setState which is bad and could end in a endless loop I guess or at least effect in worse performance. You could instead call it in componentDidMount:

```<code>componentDidMount = () => {
    this.getUserTasks();
}
</code>```

Or alternatively call already in constructor but I prefer the first option:

```<code>constructor(props){
  super(props);
  this.state = {
    noteArray: [],
    noteText: '',
    dueDate: ''
  };

  this.getUserTasks()
}
</code>```

this.props.noteArray.push({.. is probably undefined because you aren't passing it down any where. (Didn't see any reference in your snippet). I guess I would implement the saveEdit function in the Main.js component and simply pass it down to the navigation route and call the function in Details component by accessing the navigation state props:

Update

```<code>  goToNoteDetail=(key)=>{
    this.props.navigation.navigate('DetailsScreen', {
      // selectedTask: this.state.noteArray[key],
      selectedItem: key,
      saveEdit: this.saveEdit
    });
  }

  saveEdit(selectedItem){
    const selectedTask = this.state.noteArray[selectedItem]
    this.state.noteArray.push({
      'creationDate': selectedTask['creationDate'],
      'taskName': selectedTask['taskName'],
      'dueDate': this.state.dueData
    });
    this.setState({noteArray:this.state.noteArray})
    this.setState({dueData: 'YYYY/MM/DD'});
    this.saveUserTasks(this.state.noteArray)
  }
</code>```

And then call saveEdit in Details Component:

```<code>saveSelectedItem = () => {
  const { navigation } = this.props.navigation;
  const {selectedItem, saveEdit} = navigation.state && navigation.state.params;
  saveEdit(selectedItem)
}
</code>```

Body:
I have a Main class which I show an array to user, then in detail page user can edit each element which I'm passing using react navigation parameter. I want to edit my array in the detail class and save it using async storage.

//Main.jsimport React from 'react';
import {
    StyleSheet ,
     Text,
     View,
     TextInput,
     ScrollView,
     TouchableOpacity,
     KeyboardAvoidingView,
     AsyncStorage
    } from 'react-native'
import Note from './Note'
import detail from './Details'
import { createStackNavigator, createAppContainer } from "react-navigation";

export default class Main extends React.Component {

  static navigationOptions = {
    title: 'To do list',
    headerStyle: {
      backgroundColor: '#f4511e',
    },
  };

  constructor(props){
    super(props);
    this.state = {
      noteArray: [],
      noteText: '',
      dueDate: ''
    };
  }

  async saveUserTasks(value) {
    try {
      await AsyncStorage.setItem('@MySuperStore:userTask',JSON.stringify(value));
    } catch (error) {
      console.log("Error saving data" + error);
    }
  }
   getUserTasks = async() =>{
    try {
      const value = await AsyncStorage.getItem('@MySuperStore:userTask');
      if (value !== null){
        this.setState({ noteArray: JSON.parse(value)});
      }
    } catch (error) {
      console.log("Error retrieving data" + error);
    }
  }

render() {
  this.getUserTasks()
    let notes = this.state.noteArray.map((val,key) => {
      return <Note key={key} keyval={key} val={val}
      deleteMethod={ () => this.deleteNote(key)}
      goToDetailPage= {() => this.goToNoteDetail(key)}
       />
    });
    const { navigation } = this.props;
    return(
      <KeyboardAvoidingView behavior='padding' style={styles.keyboard}>
        <View style={styles.container}>
            <ScrollView style={styles.scrollContainer}>
                {notes}
            </ScrollView>
            <View style={styles.footer}>
                <TextInput
                onChangeText={(noteText) => this.setState({noteText})}
                style={styles.textInput}
                placeholder='What is your next Task?'
                placeholderTextColor='white'
                underlineColorAndroid = 'transparent'
                >
                </TextInput>
            </View>
            <TouchableOpacity onPress={this.addNote.bind(this)} style={styles.addButton}>
                <Text style={styles.addButtonText}> + </Text>
            </TouchableOpacity>
        </View>
   </KeyboardAvoidingView>
      );
    }
    addNote(){
      if (this.state.noteText){
        var d = new Date();
        this.state.noteArray.push({
        'creationDate': d.getFullYear() + "/" + (d.getMonth()+1) + "/" + d.getDay(), 'taskName': this.state.noteText,'dueDate':'YYYY/MM/DD'
        });
        this.setState({noteArray:this.state.noteArray})
        this.setState({noteText: ''});
        this.saveUserTasks(this.state.noteArray)
      }
    }
    deleteNote(key){
      this.state.noteArray.splice(key,1);
      this.setState({noteArray: this.state.noteArray})
      this.saveUserTasks(this.state.noteArray)
    }
    goToNoteDetail=(key)=>{
      this.props.navigation.navigate('DetailsScreen', {
        selectedTask: this.state.noteArray[key],
      });
    }
}

in detail view I have this method which is similar to add note in main class:

export default class Details extends React.Component {
  render() {
    const { navigation } = this.props;
    const selectedTask = navigation.getParam('selectedTask', 'task');
    return(
     <View key={this.props.keyval} style={styles.container}>
      <TouchableOpacity onPress={this.saveEdit.bind(this)} style={styles.saveButton}>
                <Text style={styles.saveButtonText}> save </Text>
      </TouchableOpacity>
    </View>
    );
  }
  saveEdit(){

    let selectedItem = { 'creationDate': selectedTask['creationDate'],
    'taskName': selectedTask['taskName'],
    'dueDate': this.state.dueData}

this.props.navigation.state.params.saveEdit(selectedItem)
      }
    }

How can I change my props in any component?

Body:
First of all you shouldn't call this.getUserTasks() in the render method because the function has this.setState which is bad and could end in a endless loop I guess or at least effect in worse performance. You could instead call it in componentDidMount:

componentDidMount = () => {
    this.getUserTasks();
}

Or alternatively call already in constructor but I prefer the first option:

constructor(props){
  super(props);
  this.state = {
    noteArray: [],
    noteText: '',
    dueDate: ''
  };

  this.getUserTasks()
}

this.props.noteArray.push({.. is probably undefined because you aren't passing it down any where. (Didn't see any reference in your snippet). I guess I would implement the saveEdit function in the Main.js component and simply pass it down to the navigation route and call the function in Details component by accessing the navigation state props:

Update

  goToNoteDetail=(key)=>{
    this.props.navigation.navigate('DetailsScreen', {
      // selectedTask: this.state.noteArray[key],
      selectedItem: key,
      saveEdit: this.saveEdit
    });
  }

  saveEdit(selectedItem){
    const selectedTask = this.state.noteArray[selectedItem]
    this.state.noteArray.push({
      'creationDate': selectedTask['creationDate'],
      'taskName': selectedTask['taskName'],
      'dueDate': this.state.dueData
    });
    this.setState({noteArray:this.state.noteArray})
    this.setState({dueData: 'YYYY/MM/DD'});
    this.saveUserTasks(this.state.noteArray)
  }

And then call saveEdit in Details Component:

saveSelectedItem = () => {
  const { navigation } = this.props.navigation;
  const {selectedItem, saveEdit} = navigation.state && navigation.state.params;
  saveEdit(selectedItem)
}


问:
Multiple Occurrences of an Event at the same Time
Conal Elliott's paper defines Event as

```<code>type Event a = [(T , a)] -- for non-decreasing times
</code>```

This would allow more than one occurrence at a time.
In my FRP library I would like to implement the function:

```<code>sample :: Reactive a -> Future () -> Future a
</code>```

This would sample the reactive when the future fires. Since the reactive can have more than one value at the time the future fires how should I implement it? Always use the last, the first, or a nonempty list?

This is how the sample function should behave:

```<code>sample
    (MkReactive "a"
        (MkEvent
            (MkFuture 2
                (MkReactive "b" ...)
            )
        )
    (MkFuture 1 ())
= MkFuture 1 "a"
</code>```

答:
In the paper Push-pull functional reactive programming (if duplode is correct), the fundamental sampling combinator switcher is described as:

The semantics of b₀ `switcher` e chooses and samples either b₀
  or the last behavior from e before a given sample time t

sample should behave the same way to be compatible with the combinators in that paper. Since a Reactive is an Event with an initial value, and a Future is a time-value pair, sample r (MkFuture t ()) should return a MkFuture t v where v is the last value in r from strictly before t, or the initial value of r if there is no such value. There's no issue with multiple values at the same time: any values at time t are ignored since they're not strictly before t, and of the values before t, "take the last one" is unambiguous.

Body:
Conal Elliott's paper defines Event as

type Event a = [(T , a)] -- for non-decreasing times

This would allow more than one occurrence at a time.
In my FRP library I would like to implement the function:

sample :: Reactive a -> Future () -> Future a

This would sample the reactive when the future fires. Since the reactive can have more than one value at the time the future fires how should I implement it? Always use the last, the first, or a nonempty list?

This is how the sample function should behave:

sample
    (MkReactive "a"
        (MkEvent
            (MkFuture 2
                (MkReactive "b" ...)
            )
        )
    (MkFuture 1 ())
= MkFuture 1 "a"


问:
Functions in Haskell
I'm new to functional programming. I have a basic question.

I'm using the Hugs interpreter,

I would like to write a function in Haskell; I went though several tutorials, but I'm not getting it.

```<code>fact :: Int -> Int
fact n = if n == 0 then
1
else
n * fact (n-1)
</code>```

This gives me a syntax error :-S

```<code>ERROR - Syntax error in input (unexpected `=')
</code>```

答:
Create a file named, for example, fact.hs

```<code>-- copying cedric's nicely formatted code
fact :: Int -> Int
fact n = if n == 0
    then 1
    else n * fact (n-1)
</code>```

That's all that really needs to be there. When you want to make real modules, you should do some extra stuff.

Now, open up ghci from the same folder. At the ghci prompt, use the :l command to load the "module"

```<code>Prelude> :l fact.hs
[1 of 1] Compiling Main             ( fact.hs, interpreted )
Ok, modules loaded: Main.
*Main> fact 3
6
*Main> fact 10
3628800
</code>```

I assume it's a very similar process with Hugs. I think hugs requires the file name to be capitalized. ghci simply creates a "Main" module and puts your code in it; that's why the prompt changes from Prelude> to *Main>

When I work on small Haskell functions, I usually keep two terminals open: one for vim and one for ghci. When I change the file in vim (and save it), I just use :r in ghci to reload the new definitions.

```<code>*Main> :r
Ok, modules loaded: Main.
</code>```

Title: Functions in Haskell

Body:
I'm new to functional programming. I have a basic question.

I'm using the Hugs interpreter,

I would like to write a function in Haskell; I went though several tutorials, but I'm not getting it.

fact :: Int -> Int
fact n = if n == 0 then
1
else
n * fact (n-1)

This gives me a syntax error :-S

ERROR - Syntax error in input (unexpected `=')

Body:
Create a file named, for example, fact.hs

-- copying cedric's nicely formatted code
fact :: Int -> Int
fact n = if n == 0
    then 1
    else n * fact (n-1)

That's all that really needs to be there. When you want to make real modules, you should do some extra stuff.

Now, open up ghci from the same folder. At the ghci prompt, use the :l command to load the "module"

Prelude> :l fact.hs
[1 of 1] Compiling Main             ( fact.hs, interpreted )
Ok, modules loaded: Main.
*Main> fact 3
6
*Main> fact 10
3628800

I assume it's a very similar process with Hugs. I think hugs requires the file name to be capitalized. ghci simply creates a "Main" module and puts your code in it; that's why the prompt changes from Prelude> to *Main>

When I work on small Haskell functions, I usually keep two terminals open: one for vim and one for ghci. When I change the file in vim (and save it), I just use :r in ghci to reload the new definitions.

*Main> :r
Ok, modules loaded: Main.


问:
Github: Remove watchers of a repository
I want to remove a specific watcher of my repository in Github. Is there a way to do that?
Or can I even track who's watching my repository?</p>

答:
There's currently (as of May 2019) no way to remove a watcher from a specific repository, but you can remove a watcher from all your repositories (with side effects, detailed below) by blocking and then unblocking them:

Navigate to https://github.com/settings/blocked_users

Add the watcher in question to your blocked users list

Remove them from your blocked users list

They'll no longer be listed as watchers on any of your repos

Side effects:

Blocking and unblocking a user will also sever any follower associations you have with them (i.e., if you follow them, you'll have to re-follow, and vice versa)

Title: Github: Remove watchers of a repository


问:
How to upgrade sqlite 3.8.2 to >= 3.8.3
In a virtual Env with Python 3.7.2, I am trying to run django's python manage.py startap myapp and I get this error:

```<code>raise ImproperlyConfigured('SQLite 3.8.3 or later is required (found %s).' % Database.sqlite_version)
django.core.exceptions.ImproperlyConfigured: SQLite 3.8.3 or later is required (found 3.8.2).
</code>```

I'm running Ubuntu Trusty 14.04 Server.

How do I upgrade or update my sqlite version to >=3.8.3?

I ran

$ apt list --installed | grep sqlite

```<code>libaprutil1-dbd-sqlite3/trusty,now 1.5.3-1 amd64 [installed,automatic]
libdbd-sqlite3/trusty,now 0.9.0-2ubuntu2 amd64 [installed]
libsqlite3-0/trusty-updates,trusty-security,now 3.8.2-1ubuntu2.2 amd64 [installed]
libsqlite3-dev/trusty-updates,trusty-security,now 3.8.2-1ubuntu2.2 amd64 [installed]
python-pysqlite2/trusty,now 2.6.3-3 amd64 [installed]
python-pysqlite2-dbg/trusty,now 2.6.3-3 amd64 [installed]
sqlite3/trusty-updates,trusty-security,now 3.8.2-1ubuntu2.2 amd64 [installed]
</code>```

and

sudo apt install --only-upgrade libsqlite3-0

```<code>Reading package lists... Done
Building dependency tree
Reading state information... Done
libsqlite3-0 is already the newest version.
0 upgraded, 0 newly installed, 0 to remove and 14 not upgraded.
</code>```

EDIT:
the settings.py is stock standard:

```<code>DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.sqlite3',
        'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
    }
}
</code>```

答: In addition to the above mentioned answers, just in case if you experience this behaviour on Travis CI, add dist: xenial directive to fix it.

Title: How to upgrade sqlite 3.8.2 to >= 3.8.3

Body:
In a virtual Env with Python 3.7.2, I am trying to run django's python manage.py startap myapp and I get this error:

raise ImproperlyConfigured('SQLite 3.8.3 or later is required (found %s).' % Database.sqlite_version)
django.core.exceptions.ImproperlyConfigured: SQLite 3.8.3 or later is required (found 3.8.2).

I'm running Ubuntu Trusty 14.04 Server.

How do I upgrade or update my sqlite version to >=3.8.3?

I ran

$ apt list --installed | grep sqlite

libaprutil1-dbd-sqlite3/trusty,now 1.5.3-1 amd64 [installed,automatic]
libdbd-sqlite3/trusty,now 0.9.0-2ubuntu2 amd64 [installed]
libsqlite3-0/trusty-updates,trusty-security,now 3.8.2-1ubuntu2.2 amd64 [installed]
libsqlite3-dev/trusty-updates,trusty-security,now 3.8.2-1ubuntu2.2 amd64 [installed]
python-pysqlite2/trusty,now 2.6.3-3 amd64 [installed]
python-pysqlite2-dbg/trusty,now 2.6.3-3 amd64 [installed]
sqlite3/trusty-updates,trusty-security,now 3.8.2-1ubuntu2.2 amd64 [installed]

and

sudo apt install --only-upgrade libsqlite3-0

Reading package lists... Done
Building dependency tree
Reading state information... Done
libsqlite3-0 is already the newest version.
0 upgraded, 0 newly installed, 0 to remove and 14 not upgraded.

EDIT:
the settings.py is stock standard:

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.sqlite3',
        'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
    }
}


答:
As @DDovzhenko pointed out u can not just declare an Optional type. Actually you should not do that at all, because u are expecting a String and should stick to that. In combination with the

```<code>required=false
</code>```

attribute of the @PathVariable it should work fine:

```<code>@PathVariable(required=false) String urVariable
</code>```

Title: Spring controller not working when the last PathVariable in RequestMapping has only

Body:
I am trying to map a request to Spring controller but it is not working as expected

I get 404 error when I am trying /simple/test/something/.....
and my mapping is as follows @RequestMapping(path="/simple/test/{string1}/{string2}")

Below is my code

@RequestMapping(path = "/search/test/{string1}/{string2}", produces = APPLICATION_JSON_UTF8_VALUE)
@ResponseBody
public SearchResult search( @PathVariable String string1, @PathVariable Optional string2) {
    if (!query.isPresent()) {
        return service.getLastQueries(string1, string2);
    }
}

when the {string2} contains / or only .... then I am getting 404 error.
For example {string2} is ....... or some/thing

Body:
As @DDovzhenko pointed out u can not just declare an Optional type. Actually you should not do that at all, because u are expecting a String and should stick to that. In combination with the

required=false

attribute of the @PathVariable it should work fine:

@PathVariable(required=false) String urVariable


问:
gRPC & HTTP servers on GKE Ingress failing healthcheck for gRPC backend
I want to deploy a gRPC + HTTP servers on GKE with HTTP/2 and mutual TLS. My deployment have both a readiness probe and liveness probe with custom path. I expose both the gRPC and HTTP servers via an Ingress.

deployment's probes and exposed ports:

```<code>    livenessProbe:
      failureThreshold: 3
      httpGet:
        path: /_ah/health
        port: 8443
        scheme: HTTPS
      periodSeconds: 10
      successThreshold: 1
      timeoutSeconds: 1
    readinessProbe:
      failureThreshold: 3
      httpGet:
        path: /_ah/health
        port: 8443
        scheme: HTTPS
    name: grpc-gke
    ports:
    - containerPort: 8443
      protocol: TCP
    - containerPort: 50052
      protocol: TCP
</code>```

NodePort service:

```<code>apiVersion: v1
kind: Service
metadata:
  name: grpc-gke-nodeport
  labels:
    app: grpc-gke
  annotations:
    cloud.google.com/app-protocols: '{"grpc":"HTTP2","http":"HTTP2"}'
    service.alpha.kubernetes.io/app-protocols: '{"grpc":"HTTP2", "http": "HTTP2"}'
spec:
  type: NodePort
  ports:
  - name: grpc
    port: 50052
    protocol: TCP
    targetPort: 50052
  - name: http
    port: 443
    protocol: TCP
    targetPort: 8443
  selector:
    app: grpc-gke
</code>```

Ingress:

```<code>apiVersion: extensions/v1beta1
kind: Ingress
metadata:
  name: grpc-gke-ingress
  annotations:
    kubernetes.io/ingress.allow-http: "false"
    #kubernetes.io/ingress.global-static-ip-name: "grpc-gke-ip"
  labels:
    app: grpc-gke
spec:
  rules:
  - http:
      paths:
      - path: /_ah/*
        backend:
          serviceName: grpc-gke-nodeport
          servicePort: 443
  backend:
    serviceName: grpc-gke-nodeport
    servicePort: 50052
</code>```

The pod does exist, and has a "green" status, before creating the liveness and readiness probes. I see regular logs on my server that both the /_ah/live and /_ah/ready are called by the kube-probe and the server responds with the 200 response.

I use a Google managed TLS certificate on the load balancer (LB). My HTTP server creates a self-signed certificate -- inspired by this blog.

I create the Ingress after I start seeing the probes' logs. After that it creates an LB with two backends, one for the HTTP and one for the gRPC. The HTTP backend's health checks are OK and the HTTP server is accessible from the Internet. The gRPC backend's health check fails thus the LB does not route the gRPC protocol and I receive the 502 error response.

This is with GKE master 1.12.7-gke.10. I also tried newer 1.13 and older 1.11 masters. The cluster has HTTP load balancing enabled and VPC-native enabled. There are firewall rules to allow access from LB to my pods (I even tried to allow all ports from all IP addresses). Delaying the probes does not help either.

Funny thing is that I deployed nearly the same setup, just the server's Docker image is different, couple of months ago and it is running without any issues. I can even deploy new Docker images of the server and everything is great. I cannot find any difference between these two.

There is one another issue, the Ingress is stuck on the "Creating Ingress" state for days. It never finishes and never sees the LB. The Ingress' LB never has a front-end and I always have to manually add an HTTP/2 front-end with a static IP and Google managed TLS certificate. This should be happening only for cluster which were created without "HTTP load balancing", but it happens in my case every time for all my "HTTP load balancing enabled" clusters. The working deployment is in this state for months already.

Any ideas why the gRPC backend's health check could be failing even though I see logs that the readiness and liveness endpoints are called by kube-probe?

EDIT:

describe svc grpc-gke-nodeport

```<code>Name:                     grpc-gke-nodeport
Namespace:                default
Labels:                   app=grpc-gke
Annotations:              cloud.google.com/app-protocols: {"grpc":"HTTP2","http":"HTTP2"}
                        kubectl.kubernetes.io/last-applied-configuration:
                            {"apiVersion":"v1","kind":"Service","metadata":{"annotations":{"cloud.google.com/app-protocols":"{\"grpc\":\"HTTP2\",\"http\":\"HTTP2\"}",...
                        service.alpha.kubernetes.io/app-protocols: {"grpc":"HTTP2", "http": "HTTP2"}
Selector:                 app=grpc-gke
Type:                     NodePort
IP:                       10.4.8.188
Port:                     grpc  50052/TCP
TargetPort:               50052/TCP
NodePort:                 grpc  32148/TCP
Endpoints:                10.0.0.25:50052
Port:                     http  443/TCP
TargetPort:               8443/TCP
NodePort:                 http  30863/TCP
Endpoints:                10.0.0.25:8443
Session Affinity:         None
External Traffic Policy:  Cluster
Events:                   <none>
</code>```

and the health check for the gRPC backend is an HTTP/2 GET using path / on port 32148. Its description is "Default kubernetes L7 Loadbalancing health check." where as the description of the HTTP's back-end health check is "Kubernetes L7 health check generated with readiness probe settings.". Thus the health check for the gRPC back-end is not created from the readiness probe.

Editing the health check to point to port 30863 an changing the path to readiness probe fixes the issue.

答:
Editing the health check to point to the readiness probe's path and changed the port to the one of the HTTP back-end fixed this issue (look for the port in the HTTP back-end's health check. it is the NodePort's.). It runs know without any issues.

Using the same health check for the gRPC back-end as for the HTTP back-end did not work, it was reset back to its own health check. Even deleting the gRPC back-end's health check did not help, it was recreated. Only editing it to use a different port and path has helped.

Body:
I want to deploy a gRPC + HTTP servers on GKE with HTTP/2 and mutual TLS. My deployment have both a readiness probe and liveness probe with custom path. I expose both the gRPC and HTTP servers via an Ingress.

deployment's probes and exposed ports:

    livenessProbe:
      failureThreshold: 3
      httpGet:
        path: /_ah/health
        port: 8443
        scheme: HTTPS
      periodSeconds: 10
      successThreshold: 1
      timeoutSeconds: 1
    readinessProbe:
      failureThreshold: 3
      httpGet:
        path: /_ah/health
        port: 8443
        scheme: HTTPS
    name: grpc-gke
    ports:
    - containerPort: 8443
      protocol: TCP
    - containerPort: 50052
      protocol: TCP

NodePort service:

apiVersion: v1
kind: Service
metadata:
  name: grpc-gke-nodeport
  labels:
    app: grpc-gke
  annotations:
    cloud.google.com/app-protocols: '{"grpc":"HTTP2","http":"HTTP2"}'
    service.alpha.kubernetes.io/app-protocols: '{"grpc":"HTTP2", "http": "HTTP2"}'
spec:
  type: NodePort
  ports:
  - name: grpc
    port: 50052
    protocol: TCP
    targetPort: 50052
  - name: http
    port: 443
    protocol: TCP
    targetPort: 8443
  selector:
    app: grpc-gke

Ingress:

apiVersion: extensions/v1beta1
kind: Ingress
metadata:
  name: grpc-gke-ingress
  annotations:
    kubernetes.io/ingress.allow-http: "false"
    #kubernetes.io/ingress.global-static-ip-name: "grpc-gke-ip"
  labels:
    app: grpc-gke
spec:
  rules:
  - http:
      paths:
      - path: /_ah/*
        backend:
          serviceName: grpc-gke-nodeport
          servicePort: 443
  backend:
    serviceName: grpc-gke-nodeport
    servicePort: 50052

The pod does exist, and has a "green" status, before creating the liveness and readiness probes. I see regular logs on my server that both the /_ah/live and /_ah/ready are called by the kube-probe and the server responds with the 200 response.

I use a Google managed TLS certificate on the load balancer (LB). My HTTP server creates a self-signed certificate -- inspired by this blog.

I create the Ingress after I start seeing the probes' logs. After that it creates an LB with two backends, one for the HTTP and one for the gRPC. The HTTP backend's health checks are OK and the HTTP server is accessible from the Internet. The gRPC backend's health check fails thus the LB does not route the gRPC protocol and I receive the 502 error response.

This is with GKE master 1.12.7-gke.10. I also tried newer 1.13 and older 1.11 masters. The cluster has HTTP load balancing enabled and VPC-native enabled. There are firewall rules to allow access from LB to my pods (I even tried to allow all ports from all IP addresses). Delaying the probes does not help either.

Funny thing is that I deployed nearly the same setup, just the server's Docker image is different, couple of months ago and it is running without any issues. I can even deploy new Docker images of the server and everything is great. I cannot find any difference between these two.

There is one another issue, the Ingress is stuck on the "Creating Ingress" state for days. It never finishes and never sees the LB. The Ingress' LB never has a front-end and I always have to manually add an HTTP/2 front-end with a static IP and Google managed TLS certificate. This should be happening only for cluster which were created without "HTTP load balancing", but it happens in my case every time for all my "HTTP load balancing enabled" clusters. The working deployment is in this state for months already.

Any ideas why the gRPC backend's health check could be failing even though I see logs that the readiness and liveness endpoints are called by kube-probe?

EDIT:

describe svc grpc-gke-nodeport

Name:                     grpc-gke-nodeport
Namespace:                default
Labels:                   app=grpc-gke
Annotations:              cloud.google.com/app-protocols: {"grpc":"HTTP2","http":"HTTP2"}
                        kubectl.kubernetes.io/last-applied-configuration:
                            {"apiVersion":"v1","kind":"Service","metadata":{"annotations":{"cloud.google.com/app-protocols":"{\"grpc\":\"HTTP2\",\"http\":\"HTTP2\"}",...
                        service.alpha.kubernetes.io/app-protocols: {"grpc":"HTTP2", "http": "HTTP2"}
Selector:                 app=grpc-gke
Type:                     NodePort
IP:                       10.4.8.188
Port:                     grpc  50052/TCP
TargetPort:               50052/TCP
NodePort:                 grpc  32148/TCP
Endpoints:                10.0.0.25:50052
Port:                     http  443/TCP
TargetPort:               8443/TCP
NodePort:                 http  30863/TCP
Endpoints:                10.0.0.25:8443
Session Affinity:         None
External Traffic Policy:  Cluster
Events:                   <none>

and the health check for the gRPC backend is an HTTP/2 GET using path / on port 32148. Its description is "Default kubernetes L7 Loadbalancing health check." where as the description of the HTTP's back-end health check is "Kubernetes L7 health check generated with readiness probe settings.". Thus the health check for the gRPC back-end is not created from the readiness probe.

Editing the health check to point to port 30863 an changing the path to readiness probe fixes the issue.