问:
Advanced if else statements with grep in Groovy
I have following Jenkinsfile which will grep for a string from URL, it will send a notification to Slack depends upon the output.

```<code>stage('Check if present') {
    steps  {
        script{
         sh """
          if curl -s http://example.foo.com:9000 | grep -q "ERROR"
            then
              slackSend channel: '#team', message: "Pipeline has been failed due to due to an error, please investigate:${env.BUILD_URL} : http://example.foo.com:9000", teamDomain: 'example', tokenCredentialId: 'foo'
                echo "Scan result: ERROR" && exit 1
            elif curl -s http://example.foo.com:9000 | grep -q "WARN"
            then
           slackSend channel: '#team', message: "Pipeline is in WARN state due to a warning, please investigate:${env.BUILD_URL} : http://example.foo.com:9000", teamDomain: 'example', tokenCredentialId: 'foo'
             fi"""
         }
       }
    }
</code>```

Absolutely the slackSend notification won't work, as it is a plugin.
I am looking for ways to do the same in Groovy so that I can implement slackNotification.

I tried the following logic in Groovy, as an example.
But it didn't work, as even if the line is not present is is printing line is found.

```<code>stage('test logic'){
steps{
 script{
     if ('curl -s http://example.foo.com:9000'.execute() | 'grep foo'.execute())
        println("The line is found")
     else {
         println("The line is not found")
         exit 1
     }
       }

}}
</code>```

答:
You can just use Groovy's (to be more accurate Java's) .contains(String) method to check if some string contains other string. Also when you execute command in pipeline you can capture stdout of that command.

Code:

```<code>stage('test logic'){
  steps{
   script{
     def commandStdout = sh(returnStdout: true, script: "curl -s http://example.foo.com:9000"
     if (commandStdout.contains("foo")) {
        println("The line is found")
     }else {
         println("The line is not found")
         exit 1
     }
   }
  }
}
</code>```

Body:
I have following Jenkinsfile which will grep for a string from URL, it will send a notification to Slack depends upon the output.

stage('Check if present') {
    steps  {
        script{
         sh """
          if curl -s http://example.foo.com:9000 | grep -q "ERROR"
            then
              slackSend channel: '#team', message: "Pipeline has been failed due to due to an error, please investigate:${env.BUILD_URL} : http://example.foo.com:9000", teamDomain: 'example', tokenCredentialId: 'foo'
                echo "Scan result: ERROR" && exit 1
            elif curl -s http://example.foo.com:9000 | grep -q "WARN"
            then
           slackSend channel: '#team', message: "Pipeline is in WARN state due to a warning, please investigate:${env.BUILD_URL} : http://example.foo.com:9000", teamDomain: 'example', tokenCredentialId: 'foo'
             fi"""
         }
       }
    }

Absolutely the slackSend notification won't work, as it is a plugin.
I am looking for ways to do the same in Groovy so that I can implement slackNotification.

I tried the following logic in Groovy, as an example.
But it didn't work, as even if the line is not present is is printing line is found.

stage('test logic'){
steps{
 script{
     if ('curl -s http://example.foo.com:9000'.execute() | 'grep foo'.execute())
        println("The line is found")
     else {
         println("The line is not found")
         exit 1
     }
       }

}}

Body:
You can just use Groovy's (to be more accurate Java's) .contains(String) method to check if some string contains other string. Also when you execute command in pipeline you can capture stdout of that command.

Code:

stage('test logic'){
  steps{
   script{
     def commandStdout = sh(returnStdout: true, script: "curl -s http://example.foo.com:9000"
     if (commandStdout.contains("foo")) {
        println("The line is found")
     }else {
         println("The line is not found")
         exit 1
     }
   }
  }
}


来源: stackexchange

问:
Nested lists into smalls lists (splitted by category)
This is my code, which is inside of a function:

```<code>xArray = []

for t in range(npapers):

  nHeader = []
  headers = browser.find_elements_by_xpath("(//div[@class='gs_a'])[%s]"%(t+1))

  for nheaders in headers:
     nHeader.append(nheaders.text)
  xArray.append(nHeader)

  return xArray
</code>```

It prints me a big list, with the following result:

```<code>[['LR Hirsch, AM Gobin, AR Lowery, F Tam… - Annals of biomedical …, 2006 - Springer'],
 ['C Loo, A Lowery, N Halas, J West, R Drezek - Nano letters, 2005 - ACS Publications'],
 ['SJ Oldenburg, JB Jackson, SL Westcott… - Applied Physics …, 1999 - aip.scitation.org'],
 ['RD Averitt, SL Westcott, NJ Halas - JOSA B, 1999 - osapublishing.org'],
 ['LR Hirsch, JB Jackson, A Lee, NJ Halas… - Analytical …, 2003 - ACS Publications'],
 ['SJ Oldenburg, RD Averitt, NJ Halas - US Patent 6,344,272, 2002 - Google Patents'],
 ['AM Gobin, MH Lee, NJ Halas, WD James… - Nano …, 2007 - ACS Publications'],
 ['JB Lassiter, J Aizpurua, LI Hernandez, DW Brandl… - Nano …, 2008 - ACS Publications'],
 ['JB Jackson, NJ Halas - The Journal of Physical Chemistry B, 2001 - ACS Publications'],
 ['RD Averitt, D Sarkar, NJ Halas - Physical Review Letters, 1997 - APS']]
</code>```

I am trying to split it up and get small subsets of the big list, something like:

```<code>Authors = [LR Hirsch, AM Gobin, AR Lowery, F Tam],[C Loo, A Lowery, N Halas, J West, R Drezek],[SJ Oldenburg, JB Jackson, SL Westcott],[RD Averitt, SL Westcott, NJ Halas],[LR Hirsch, JB Jackson, A Lee, NJ Halas],[SJ Oldenburg, RD Averitt, NJ Halas],[AM Gobin, MH Lee, NJ Halas, WD James],[JB Lassiter, J Aizpurua, LI Hernandez, DW Brandl],[JB Jackson, NJ Halas],[RD Averitt, D Sarkar, NJ Halas]]
Year = [[2006],[2005],[1999],[1999],[2003],[2002],[2007],[2008],[2001],[1997]]
Publisher =[[Springer],[ACS Publications],[aip.scitation.org],[ACS Publications][osapublishing.org],[Google Patents],[ACS Publications],[ACS Publications],[ACS Publications],[APS]]
</code>```

答:
The same type of output - nested list of small lists(splitted by category) that you want.

```<code>import re

authors = []
years = []
publications = []

text=[['LR Hirsch, AM Gobin, AR Lowery, F Tam… - Annals of biomedical …, 2006 - Springer'],
 ['C Loo, A Lowery, N Halas, J West, R Drezek - Nano letters, 2005 - ACS Publications'],
 ['SJ Oldenburg, JB Jackson, SL Westcott… - Applied Physics …, 1999 - aip.scitation.org'],
 ['RD Averitt, SL Westcott, NJ Halas - JOSA B, 1999 - osapublishing.org'],
 ['LR Hirsch, JB Jackson, A Lee, NJ Halas… - Analytical …, 2003 - ACS Publications'],
 ['SJ Oldenburg, RD Averitt, NJ Halas - US Patent 6,344,272, 2002 - Google Patents'],
 ['AM Gobin, MH Lee, NJ Halas, WD James… - Nano …, 2007 - ACS Publications'],
 ['JB Lassiter, J Aizpurua, LI Hernandez, DW Brandl… - Nano …, 2008 - ACS Publications'],
 ['JB Jackson, NJ Halas - The Journal of Physical Chemistry B, 2001 - ACS Publications'],
 ['RD Averitt, D Sarkar, NJ Halas - Physical Review Letters, 1997 - APS']]

regex = "\[\'(?P<author>[A-Za-z\s,]+)(.*?),\s+(?P<year>[\d]{4})\s+-\s+(?P<publication>.*?)\'\],"

matches = re.finditer(regex, str(text), re.MULTILINE)

for matchNum, match in enumerate(matches, start=1):
    authors.append([match.group('author').strip()])
    years.append([match.group('year').strip()])
    publications.append([match.group('publication').strip()])

print('Authors = ', authors)
print('Year = ', years)
print('Publisher =', publications)
</code>```

Output:

```<code>Authors =  [['LR Hirsch, AM Gobin, AR Lowery, F Tam'], ['C Loo, A Lowery, N Halas, J West, R Drezek'], ['SJ Oldenburg, JB Jackson, SL Westcott'], ['RD Averitt, SL Westcott, NJ Halas'], ['LR Hirsch, JB Jackson, A Lee, NJ Halas'], ['SJ Oldenburg, RD Averitt, NJ Halas'], ['AM Gobin, MH Lee, NJ Halas, WD James'], ['JB Lassiter, J Aizpurua, LI Hernandez, DW Brandl'], ['JB Jackson, NJ Halas']]
Year =  [['2006'], ['2005'], ['1999'], ['1999'], ['2003'], ['2002'], ['2007'], ['2008'], ['2001']]
Publisher = [['Springer'], ['ACS Publications'], ['aip.scitation.org'], ['osapublishing.org'], ['ACS Publications'], ['Google Patents'], ['ACS Publications'], ['ACS Publications'], ['ACS Publications']]
</code>```

ContentLicense: CC BY-SA 4.0

Body:
This is my code, which is inside of a function:

xArray = []

for t in range(npapers):

  nHeader = []
  headers = browser.find_elements_by_xpath("(//div[@class='gs_a'])[%s]"%(t+1))

  for nheaders in headers:
     nHeader.append(nheaders.text)
  xArray.append(nHeader)

  return xArray

It prints me a big list, with the following result:

[['LR Hirsch, AM Gobin, AR Lowery, F Tam… - Annals of biomedical …, 2006 - Springer'],
 ['C Loo, A Lowery, N Halas, J West, R Drezek - Nano letters, 2005 - ACS Publications'],
 ['SJ Oldenburg, JB Jackson, SL Westcott… - Applied Physics …, 1999 - aip.scitation.org'],
 ['RD Averitt, SL Westcott, NJ Halas - JOSA B, 1999 - osapublishing.org'],
 ['LR Hirsch, JB Jackson, A Lee, NJ Halas… - Analytical …, 2003 - ACS Publications'],
 ['SJ Oldenburg, RD Averitt, NJ Halas - US Patent 6,344,272, 2002 - Google Patents'],
 ['AM Gobin, MH Lee, NJ Halas, WD James… - Nano …, 2007 - ACS Publications'],
 ['JB Lassiter, J Aizpurua, LI Hernandez, DW Brandl… - Nano …, 2008 - ACS Publications'],
 ['JB Jackson, NJ Halas - The Journal of Physical Chemistry B, 2001 - ACS Publications'],
 ['RD Averitt, D Sarkar, NJ Halas - Physical Review Letters, 1997 - APS']]

I am trying to split it up and get small subsets of the big list, something like:

Authors = [LR Hirsch, AM Gobin, AR Lowery, F Tam],[C Loo, A Lowery, N Halas, J West, R Drezek],[SJ Oldenburg, JB Jackson, SL Westcott],[RD Averitt, SL Westcott, NJ Halas],[LR Hirsch, JB Jackson, A Lee, NJ Halas],[SJ Oldenburg, RD Averitt, NJ Halas],[AM Gobin, MH Lee, NJ Halas, WD James],[JB Lassiter, J Aizpurua, LI Hernandez, DW Brandl],[JB Jackson, NJ Halas],[RD Averitt, D Sarkar, NJ Halas]]
Year = [[2006],[2005],[1999],[1999],[2003],[2002],[2007],[2008],[2001],[1997]]
Publisher =[[Springer],[ACS Publications],[aip.scitation.org],[ACS Publications][osapublishing.org],[Google Patents],[ACS Publications],[ACS Publications],[ACS Publications],[APS]]

Body:
The same type of output - nested list of small lists(splitted by category) that you want.

import re

authors = []
years = []
publications = []

text=[['LR Hirsch, AM Gobin, AR Lowery, F Tam… - Annals of biomedical …, 2006 - Springer'],
 ['C Loo, A Lowery, N Halas, J West, R Drezek - Nano letters, 2005 - ACS Publications'],
 ['SJ Oldenburg, JB Jackson, SL Westcott… - Applied Physics …, 1999 - aip.scitation.org'],
 ['RD Averitt, SL Westcott, NJ Halas - JOSA B, 1999 - osapublishing.org'],
 ['LR Hirsch, JB Jackson, A Lee, NJ Halas… - Analytical …, 2003 - ACS Publications'],
 ['SJ Oldenburg, RD Averitt, NJ Halas - US Patent 6,344,272, 2002 - Google Patents'],
 ['AM Gobin, MH Lee, NJ Halas, WD James… - Nano …, 2007 - ACS Publications'],
 ['JB Lassiter, J Aizpurua, LI Hernandez, DW Brandl… - Nano …, 2008 - ACS Publications'],
 ['JB Jackson, NJ Halas - The Journal of Physical Chemistry B, 2001 - ACS Publications'],
 ['RD Averitt, D Sarkar, NJ Halas - Physical Review Letters, 1997 - APS']]

regex = "\[\'(?P<author>[A-Za-z\s,]+)(.*?),\s+(?P<year>[\d]{4})\s+-\s+(?P<publication>.*?)\'\],"

matches = re.finditer(regex, str(text), re.MULTILINE)

for matchNum, match in enumerate(matches, start=1):
    authors.append([match.group('author').strip()])
    years.append([match.group('year').strip()])
    publications.append([match.group('publication').strip()])

print('Authors = ', authors)
print('Year = ', years)
print('Publisher =', publications)

Output:

Authors =  [['LR Hirsch, AM Gobin, AR Lowery, F Tam'], ['C Loo, A Lowery, N Halas, J West, R Drezek'], ['SJ Oldenburg, JB Jackson, SL Westcott'], ['RD Averitt, SL Westcott, NJ Halas'], ['LR Hirsch, JB Jackson, A Lee, NJ Halas'], ['SJ Oldenburg, RD Averitt, NJ Halas'], ['AM Gobin, MH Lee, NJ Halas, WD James'], ['JB Lassiter, J Aizpurua, LI Hernandez, DW Brandl'], ['JB Jackson, NJ Halas']]
Year =  [['2006'], ['2005'], ['1999'], ['1999'], ['2003'], ['2002'], ['2007'], ['2008'], ['2001']]
Publisher = [['Springer'], ['ACS Publications'], ['aip.scitation.org'], ['osapublishing.org'], ['ACS Publications'], ['Google Patents'], ['ACS Publications'], ['ACS Publications'], ['ACS Publications']]


问:
elastic: query the sum of a filtered subset of nested documents
Consider a document (post) like this in elasticsearch index:

```<code>    {
      title: "I love ice cream!"
      comments: [
        {
          body: "me too!",
          reaction: 'positive',
          likes: 20
        },
        {
          body: "huh!",
          reaction: 'sarcastic',
          likes: 5
        }
      ]
    }
</code>```

The comments is a field of nested type.

How can elastic answer this:
Give me all posts, where the total sum of likes on "sarcastic" comments is greater than 100.
I'm open to any other way of modelling data which helps answer such queries.

答:
This can be solved using bucket selector aggregation.

Mapping:

```<code>{
  "index1" : {
    "mappings" : {
      "properties" : {
        "comments" : {
          "type" : "nested",
          "properties" : {
            "body" : {
              "type" : "text"
            },
            "likes" : {
              "type" : "integer"
            },
            "reaction" : {
              "type" : "text"
            }
          }
        },
        "title" : {
          "type" : "keyword"
        }
      }
    }
  }
}
</code>```

Data:

```<code>  "hits" : [
      {
        "_index" : "index1",
        "_type" : "_doc",
        "_id" : "p0y9DGsBfPdKzuAGdQrm",
        "_score" : 1.0,
        "_source" : {
          "title" : "I love ice cream!",
          "comments" : [
            {
              "body" : "me too!",
              "reaction" : "positive",
              "likes" : 20
            },
            {
              "body" : "huh!",
              "reaction" : "sarcastic",
              "likes" : 5
            }
          ]
        }
      },
      {
        "_index" : "index1",
        "_type" : "_doc",
        "_id" : "qEy9DGsBfPdKzuAGnwox",
        "_score" : 1.0,
        "_source" : {
          "title" : "I hate ice cream!",
          "comments" : [
            {
              "body" : "me too!",
              "reaction" : "positive",
              "likes" : 10
            },
            {
              "body" : "huh!",
              "reaction" : "sarcastic",
              "likes" : 5
            }
          ]
        }
      }
    ]
  }
</code>```

Query:

```<code>GET index1/_search
{
  "size": 0,
  "aggs": {
    "title": {
      "terms": {
        "field": "title"
      },
      "aggs": {
        "comments": {
          "nested": {
            "path": "comments"
          },
          "aggs": {
            "reaction": {
              "filter": {
                "term": {
                  "comments.reaction": "positive"
                }
              },
              "aggs": {
                "total_likes": {
                  "sum": {
                    "field": "comments.likes"
                  }
                }
              }
            }
          }
        },
        "total_likes_filter": {
          "bucket_selector": {
            "buckets_path": {
              "likes": "comments>reaction>total_likes"
            },
            "script": "params.likes > 15"
          }
        }
      }
    }
  }
}
</code>```

Result:

```<code>  "aggregations" : {
    "title" : {
      "doc_count_error_upper_bound" : 0,
      "sum_other_doc_count" : 0,
      "buckets" : [
        {
          "key" : "I love ice cream!",
          "doc_count" : 1,
          "comments" : {
            "doc_count" : 2,
            "reaction" : {
              "doc_count" : 1,
              "total_likes" : {
                "value" : 20.0
              }
            }
          }
        }
      ]
    }
  }
}
</code>```

Bucket contains only "I love ice cream!" where total likes for reaction positive  is greater than 20.
I hate ice cream! has total sum 5 for positive reaction so it is not included.

Body:
Consider a document (post) like this in elasticsearch index:

    {
      title: "I love ice cream!"
      comments: [
        {
          body: "me too!",
          reaction: 'positive',
          likes: 20
        },
        {
          body: "huh!",
          reaction: 'sarcastic',
          likes: 5
        }
      ]
    }

The comments is a field of nested type.

How can elastic answer this:
Give me all posts, where the total sum of likes on "sarcastic" comments is greater than 100.
I'm open to any other way of modelling data which helps answer such queries.

Body:
This can be solved using bucket selector aggregation.

Mapping:

{
  "index1" : {
    "mappings" : {
      "properties" : {
        "comments" : {
          "type" : "nested",
          "properties" : {
            "body" : {
              "type" : "text"
            },
            "likes" : {
              "type" : "integer"
            },
            "reaction" : {
              "type" : "text"
            }
          }
        },
        "title" : {
          "type" : "keyword"
        }
      }
    }
  }
}

Data:

  "hits" : [
      {
        "_index" : "index1",
        "_type" : "_doc",
        "_id" : "p0y9DGsBfPdKzuAGdQrm",
        "_score" : 1.0,
        "_source" : {
          "title" : "I love ice cream!",
          "comments" : [
            {
              "body" : "me too!",
              "reaction" : "positive",
              "likes" : 20
            },
            {
              "body" : "huh!",
              "reaction" : "sarcastic",
              "likes" : 5
            }
          ]
        }
      },
      {
        "_index" : "index1",
        "_type" : "_doc",
        "_id" : "qEy9DGsBfPdKzuAGnwox",
        "_score" : 1.0,
        "_source" : {
          "title" : "I hate ice cream!",
          "comments" : [
            {
              "body" : "me too!",
              "reaction" : "positive",
              "likes" : 10
            },
            {
              "body" : "huh!",
              "reaction" : "sarcastic",
              "likes" : 5
            }
          ]
        }
      }
    ]
  }

Query:

GET index1/_search
{
  "size": 0,
  "aggs": {
    "title": {
      "terms": {
        "field": "title"
      },
      "aggs": {
        "comments": {
          "nested": {
            "path": "comments"
          },
          "aggs": {
            "reaction": {
              "filter": {
                "term": {
                  "comments.reaction": "positive"
                }
              },
              "aggs": {
                "total_likes": {
                  "sum": {
                    "field": "comments.likes"
                  }
                }
              }
            }
          }
        },
        "total_likes_filter": {
          "bucket_selector": {
            "buckets_path": {
              "likes": "comments>reaction>total_likes"
            },
            "script": "params.likes > 15"
          }
        }
      }
    }
  }
}

Result:

  "aggregations" : {
    "title" : {
      "doc_count_error_upper_bound" : 0,
      "sum_other_doc_count" : 0,
      "buckets" : [
        {
          "key" : "I love ice cream!",
          "doc_count" : 1,
          "comments" : {
            "doc_count" : 2,
            "reaction" : {
              "doc_count" : 1,
              "total_likes" : {
                "value" : 20.0
              }
            }
          }
        }
      ]
    }
  }
}

Bucket contains only "I love ice cream!" where total likes for reaction positive  is greater than 20.
I hate ice cream! has total sum 5 for positive reaction so it is not included.


问:
Google chrome doesn't show icons of fontawesome
I am trying to put some font awesome icons on my site. But google chrome doesn't show icons of fontawesome.com
I have tested with other browsers, it works fine.
I have imported the link of fontawsome CDN in the head tag.
I have also put the tag of icons to show.
There's no adblocker and any extension that blocks icons.
I have tested with chromium browser, same problem with that browser.
I haven't used any extension for chromium.

Note: I am on the latest version of the Chrome browser and also imported the latest version of fontawesome.com
Chrome: Version 74.0.3729.169 (Official Build) (64-bit)
Font. version: 5.8.2

P.S.: It's working fine on another laptop of my friend, but not working in my mine. Please figure out the problem.
link
Here's the link of jsfiddle for code:

```<code> <!-- Font awesome 4 -->
<link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.8.2/css/all.css" integrity="sha384-oS3vJWv+0UjzBfQzYUhtDYW+Pj2yciDJxpsK1OYPAYjqT085Qq/1cq5FLXAZQ7Ay" crossorigin="anonymous">

<!-- The code for icon -->
<div class="icon-container">
    <i class="icon far fa-gem"></i>
</div>
</code>```

Please check the screenshots:

答: I'm using the same version of Chrome and that fiddle displays as expected (far-gem is shown).  So I don't think it is a FA-issue or a Chrome-issue. Possibly some addins are causing trouble.</p>

Body:
I am trying to put some font awesome icons on my site. But google chrome doesn't show icons of fontawesome.com
I have tested with other browsers, it works fine.
I have imported the link of fontawsome CDN in the head tag.
I have also put the tag of icons to show.
There's no adblocker and any extension that blocks icons.
I have tested with chromium browser, same problem with that browser.
I haven't used any extension for chromium.

Note: I am on the latest version of the Chrome browser and also imported the latest version of fontawesome.com
Chrome: Version 74.0.3729.169 (Official Build) (64-bit)
Font. version: 5.8.2

P.S.: It's working fine on another laptop of my friend, but not working in my mine. Please figure out the problem.
link
Here's the link of jsfiddle for code:

<link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.8.2/css/all.css" integrity="sha384-oS3vJWv+0UjzBfQzYUhtDYW+Pj2yciDJxpsK1OYPAYjqT085Qq/1cq5FLXAZQ7Ay" crossorigin="anonymous">

Please check the screenshots:


问:
would return 0 using C++ in a class outside of main close the application?
I'm currently working on implementing patch files in some code, and apparently one of the patch files uses return 0 in a class outside of the main. I know return 0 would close the application if it was in the main function, however I'm not sure about how it would function in a class outside of the main function. Basically the code could be summed up like this in pseudocode:

```<code>boost::uint64_t
namespace::class(etc. etc.)
{

   if (method.isValid)
   {
      //do stuff
   }
return 0;
}
</code>```

Normally when I think of return 0 in C++, I think of exiting the application by calling it in main, however in this case, I'm not sure if this would exit the application, or just the class's functionality/the class it self. Could someone please explain what the return 0 would actually be doing in this situation?

Thanks,
Flyboy

答: No, returning 0 (or anything else) from a function won't exit the application.  Returning from main -- regardless of the value returned -- exits from a (single-threaded) application. But other functions come and go all the time.

ContentLicense: CC BY-SA 3.0

Body:
I'm currently working on implementing patch files in some code, and apparently one of the patch files uses return 0 in a class outside of the main. I know return 0 would close the application if it was in the main function, however I'm not sure about how it would function in a class outside of the main function. Basically the code could be summed up like this in pseudocode:

boost::uint64_t
namespace::class(etc. etc.)
{

   if (method.isValid)
   {
      //do stuff
   }
return 0;
}

Normally when I think of return 0 in C++, I think of exiting the application by calling it in main, however in this case, I'm not sure if this would exit the application, or just the class's functionality/the class it self. Could someone please explain what the return 0 would actually be doing in this situation?

Thanks,
Flyboy


问:
How do I use a data constructor on a value wrapped inside an IO monad?
So I have a data type in haskell defined as follows:

```<code>import qualified Data.UUID as UUID
import qualified Data.Time.Clock as CLK

data MyRecord = MyRecord {
    id :: UUID.UUID,
    creationDate :: CLK.UTCTime,
    comment :: String
}
</code>```

now the problem is that the UUID and UTCTime are returned inside an IO monad. The functions I use to generate them have the following type

for UUID

```<code>nextRandom :: IO uuid-types-1.0.3:Data.UUID.Types.Internal.UUID
</code>```

for getting the current time stamp:

```<code>getCurrentTime :: IO UTCTime
</code>```

my problem is how do use the data constructor to actually initialise the data type?

I can do the following

```<code>MyRecord <$> nextRandom
</code>```

and this works, but I am not able to understand how to provide the constructor with the other argument.

答:
You can use the sequential application (<*>) :: Applicative f => f (a -> b) -> f a -> f b for this. For example:

```<code>MyRecord <$> nextRandom <b><*></b> getCurrentTime <b><*></b> return "some comment"</code>```

This is equivalent to:

```<code>some_function :: IO MyRecord
some_function = do
    r <- nextRandom
    t <- getCurrentTime
    return (MyRecord r t "some comment")</code>```

What here basically happens is that if you write:

```<code>MyRecord <$> nextRandom</code>```

you construct an item of type IO (UTCTime -> String -> MyRecord). Now by using the (<*>) function with as left operand this function, and as right operand an IO UTCTime, we thus construct an object of type IO (String -> MyRecord).

We can use return :: Monad m => a -> m a or pure :: Applicative f => a -> f a to convert a String to an IO String, and we thus use again (<*>) to apply this to the partial data constructor.

Body:
So I have a data type in haskell defined as follows:

import qualified Data.UUID as UUID
import qualified Data.Time.Clock as CLK

data MyRecord = MyRecord {
    id :: UUID.UUID,
    creationDate :: CLK.UTCTime,
    comment :: String
}

now the problem is that the UUID and UTCTime are returned inside an IO monad. The functions I use to generate them have the following type

for UUID

nextRandom :: IO uuid-types-1.0.3:Data.UUID.Types.Internal.UUID

for getting the current time stamp:

getCurrentTime :: IO UTCTime

my problem is how do use the data constructor to actually initialise the data type?

I can do the following

MyRecord <$> nextRandom

and this works, but I am not able to understand how to provide the constructor with the other argument.

Body:
You can use the sequential application (<*>) :: Applicative f => f (a -> b) -> f a -> f b for this. For example:

MyRecord <$> nextRandom <*> getCurrentTime <*> return "some comment"

This is equivalent to:

some_function :: IO MyRecord
some_function = do
    r <- nextRandom
    t <- getCurrentTime
    return (MyRecord r t "some comment")

What here basically happens is that if you write:

MyRecord <$> nextRandom

you construct an item of type IO (UTCTime -> String -> MyRecord). Now by using the (<*>) function with as left operand this function, and as right operand an IO UTCTime, we thus construct an object of type IO (String -> MyRecord).

We can use return :: Monad m => a -> m a or pure :: Applicative f => a -> f a to convert a String to an IO String, and we thus use again (<*>) to apply this to the partial data constructor.


问:
how do I send the last insert id data to another function?
I want to pass my last insert id from one table into another function when I test with var_dumb() $ids var contains value but after submiting $ids var contains nothing.
can someone show me how to do it in this code,
thank you

this is my controller :

```<code>function save()
{
    $judul = $this->input->post('judul');
    $isi = $this->input->post('isi');
    $kategori = implode(',', $this->input->post('kategori'));
    $c_date=date("Y-m-d H:i:s");

    $data = array(
        'judul' => $judul,
        'isi' => $isi,
        'kategori' => $kategori,
        'publish' => $c_date
    );

    $ids = $this->text_editor_model->simpan($data);
    redirect('text_editor');

    $last = $this->upload_image($ids);
}

function upload_image($last)
{
    $config['upload_path'] = './berkas/news/';
    $config['allowed_types'] = 'jpg|png|jpeg';
    $config['max_size'] = 0;

    $this->load->library('upload', $config);

    var_dump($last);

    if ( !$this->upload->do_upload('file')) {
        $this->output->set_header('HTTP/1.0 500 Server Error');
        exit;
    } else {
        $file = $this->upload->data();
        $this->output
            ->set_content_type('application/json', 'utf-8')
            ->set_output(json_encode(['location' => base_url().'/berkas/news/'.$file['file_name']]))
            ->_display();
        $count = count($file['file_name']);
            for ($i=0; $i < $count ; $i++) {
                $data2[$i]['id_berita'] = $last;
                $data2[$i]['img_name'] =  $file['file_name'];
            }
            $this->text_editor_model->insert_img($data2);
            exit;
    }
}
</code>```

my simpan model :

```<code>function simpan($data)
{
    $this->db->insert('db_news',$data);

    $id_berita = $this->db->insert_id();
    return $id_berita;
}
</code>```

答:
if redirect('text_editor'); redirects to another page? then $last = $this->upload_image($ids); will not execute, so you need to call the upload first then redirect

```<code>$last = $this->upload_image($ids);
redirect('text_editor');
</code>```

Body:
I want to pass my last insert id from one table into another function when I test with var_dumb() $ids var contains value but after submiting $ids var contains nothing.
can someone show me how to do it in this code,
thank you

this is my controller :

function save()
{
    $judul = $this->input->post('judul');
    $isi = $this->input->post('isi');
    $kategori = implode(',', $this->input->post('kategori'));
    $c_date=date("Y-m-d H:i:s");

    $data = array(
        'judul' => $judul,
        'isi' => $isi,
        'kategori' => $kategori,
        'publish' => $c_date
    );

    $ids = $this->text_editor_model->simpan($data);
    redirect('text_editor');

    $last = $this->upload_image($ids);
}

function upload_image($last)
{
    $config['upload_path'] = './berkas/news/';
    $config['allowed_types'] = 'jpg|png|jpeg';
    $config['max_size'] = 0;

    $this->load->library('upload', $config);

    var_dump($last);

    if ( !$this->upload->do_upload('file')) {
        $this->output->set_header('HTTP/1.0 500 Server Error');
        exit;
    } else {
        $file = $this->upload->data();
        $this->output
            ->set_content_type('application/json', 'utf-8')
            ->set_output(json_encode(['location' => base_url().'/berkas/news/'.$file['file_name']]))
            ->_display();
        $count = count($file['file_name']);
            for ($i=0; $i < $count ; $i++) {
                $data2[$i]['id_berita'] = $last;
                $data2[$i]['img_name'] =  $file['file_name'];
            }
            $this->text_editor_model->insert_img($data2);
            exit;
    }
}

my simpan model :

function simpan($data)
{
    $this->db->insert('db_news',$data);

    $id_berita = $this->db->insert_id();
    return $id_berita;
}

Body:
if redirect('text_editor'); redirects to another page? then $last = $this->upload_image($ids); will not execute, so you need to call the upload first then redirect

$last = $this->upload_image($ids);
redirect('text_editor');


问:
How to use localStorage Carefully in Angular
Since localStorage data can be changed easily, how can we make access controls and more things secure in the Angular App.

Suppose our localstorage contains:

data - {name:user, account_status:inactive,...}

The user can easily change the account_status from inactive to active and get all access.
I am not just concerned about access control but also the other localstorage data which is used in angular.

Can I encrypt the data from the node server and store it in localstorage and decrypt it back when i want to use with the same secret key. Will this have some adverse effects.

Please suggest some methods which can be used.

答: You can create a common service for localstorage operation which will perform the encryption when storing data in localstorage and decryption when getting data from localstorage. You should encrypt key and value both so it is not easy to change the value in localstorage. You can use CryptoJS for encryption.</p>


问:
How to add White color to web view Background
I have a web view to show the pdf. When it displaying the pdf it's not taking full area it's not the issues with me, but the background color of it shows a kind of dark color background I need to remove that dark color to white how to do this in xamarin forms

答:
Did you use Google doc viewer to load the remote pdf files? If so, the extra border can't be removed as it is controlled by Google. I didn't find any api to change that appearance. But you can change the embedded style:

```<code>protected override void OnElementChanged(ElementChangedEventArgs<WebView> e)
{
    base.OnElementChanged(e);

    if (e.NewElement != null)
    {
        var customWebView = Element as CustomWebView;
        Control.Settings.AllowUniversalAccessFromFileURLs = true;
        Control.LoadUrl("https://drive.google.com/viewerng/viewer?embedded=true&url=" + customWebView.Uri);
    }
}
</code>```

It shows a light gray border when we set the embedded to true.

You have to create a custom control on Forms for consuming the custom renderer above:

```<code>public class CustomWebView : WebView
{
    public static readonly BindableProperty UriProperty = BindableProperty.Create(propertyName: "Uri",
            returnType: typeof(string),
            declaringType: typeof(CustomWebView),
            defaultValue: default(string));

    public string Uri
    {
        get { return (string)GetValue(UriProperty); }
        set { SetValue(UriProperty, value); }
    }
}
</code>```

At last, use it in XAML:

```<code><StackLayout>
    <local:CustomWebView VerticalOptions="FillAndExpand" Uri="http://www.africau.edu/images/default/sample.pdf" />
</StackLayout>
</code>```

Update:

It can scroll if pdf has couples of pages:

Body:
Did you use Google doc viewer to load the remote pdf files? If so, the extra border can't be removed as it is controlled by Google. I didn't find any api to change that appearance. But you can change the embedded style:

protected override void OnElementChanged(ElementChangedEventArgs<WebView> e)
{
    base.OnElementChanged(e);

    if (e.NewElement != null)
    {
        var customWebView = Element as CustomWebView;
        Control.Settings.AllowUniversalAccessFromFileURLs = true;
        Control.LoadUrl("https://drive.google.com/viewerng/viewer?embedded=true&url=" + customWebView.Uri);
    }
}

It shows a light gray border when we set the embedded to true.

You have to create a custom control on Forms for consuming the custom renderer above:

public class CustomWebView : WebView
{
    public static readonly BindableProperty UriProperty = BindableProperty.Create(propertyName: "Uri",
            returnType: typeof(string),
            declaringType: typeof(CustomWebView),
            defaultValue: default(string));

    public string Uri
    {
        get { return (string)GetValue(UriProperty); }
        set { SetValue(UriProperty, value); }
    }
}

At last, use it in XAML:

<StackLayout>
    <local:CustomWebView VerticalOptions="FillAndExpand" Uri="http://www.africau.edu/images/default/sample.pdf" />
</StackLayout>

Update:

It can scroll if pdf has couples of pages:


问:
Python Cookbook recipe9.14 Discussion
When I read Python Cookbook recipe 9.14 discussion, it says that I have to convert the OrderedDict to a dict instance when making the final class object. Do I have to do that or using OrderedDict is ok?

I tried this, pass OrderedDict to type constructor, it doesn't raise any exception

```<code>class OrderedMeta(type):
    def __new__(cls, clsname, bases, attr_dict):
        order = []
        for name, value in attr_dict.items():
            if isinstance(value, Typed):
                value._name = name
                order.append(name)
        attr_dict['_order'] = order
        return type.__new__(cls, clsname, bases, attr_dict)

    @classmethod
    def __prepare__(cls, clsname, bases):
        return OrderedDict()
</code>```

code from book

```<code>class OrderedMeta(type):
    def __new__(cls, clsname, bases, attr_dict):
        d = dict(attr_dict)
        order = []
        for name, value in attr_dict.items():
            if isinstance(value, Typed):
                value._name = name
                order.append(name)
        d['_order'] = order
        return type.__new__(cls, clsname, bases, d)

    @classmethod
    def __prepare__(cls, clsname, bases):
        return OrderedDict()
</code>```

enter image description here

答:
You have to do that, for some reasons that David Beasley did not elaborate on further than saying that

"it may cause problems if you don't"

in his 2013 tutorial Python 3 Metaprogramming, at around 1 Hour and 30 minutes.

Since that tutorial, python 3.6 introduced dictionaries that retain their order, you can therefore, probably, safely ignore the use of an ordereddict for this recipe.

Title: Python Cookbook recipe9.14 Discussion

Body:
When I read Python Cookbook recipe 9.14 discussion, it says that I have to convert the OrderedDict to a dict instance when making the final class object. Do I have to do that or using OrderedDict is ok?

I tried this, pass OrderedDict to type constructor, it doesn't raise any exception

class OrderedMeta(type):
    def __new__(cls, clsname, bases, attr_dict):
        order = []
        for name, value in attr_dict.items():
            if isinstance(value, Typed):
                value._name = name
                order.append(name)
        attr_dict['_order'] = order
        return type.__new__(cls, clsname, bases, attr_dict)

    @classmethod
    def __prepare__(cls, clsname, bases):
        return OrderedDict()

code from book

class OrderedMeta(type):
    def __new__(cls, clsname, bases, attr_dict):
        d = dict(attr_dict)
        order = []
        for name, value in attr_dict.items():
            if isinstance(value, Typed):
                value._name = name
                order.append(name)
        d['_order'] = order
        return type.__new__(cls, clsname, bases, d)

    @classmethod
    def __prepare__(cls, clsname, bases):
        return OrderedDict()

enter image description here


答:
This is the common applicative style pattern:

MyRecord <$> nextRandom
         <*> getCurrentTime
         <*> pure "my comment"
```

Title: How do I use a data constructor on a value wrapped inside an IO monad?


答: return 0 is only relative to the scope of the current function so it will not close the application if it is outside of main.

Title: would return 0 using C++ in a class outside of main close the application?


问:
Split view controller rotation on iPhone 6 Plus
I have a split view controller in landscape mode with two navigation controllers.

This collapses to a single navigation controller in portrait and the detail view controller is pushed from the master.

If I rotate back to landscape when the detail view controller is pushed in portrait I don't understand how to put the detail view controller back into it's own navigation controller.

答: Make the detail have its own navigation controller, like in the Master Detail template. When the split view collapses it calls showViewController on the master navigation controller and when it detects a controller of class UINavigationController it sets allow nested navigation controllers true and hides the navigation bar. This way you get to keep the detail navigation so when you rotate to landscape and separate it can use the existing navigation again.


问:
How to configure TestRestTemplate to use a Keystore?
My project has a series of integration tests that use TestRestTemplate and MockMvc.  These had been passing successfully.

I have now added Spring Boot Starter Security and Spring Security OAuth2 Autoconfigure dependencies to my project.  I have added a custom class that extends WebSecurityConfigurerAdapter to allow open access (for the moment) to my applicaiton.  Here is the class

```<code>@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class WebSecurityConfiguration extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(HttpSecurity httpSecurity) throws Exception {
        httpSecurity
            .authorizeRequests()
            .anyRequest()
            .permitAll();
    }

    @Override
    public void configure(WebSecurity webSecurity) {
        webSecurity
            .ignoring()
            .antMatchers(HttpMethod.OPTIONS, "/**");
    }
}
</code>```

The application also needs to act as an OAuth2 Resource Server so I have also annotated my main class with @EnableResourceServer.  I provide the path to the trusted key store as run parameters when running the application.  -Djavax.net.ssl.trustStore=<where the cert is stored locally> -Djavax.net.ssl.trustStorePassword=<the password>

The application works fine but now all of the integration tests are failing.  Here is an example of the error common to all the tests that use the TestRestTemplate

```<code>Could not fetch user details: class org.springframework.web.client.ResourceAccessException, I/O error on GET request for <the path to my userinfo URL>:
PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException:
unable to find valid certification path to requested target; nested exception is javax.net.ssl.SSLHandshakeException:
PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target
</code>```

It seems that the TestRestTemplate I am using for my tests needs to be instructed to use the same keystore that the application does.  Is it possible to do this?  How would it work for MockMvc?

答:
I think you may also need to pass -Djavax.net.ssl.trustStore= -Djavax.net.ssl.trustStorePassword=
parameters while running tests.
For running single test pass arguments in configuration and in maven also you can pass these parameters.

Below two links might help

Specifying trust store information in spring boot application.properties

http://codeboarding.com/tag/testresttemplate/

Body:
My project has a series of integration tests that use TestRestTemplate and MockMvc.  These had been passing successfully.

I have now added Spring Boot Starter Security and Spring Security OAuth2 Autoconfigure dependencies to my project.  I have added a custom class that extends WebSecurityConfigurerAdapter to allow open access (for the moment) to my applicaiton.  Here is the class

@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class WebSecurityConfiguration extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(HttpSecurity httpSecurity) throws Exception {
        httpSecurity
            .authorizeRequests()
            .anyRequest()
            .permitAll();
    }

    @Override
    public void configure(WebSecurity webSecurity) {
        webSecurity
            .ignoring()
            .antMatchers(HttpMethod.OPTIONS, "/**");
    }
}

The application also needs to act as an OAuth2 Resource Server so I have also annotated my main class with @EnableResourceServer.  I provide the path to the trusted key store as run parameters when running the application.  -Djavax.net.ssl.trustStore=<where the cert is stored locally> -Djavax.net.ssl.trustStorePassword=<the password>

The application works fine but now all of the integration tests are failing.  Here is an example of the error common to all the tests that use the TestRestTemplate

Could not fetch user details: class org.springframework.web.client.ResourceAccessException, I/O error on GET request for <the path to my userinfo URL>:
PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException:
unable to find valid certification path to requested target; nested exception is javax.net.ssl.SSLHandshakeException:
PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target

It seems that the TestRestTemplate I am using for my tests needs to be instructed to use the same keystore that the application does.  Is it possible to do this?  How would it work for MockMvc?


问:
How to add values together from a database in windows form application
I'm trying to add all of a students course values together to get the average. The values are saved into a database but when I try add the values together and insert them into a text box it inserts both values into the text box instead of adding the values together.</p>

```<code>            string output = "";
            output += (dr["Course 1"].ToString());
            output += (dr["Course 2"].ToString());
            txtbxaverage.Text = output;

        }
</code>```

答:
When you add 2 strings together, it concatenations them together.

"Hello" + "_World" = "hello_World"

You want:

```<code>string output = "";
output += dr["Course 1"];
output += dr["Course 2"]);
txtbxaverage.Text = output.ToString();
</code>```

You only call "ToString()"  AFTER adding the integers together.

Body:
I'm trying to add all of a students course values together to get the average. The values are saved into a database but when I try add the values together and insert them into a text box it inserts both values into the text box instead of adding the values together.

            string output = "";
            output += (dr["Course 1"].ToString());
            output += (dr["Course 2"].ToString());
            txtbxaverage.Text = output;

        }

Body:
When you add 2 strings together, it concatenations them together.

"Hello" + "_World" = "hello_World"

You want:

string output = "";
output += dr["Course 1"];
output += dr["Course 2"]);
txtbxaverage.Text = output.ToString();

You only call "ToString()"  AFTER adding the integers together.


问:
Change Color of Selected Value in UIPickerView Swift
I have UIPickerView to display names using names Array

The first element of the array is default value "Select Name"

I want to display selected value in Gary color and rest of names in blue color

this func used to prevent selecting the default value:

```<code>func pickerView(pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
    if row == 0 {
        pickerView.selectRow(row+1, inComponent: component, animated: true)
        selectedName = names[row+1]
    } else {
        selectedName = names[row]
    }
}
</code>```

and this func to change color

```<code>func pickerView(pickerView: UIPickerView, viewForRow row: Int, forComponent component: Int, reusingView view: UIView?) -> UIView {
    let pickerLabel = UILabel()
    pickerLabel.textColor = (row == pickerView.selectedRowInComponent(component)) ? UIColor.grayColor() : UIColor.blueColor()
    pickerLabel.text = names[row].name
    pickerLabel.textAlignment = NSTextAlignment.Center
    return pickerLabel
}
</code>```

The problem is when I select the first value of the picker (not the default value), the color remains blue. All other items are working correctly (their color change to gray when I select them)

答:
I do this just before returning the value on pickerView viewForRow or pickerView attributedTitleForRow:

```<code>DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 0.1, execute: {
  pickerView.reloadAllComponents() // hack to refresh all values while scrolling
})
</code>```

It's hacky but it works good enough for me. I hope it helps :)

Body:
I have UIPickerView to display names using names Array

The first element of the array is default value "Select Name"

I want to display selected value in Gary color and rest of names in blue color

this func used to prevent selecting the default value:

func pickerView(pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
    if row == 0 {
        pickerView.selectRow(row+1, inComponent: component, animated: true)
        selectedName = names[row+1]
    } else {
        selectedName = names[row]
    }
}

and this func to change color

func pickerView(pickerView: UIPickerView, viewForRow row: Int, forComponent component: Int, reusingView view: UIView?) -> UIView {
    let pickerLabel = UILabel()
    pickerLabel.textColor = (row == pickerView.selectedRowInComponent(component)) ? UIColor.grayColor() : UIColor.blueColor()
    pickerLabel.text = names[row].name
    pickerLabel.textAlignment = NSTextAlignment.Center
    return pickerLabel
}

The problem is when I select the first value of the picker (not the default value), the color remains blue. All other items are working correctly (their color change to gray when I select them)

Body:
I do this just before returning the value on pickerView viewForRow or pickerView attributedTitleForRow:

DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 0.1, execute: {
  pickerView.reloadAllComponents() // hack to refresh all values while scrolling
})

It's hacky but it works good enough for me. I hope it helps :)


问:
Dealing with Transaction (Process ID X) was deadlocked on lock
I get the following error message on a query on SQL Server 2016 - ADO.NET Connection

Exception message: Transaction (Process ID 358) was deadlocked on lock | communication buffer resources with another process and has been chosen as the deadlock victim. Rerun the transaction.

```<code>SELECT * FROM Table2 WHERE EXISTS (
                       SELECT * FROM Table1
                      WHERE Id = '1234'
                      AND SourceId = Table1.[Id]);
</code>```

What could be possibly causing the issue ?

What is the scope of the shared/read lock that gets created when this query is run ?   ie, is the shared lock applied on entire Table2 or just the rows in the result set ? (I am asking this because this looks like a correlated subquery)

Will refactoring this to INNER JOIN will help?

```<code>SELECT t2.* FROM Table2 t2
INNER JOIN  Table1 t1
ON t2.SourceId = b.Id
WHERE t1.Id = '1234'
</code>```

From logs I not see any other update statements updating the result set(or the table) +/- 10 seconds when error occurred.

So will multiple users running the same query create deadlock ? (there are no non clustered index on the table)

Will speeding up the query using indexing strategy help with deadlock situation ?
Table has 2 Million records and is not indexed properly (it just has a primary key (not SourceId )). I see an Index scan in the execution plan. Hence adding a non clustered index on SourceId covering  other columns help ?
I see that this will require additional 400 MB on space for index data structure. So I would not ideally want to do it.
Will adding a non clustered index on SourceId (not covering index) help ?(due to space constrains)

Default Isolation level for our application is Repeated Read. Will relaxing the isolation level by using WITH (NOLOCK) help ?

How do I know which is the other SQL statement which is conflicting with this ? Is it OK to run SQL Profiler in Production database to generate the DeadLock graph ?

What else is recommended to identify and fix the issue ?

答: reducing isolation level does not help with locked user.. but helps the other users whom uses locked tables.. reducing isolation level to Read Uncommitted does same effect with No Lock statements in each table.</p>

Body:
I get the following error message on a query on SQL Server 2016 - ADO.NET Connection

Exception message: Transaction (Process ID 358) was deadlocked on lock | communication buffer resources with another process and has been chosen as the deadlock victim. Rerun the transaction.

SELECT * FROM Table2 WHERE EXISTS (
                       SELECT * FROM Table1
                      WHERE Id = '1234'
                      AND SourceId = Table1.[Id]);

What could be possibly causing the issue ?

What is the scope of the shared/read lock that gets created when this query is run ?   ie, is the shared lock applied on entire Table2 or just the rows in the result set ? (I am asking this because this looks like a correlated subquery)

Will refactoring this to INNER JOIN will help?

SELECT t2.* FROM Table2 t2
INNER JOIN  Table1 t1
ON t2.SourceId = b.Id
WHERE t1.Id = '1234'

From logs I not see any other update statements updating the result set(or the table) +/- 10 seconds when error occurred.

So will multiple users running the same query create deadlock ? (there are no non clustered index on the table)

Will speeding up the query using indexing strategy help with deadlock situation ?
Table has 2 Million records and is not indexed properly (it just has a primary key (not SourceId )). I see an Index scan in the execution plan. Hence adding a non clustered index on SourceId covering  other columns help ?
I see that this will require additional 400 MB on space for index data structure. So I would not ideally want to do it.
Will adding a non clustered index on SourceId (not covering index) help ?(due to space constrains)

Default Isolation level for our application is Repeated Read. Will relaxing the isolation level by using WITH (NOLOCK) help ?

How do I know which is the other SQL statement which is conflicting with this ? Is it OK to run SQL Profiler in Production database to generate the DeadLock graph ?

What else is recommended to identify and fix the issue ?


问:
How to handle logical OR operation from cucumber step in java
I have a Cucumber step which I want to perform depending on the statement passed in Cucumber step

```<code>verify word does exists in log
clear the logs
</code>```

or I may pass

```<code>verify word does not exists in log
not clear the logs
</code>```

and Gherkin for this would be

```<code>("^verify word does(not|) exists in log$")
("^(|not )clear the logs$")
</code>```

Can I handle this in Java?

I want to perform action depending up on the key I pass

答:
I found the solution,  I have done it in Java as below</p>

```<code> @Then("^verify word does(not|) exists in log$")
    public void verifyLogs(String action) {

        switch statement
        code logic

//or
        if(action.contains("not")){
            code logic
        }
}
</code>```

Body:
I have a Cucumber step which I want to perform depending on the statement passed in Cucumber step

verify word does exists in log
clear the logs

or I may pass

verify word does not exists in log
not clear the logs

and Gherkin for this would be

("^verify word does(not|) exists in log$")
("^(|not )clear the logs$")

Can I handle this in Java?

I want to perform action depending up on the key I pass

Body:
I found the solution,  I have done it in Java as below

 @Then("^verify word does(not|) exists in log$")
    public void verifyLogs(String action) {

        switch statement
        code logic

//or
        if(action.contains("not")){
            code logic
        }
}


问:
is there a function readDir, how to access the value in the other file?
I divided the code into parts of Main.cs and readDirectory.cs. How to return the result from readDir functions in readDirectory.cs to Main.cs?  Below is readDirectory.cs code</p>

```<code>class ReadDirectory
{
    public static string[] readDir()
    {

         string textFile = @"C:\Users\Nurgaliev.IA\source\repos\ConsoleApp3\ConsoleApp3\bin\Debug\paths.txt";
        string[] lines = null;

        if (File.Exists(textFile))
        {
           lines = File.ReadAllLines(textFile);
        }
        return lines;
    }
</code>```

答:
You need to call the function readDir() of  readDirectory.cs from Main.cs

Try this inside Main.cs:

```<code>string[] TextInFile= ReadDirectory.readDir();
</code>```

As it is static function so just call it directly using its class name.

Body:
I divided the code into parts of Main.cs and readDirectory.cs. How to return the result from readDir functions in readDirectory.cs to Main.cs?  Below is readDirectory.cs code

class ReadDirectory
{
    public static string[] readDir()
    {

         string textFile = @"C:\Users\Nurgaliev.IA\source\repos\ConsoleApp3\ConsoleApp3\bin\Debug\paths.txt";
        string[] lines = null;

        if (File.Exists(textFile))
        {
           lines = File.ReadAllLines(textFile);
        }
        return lines;
    }

Body:
You need to call the function readDir() of  readDirectory.cs from Main.cs

Try this inside Main.cs:

string[] TextInFile= ReadDirectory.readDir();

As it is static function so just call it directly using its class name.


问:
Check battery level of connected bluetooth device on linux
How can I check the battery level of a connected bluetooth device? The device shows the battery level on Android so I'm assuming the device supports the GATT-based Battery Service. However, by entering "menu gatt" in bluetoothctl and then listing the GATT attributes of the device with "list-attributes [dev]", nothing shows up.

A similar question was posted to SO but the OP seems to have found a solution that doesn't work for me. When I run "info [dev]" in bluetoothctl I don't see the UUID for Battery Service.

I would prefer a solution that runs on the command line and is distro-agnostic.

Please let me know if this question should be posted on SuperUser instead.

答:
Here is a way to get battery level via pulseaudio logs with some hack.
My bluetooth headset uses proprietary Apple HFP AT commands, HFP/A2DP protocols are handled by pulseaudio directly. It seems the only way to get those values is through pulse.</p>


问:
Upload a product image using PrestaShop Web-service with Node
I'm trying to upload a Product image using the PrestaShop Web-service.

It is always returning the same error:

  <?xml version="1.0" encoding="UTF-8"?>
  <prestashop xmlns:xlink="http://www.w3.org/1999/xlink">
    <errors>
      <error>
        <![CDATA[66]]>
        <message><![CDATA[Unable to save this image]]></message>
      </error>
    </errors>
  </prestashop>
```

<p><strong>My current code looks like this:</strong></p>

<pre class="lang-js prettyprint-override"><code>const url = this.options.url
    + '/api/images/products/'
    + piezaSchema.querySelector('product>id').childNodes[0].nodeValue
    + '?ws_key='
    + this.options.api;

const file = require('fs').readFileSync(require('path')
        .resolve(this.options.ruta
            + '/images/'
            + image.getAttribute('fichero')));

const resp = await fetch(url, {
    method: 'POST',
    body: 'image=' + file,
    headers: {
        'Content-Type': 'application/x-www-form-urlencoded'
    }
});
</code>```

I've tried with different encoding options, sending as 'Content-Type': 'image/jpeg', etc.

Thank you all for your time.

答:
I've been able to fix by sending the image as if it were uploaded by a form:</p>

```<code>async uploadImage(fichero, url) {

    const form = new FormData();

    const filePath = require('path').resolve(this.options.ruta + '/images/' + fichero);

    const file = new File([await fetch(filePath).then(r => r.blob())], fichero, {type: 'image/jpeg'});

    form.append('image', file);

    const options = {
        method: 'POST',
        body: form
    };

    fetch(url, options);

}
</code>```

Body:
I'm trying to upload a Product image using the PrestaShop Web-service.

It is always returning the same error:

  <?xml version="1.0" encoding="UTF-8"?>
  <prestashop xmlns:xlink="http://www.w3.org/1999/xlink">
    <errors>
      <error>
        <![CDATA[66]]>
        <message><![CDATA[Unable to save this image]]></message>
      </error>
    </errors>
  </prestashop>

My current code looks like this:

const url = this.options.url
    + '/api/images/products/'
    + piezaSchema.querySelector('product>id').childNodes[0].nodeValue
    + '?ws_key='
    + this.options.api;

const file = require('fs').readFileSync(require('path')
        .resolve(this.options.ruta
            + '/images/'
            + image.getAttribute('fichero')));

const resp = await fetch(url, {
    method: 'POST',
    body: 'image=' + file,
    headers: {
        'Content-Type': 'application/x-www-form-urlencoded'
    }
});

I've tried with different encoding options, sending as 'Content-Type': 'image/jpeg', etc.

Thank you all for your time.

Body:
I've been able to fix by sending the image as if it were uploaded by a form:

async uploadImage(fichero, url) {

    const form = new FormData();

    const filePath = require('path').resolve(this.options.ruta + '/images/' + fichero);

    const file = new File([await fetch(filePath).then(r => r.blob())], fichero, {type: 'image/jpeg'});

    form.append('image', file);

    const options = {
        method: 'POST',
        body: form
    };

    fetch(url, options);

}


答:
That's execalty what happened back in the time with Spotify. The result ? With a little script, you could have spotify premium for free.

My point is, that you should not store sensitive data in the client side, and if you do so and use it, there should be a doucble checking (one from the client, one from the server) : if the user changes the values of the client, the server will check the validity of the requests anyway, and  refuse resources to the user.

To finish, my point is that you don't need to encrypt your data, or to stop using local storage : just be clever and double-check the user permissions.

Title: How to use localStorage Carefully in Angular

Body:
Since localStorage data can be changed easily, how can we make access controls and more things secure in the Angular App.

Suppose our localstorage contains:

data - {name:user, account_status:inactive,...}

The user can easily change the account_status from inactive to active and get all access.
I am not just concerned about access control but also the other localstorage data which is used in angular.

Can I encrypt the data from the node server and store it in localstorage and decrypt it back when i want to use with the same secret key. Will this have some adverse effects.

Please suggest some methods which can be used.


问:
Protobuf how to change inheritance hierarchy without losing backward compatibility
I have a specific use-case for inheritance using protobuf-net which I don't know (if possible) how to handle.

Let's say we have these sample classes (label this as Version 1):

```<code>public class FooA
{
    public double A { get; set; }
    public double B { get; set; }
}

public class FooB : FooA
{
    public double C { get; set; }
}

public class FooC : FooB
{
}

public class FooD : FooC
{
    public double D { get; set; }
}

public class FooA1 : FooA
{
}
</code>```

With the below protobuf's model definition:

```<code>        Model = RuntimeTypeModel.Create();

        Model.Add(typeof(FooA), false)
            .AddSubType(201, typeof(FooB))
            .AddSubType(202, typeof(FooA1))
            .Add(1, "A")
            .Add(2, "B");

        Model[typeof(FooB)]
            .AddSubType(201, typeof(FooC))
            .Add(1, "C");

        Model[typeof(FooC)]
            .AddSubType(201, typeof(FooD));

        Model[typeof(FooD)]
            .Add(1, "D");
</code>```

I serialize them as following

```<code>        FooA a = new FooA() {A = 10, B = 20};
        FooB b = new FooB() {A = 10, B = 20, C = 30};
        FooA1 b1 = new FooA1() {A = 100, B = 200};
        FooC c = new FooC() {A = 10, B = 20, C = 30};
        FooD d = new FooD() {A = 10, B = 20, C = 30, D = 40};

        using (var stream = File.Open(fileName, FileMode.Create, FileAccess.Write))
        {
            SerializeWithLengthPrefix(stream, a);
            SerializeWithLengthPrefix(stream, b);
            SerializeWithLengthPrefix(stream, b1);
            SerializeWithLengthPrefix(stream, c);
            SerializeWithLengthPrefix(stream, d);
        }
</code>```

Helper Methods

```<code>    public void SerializeWithLengthPrefix<T>(Stream stream, T obj)
    {
        var serializationContext = new ProtoBuf.SerializationContext() { Context = this };
        Model.SerializeWithLengthPrefix(stream, obj, typeof(T), PrefixStyle.Base128, 1, serializationContext);
    }

    public T DeserializeWithLengthPrefix<T>(Stream stream, out long bytesRead, out bool haveObject)
    {
        var serializationContext = new ProtoBuf.SerializationContext() { Context = this };

        return (T)Model.DeserializeWithLengthPrefix(stream, null, typeof(T), PrefixStyle.Base128, 1, null, out bytesRead, out haveObject, serializationContext);
    }
</code>```

Now I need to change the inheritance hierarchy in this way (label this as Version 2):

```<code>public class FooA
{
    public double A { get; set; }
    public double B { get; set; }
}

public class FooB : FooA
{
    public double C { get; set; }
}

public class FooC : FooA1/*FooB*/
{
    public double C { get; set; }
}

public class FooD : FooC
{
    public double D { get; set; }
}

public class FooA1 /*: FooA*/
{
    public double A { get; set; }
    public double B { get; set; }
}
</code>```

And also Model definition according to it, trying to preserve the same id for each class defined previously.

```<code>       Model = RuntimeTypeModel.Create();

        Model.Add(typeof(FooA), false)
            .AddSubType(201, typeof(FooB))
            //.AddSubType(202, typeof(FooA1))
            .Add(1, "A")
            .Add(2, "B");

        Model.Add(typeof(FooA1), false)
            .Add(1, "A")
            .Add(2, "B");

        Model[typeof(FooB)]
            //.AddSubType(201, typeof(FooC))
            .Add(1, "C");

        Model[typeof(FooA1)]
            .AddSubType(201, typeof(FooC));

        Model[typeof(FooC)]
            .Add(1, "C")
            .AddSubType(201, typeof(FooD));

        Model[typeof(FooD)]
            .Add(1, "D");
</code>```

Now I deserialize the file stored with Version 1 and I check for types defined in the model: they're the same than the one during serialization with Version 1.

But when I check for objects values I see that FooC has been deserialized as FooD and D value is always equal to 0.

What am I doing wrong? Is there a way to handle this?

UPDATE

Trying to debug the protobuf-net source code when FooC is deserialized with Version 2, the method RuntimeTypeModel.GetKey() starts from the base class (getBaseKey=true), correctly gets FooA1 (key=2) but finally it gets FooD object instead of FooC. Maybe is there a way to handle this method in a different way to allow a scenario like this?

答:
I can't think of a way of making that change without breaking compatibility. My advice when we anyone gets tied into a knot: split the "real" types and the serialization types apart into separate type models that don't need to be a 1:1 map to each-other. Then you can do whatever you want to the "real" types (the domain model), and you just project those values into the serialization model, which might have different rules and be more convenient for the serializer. In this case, the serialization types might not be a 1:1 map in terms of the inheritance tree.

The other option is to forcibly migrate the old data, so: deserialize it with the old layout, and re-serialize it with the new layout. This is embracing the inheritance change, rather than trying to pretend it didn't happen.

The following is to show the resultant .proto layout to explain why FooC ends up as FooD in v2:

v1 starting from FooA - FooC is 201, 201 (FooD is 201, 201, 201)

syntax = "proto2";

message FooA {
   optional double A = 1;
   optional double B = 2;
   oneof subtype {
      FooB FooB = 201;
      FooA1 FooA1 = 202;
   }
}
message FooA1 {
}
message FooB {
   optional double C = 1;
   oneof subtype {
      FooC FooC = 201;
   }
}
message FooC {
   oneof subtype {
      FooD FooD = 201;
   }
}
message FooD {
   optional double D = 1;
}
```

<p>v2 starting from <code>FooA1</code> - <code>FooD</code> is 201, 201:</p>

<pre class="lang-proto prettyprint-override"><code>syntax = "proto2";

message FooA1 {
   optional double A = 1;
   optional double B = 2;
   oneof subtype {
      FooC FooC = 201;
   }
}
message FooC {
   optional double C = 1;
   oneof subtype {
      FooD FooD = 201;
   }
}
message FooD {
   optional double D = 1;
}
</code>```

Body:
I have a specific use-case for inheritance using protobuf-net which I don't know (if possible) how to handle.

Let's say we have these sample classes (label this as Version 1):

public class FooA
{
    public double A { get; set; }
    public double B { get; set; }
}

public class FooB : FooA
{
    public double C { get; set; }
}

public class FooC : FooB
{
}

public class FooD : FooC
{
    public double D { get; set; }
}

public class FooA1 : FooA
{
}

With the below protobuf's model definition:

        Model = RuntimeTypeModel.Create();

        Model.Add(typeof(FooA), false)
            .AddSubType(201, typeof(FooB))
            .AddSubType(202, typeof(FooA1))
            .Add(1, "A")
            .Add(2, "B");

        Model[typeof(FooB)]
            .AddSubType(201, typeof(FooC))
            .Add(1, "C");

        Model[typeof(FooC)]
            .AddSubType(201, typeof(FooD));

        Model[typeof(FooD)]
            .Add(1, "D");

I serialize them as following

        FooA a = new FooA() {A = 10, B = 20};
        FooB b = new FooB() {A = 10, B = 20, C = 30};
        FooA1 b1 = new FooA1() {A = 100, B = 200};
        FooC c = new FooC() {A = 10, B = 20, C = 30};
        FooD d = new FooD() {A = 10, B = 20, C = 30, D = 40};

        using (var stream = File.Open(fileName, FileMode.Create, FileAccess.Write))
        {
            SerializeWithLengthPrefix(stream, a);
            SerializeWithLengthPrefix(stream, b);
            SerializeWithLengthPrefix(stream, b1);
            SerializeWithLengthPrefix(stream, c);
            SerializeWithLengthPrefix(stream, d);
        }

Helper Methods

    public void SerializeWithLengthPrefix<T>(Stream stream, T obj)
    {
        var serializationContext = new ProtoBuf.SerializationContext() { Context = this };
        Model.SerializeWithLengthPrefix(stream, obj, typeof(T), PrefixStyle.Base128, 1, serializationContext);
    }

    public T DeserializeWithLengthPrefix<T>(Stream stream, out long bytesRead, out bool haveObject)
    {
        var serializationContext = new ProtoBuf.SerializationContext() { Context = this };

        return (T)Model.DeserializeWithLengthPrefix(stream, null, typeof(T), PrefixStyle.Base128, 1, null, out bytesRead, out haveObject, serializationContext);
    }

Now I need to change the inheritance hierarchy in this way (label this as Version 2):

public class FooA
{
    public double A { get; set; }
    public double B { get; set; }
}

public class FooB : FooA
{
    public double C { get; set; }
}

public class FooC : FooA1/*FooB*/
{
    public double C { get; set; }
}

public class FooD : FooC
{
    public double D { get; set; }
}

public class FooA1 /*: FooA*/
{
    public double A { get; set; }
    public double B { get; set; }
}

And also Model definition according to it, trying to preserve the same id for each class defined previously.

       Model = RuntimeTypeModel.Create();

        Model.Add(typeof(FooA), false)
            .AddSubType(201, typeof(FooB))
            //.AddSubType(202, typeof(FooA1))
            .Add(1, "A")
            .Add(2, "B");

        Model.Add(typeof(FooA1), false)
            .Add(1, "A")
            .Add(2, "B");

        Model[typeof(FooB)]
            //.AddSubType(201, typeof(FooC))
            .Add(1, "C");

        Model[typeof(FooA1)]
            .AddSubType(201, typeof(FooC));

        Model[typeof(FooC)]
            .Add(1, "C")
            .AddSubType(201, typeof(FooD));

        Model[typeof(FooD)]
            .Add(1, "D");

Now I deserialize the file stored with Version 1 and I check for types defined in the model: they're the same than the one during serialization with Version 1.

But when I check for objects values I see that FooC has been deserialized as FooD and D value is always equal to 0.

What am I doing wrong? Is there a way to handle this?

UPDATE

Trying to debug the protobuf-net source code when FooC is deserialized with Version 2, the method RuntimeTypeModel.GetKey() starts from the base class (getBaseKey=true), correctly gets FooA1 (key=2) but finally it gets FooD object instead of FooC. Maybe is there a way to handle this method in a different way to allow a scenario like this?

Body:
I can't think of a way of making that change without breaking compatibility. My advice when we anyone gets tied into a knot: split the "real" types and the serialization types apart into separate type models that don't need to be a 1:1 map to each-other. Then you can do whatever you want to the "real" types (the domain model), and you just project those values into the serialization model, which might have different rules and be more convenient for the serializer. In this case, the serialization types might not be a 1:1 map in terms of the inheritance tree.

The other option is to forcibly migrate the old data, so: deserialize it with the old layout, and re-serialize it with the new layout. This is embracing the inheritance change, rather than trying to pretend it didn't happen.

The following is to show the resultant .proto layout to explain why FooC ends up as FooD in v2:

v1 starting from FooA - FooC is 201, 201 (FooD is 201, 201, 201)

syntax = "proto2";

message FooA {
   optional double A = 1;
   optional double B = 2;
   oneof subtype {
      FooB FooB = 201;
      FooA1 FooA1 = 202;
   }
}
message FooA1 {
}
message FooB {
   optional double C = 1;
   oneof subtype {
      FooC FooC = 201;
   }
}
message FooC {
   oneof subtype {
      FooD FooD = 201;
   }
}
message FooD {
   optional double D = 1;
}

v2 starting from FooA1 - FooD is 201, 201:

syntax = "proto2";

message FooA1 {
   optional double A = 1;
   optional double B = 2;
   oneof subtype {
      FooC FooC = 201;
   }
}
message FooC {
   optional double C = 1;
   oneof subtype {
      FooD FooD = 201;
   }
}
message FooD {
   optional double D = 1;
}


问:
how to filter all string sequence in array using javascript
I have a large array, and I want to filter it based on a string I pass it. This string could be one or two characters, up to an entire string.

Here's an example array:

```<code>var data = ["bourbon", "beer", "electric"]
</code>```

If I pass e, I want the result ["electric", "beer"].

How can I achieve this functionality?

答:
you can use underscore.

var data = ["bourbon","beer", "electric"]
var filtered = [];
var filter = function(value) {
  filtered = _.filter(data, function(el) {
    return el.indexOf(value)
  })
  return filtered;
}

console.log('filtered',filter('e'));```

Body:
I have a large array, and I want to filter it based on a string I pass it. This string could be one or two characters, up to an entire string.

Here's an example array:

var data = ["bourbon", "beer", "electric"]

If I pass e, I want the result ["electric", "beer"].

How can I achieve this functionality?


问:
reduce es6 missing nested array of object using spread
I've got a problem merging 2 sets of data by a condition. I've debugged for more than an hour but couldn't figure out why. I've created a sample below.

I have these 2 data:

```<code>const staticRockData = {
    rockTypes: [
      {
        supplierRockTypes: [
          {
            rockCodes: ["1"],
            match_id: "abc"
          },
          {
            rockCodes: ["2"],
            match_id: "abc"
          }
        ]
      }
    ]
  };

  const gatewayRockData = {
    match_id: "abc",
    rocks: [{ rock_type: "1", rates: [] }, { rock_type: "2", rates: [] }]
  };
</code>```

I have this mapping logic:

```<code>let rockTypes = staticRockData.rockTypes;

  rockTypes = rockTypes.reduce((accum, rockType) => {
    const matchedSourceId = rockType.supplierRockTypes.some(
      o2 => o2.match_id === gatewayRockData.match_id
    );
    if (matchedSourceId) {
      gatewayRockData.rocks.forEach(rock => {
        const matchRockType = rockType.supplierRockTypes.some(o2 => {
          return o2.rockCodes.includes(rock.rock_type);
        });

        if (matchRockType) {
          console.log("rock.rock_type", rock.rock_type);
          rockType = {
            ...rockType,
            rock_type: rock.rock_type,
            rates: rock.rates
          };
        }
      });
    }

    accum = [...accum, { ...omit(rockType, "supplierRockTypes") }];

    return accum;
  }, []);

  return {
    rocks: rockTypes
  };
</code>```

and I expected this:

```<code>rocks: [
       {
         rates: [],
         rock_type: "1"
       },
       {
         rates: [],
         rock_type: "2"
       }
     ]
   }
</code>```

The current solution is missing this:

{ rates: [], rock_type: "1"}, I wonder where my mistake is.

Omit is lodash's omit function, but I don't think that's the culprit. I created a demo here:

https://codesandbox.io/s/condescending-platform-1jp9l?fontsize=14&previewwindow=tests

答:
I don't know your exact requirement but I found out what is causing the issue
The problem is in your reducer's forEach, which is fixed in version below:

```<code>rockTypes = rockTypes.reduce((accum, rockType) => {
    const matchedSourceId = rockType.supplierRockTypes.some(
      o2 => o2.match_id === gatewayRockData.match_id
    );
    if (matchedSourceId) {
      gatewayRockData.rocks.forEach(rock => {
        const matchRockType = rockType.supplierRockTypes.some(o2 => {
          return o2.rockCodes.includes(rock.rock_type);
        });

        if (matchRockType) {
          accum = [...accum, { rock_type: rock.rock_type,
            rates: rock.rates }];;
        }
      });
    }

    return accum;
  }, []);
</code>```

More specifically line below in forEach:

```<code>if (matchRockType) {
          rockType = {
            ...rockType,
            rock_type: rock.rock_type,
            rates: rock.rates
          };
        }
</code>```

Every time loop runs and it found match your it replaces your rockType content as it is an object not an array.

other solution takes an empty array outside forEach and push the contents in the inside if condition and spread it while returning.

Just saying you should consider refactoring your code.

Body:
I've got a problem merging 2 sets of data by a condition. I've debugged for more than an hour but couldn't figure out why. I've created a sample below.

I have these 2 data:

const staticRockData = {
    rockTypes: [
      {
        supplierRockTypes: [
          {
            rockCodes: ["1"],
            match_id: "abc"
          },
          {
            rockCodes: ["2"],
            match_id: "abc"
          }
        ]
      }
    ]
  };

  const gatewayRockData = {
    match_id: "abc",
    rocks: [{ rock_type: "1", rates: [] }, { rock_type: "2", rates: [] }]
  };

I have this mapping logic:

let rockTypes = staticRockData.rockTypes;

  rockTypes = rockTypes.reduce((accum, rockType) => {
    const matchedSourceId = rockType.supplierRockTypes.some(
      o2 => o2.match_id === gatewayRockData.match_id
    );
    if (matchedSourceId) {
      gatewayRockData.rocks.forEach(rock => {
        const matchRockType = rockType.supplierRockTypes.some(o2 => {
          return o2.rockCodes.includes(rock.rock_type);
        });

        if (matchRockType) {
          console.log("rock.rock_type", rock.rock_type);
          rockType = {
            ...rockType,
            rock_type: rock.rock_type,
            rates: rock.rates
          };
        }
      });
    }

    accum = [...accum, { ...omit(rockType, "supplierRockTypes") }];

    return accum;
  }, []);

  return {
    rocks: rockTypes
  };

and I expected this:

rocks: [
       {
         rates: [],
         rock_type: "1"
       },
       {
         rates: [],
         rock_type: "2"
       }
     ]
   }

The current solution is missing this:

{ rates: [], rock_type: "1"}, I wonder where my mistake is.

Omit is lodash's omit function, but I don't think that's the culprit. I created a demo here:

https://codesandbox.io/s/condescending-platform-1jp9l?fontsize=14&previewwindow=tests

Body:
I don't know your exact requirement but I found out what is causing the issue
The problem is in your reducer's forEach, which is fixed in version below:

rockTypes = rockTypes.reduce((accum, rockType) => {
    const matchedSourceId = rockType.supplierRockTypes.some(
      o2 => o2.match_id === gatewayRockData.match_id
    );
    if (matchedSourceId) {
      gatewayRockData.rocks.forEach(rock => {
        const matchRockType = rockType.supplierRockTypes.some(o2 => {
          return o2.rockCodes.includes(rock.rock_type);
        });

        if (matchRockType) {
          accum = [...accum, { rock_type: rock.rock_type,
            rates: rock.rates }];;
        }
      });
    }

    return accum;
  }, []);

More specifically line below in forEach:

if (matchRockType) {
          rockType = {
            ...rockType,
            rock_type: rock.rock_type,
            rates: rock.rates
          };
        }

Every time loop runs and it found match your it replaces your rockType content as it is an object not an array.

other solution takes an empty array outside forEach and push the contents in the inside if condition and spread it while returning.

Just saying you should consider refactoring your code.


答:
rockType is overwritten each repeat of the loop:

```<code>rockType = {
        ...rockType,
        rock_type: rock.rock_type,
        rates: rock.rates
      };
</code>```

You should store the result in another variable this way:

```<code>...
let matchedRockTypes = [];
if (matchedSourceId) {
  gatewayRockData.rocks.forEach(rock => {
    const matchRockType = rockType.supplierRockTypes.some(o2 => {
      return o2.rockCodes.includes(rock.rock_type);
    });

    if (matchRockType) {
      console.log("rock.rock_type", rock.rock_type);
      matchedRockTypes.push({
        rock_type: rock.rock_type,
        rates: rock.rates
      });
    }
  });
}
return matchedRockTypes;
...
</code>```

Here is the result:
https://codesandbox.io/s/tender-ritchie-i0qkt

Title: reduce es6 missing nested array of object using spread

Body:
rockType is overwritten each repeat of the loop:

rockType = {
        ...rockType,
        rock_type: rock.rock_type,
        rates: rock.rates
      };

You should store the result in another variable this way:

...
let matchedRockTypes = [];
if (matchedSourceId) {
  gatewayRockData.rocks.forEach(rock => {
    const matchRockType = rockType.supplierRockTypes.some(o2 => {
      return o2.rockCodes.includes(rock.rock_type);
    });

    if (matchRockType) {
      console.log("rock.rock_type", rock.rock_type);
      matchedRockTypes.push({
        rock_type: rock.rock_type,
        rates: rock.rates
      });
    }
  });
}
return matchedRockTypes;
...

Here is the result:
https://codesandbox.io/s/tender-ritchie-i0qkt


问:
REST Framework for .NET 4.0
I am looking for a simple .NET REST Framework to write a simple web service with.  The web service will be consumed by a Blackberry application, so my requirements aren't too strict hopefully:

Supports custom Basic Authentication (against a database of users)

Supports GET and POST.

Supports both JSON and XML.  (XML is something I am not fussed about, so it's not mandatory)

Supports custom serialization of objects (I have some currently existing POCOs, which are decorated with DataMember attributes, so it would be good to keep using those classes)

Must be simple!

Preferably supports .NET 4.0. (I am not sure if it is possible to run class libraries compiled against .NET 3.5 on 4.0, but if it is, 3.5 would certainly do)

Runs on IIS6.

Of those, the basic authentication one is the major requirement.

I prototyped up a web service using the WCF REST Starter Kit, and it was pretty simple to get up and running, but it's all gone a bit oddly pear-shaped to be honest. Plus, it was only a prototype, and with the starter kit not being developed any more, it would probably be a good idea to re-implement it.

Would something like OpenRasta do the job?

答:
I would definitely give WCF HTTP a shot (it's the latest bits from the WCF team and replaces the old hack-y REST Starter Kit). You can download it from Codeplex at:

WCF Community Site - WCF HTTP

If that doesn't work for you, you could always fall back to ASP.NET MVC and simply return JSON objects from your Action Methods.

Title: REST Framework for .NET 4.0


问:
why resource timing api is giving the encoded , decoded and transfer size of some resources as 0?
I am using resource timing api to capture the encoded, decoded and transfer size of all the resources of a page,but for some of the resources it is giving the zero for all the 3 keys. Please help me to solve this.</p>

答:
it happens for the cross origin resources when the "Timing-Allow-Origin" header is not set by the server and hence wont expose the resource timing values
please go through the specification here

hope this answers your question.


问:
Can C# make use of fused multiply-add?
Does the C# compiler / jitter make use of fused multiply-add operations if they are available on the hardware being used? If it does, are there any particular compiler settings I need to set in order to take advantage of it?</p>

答: At last, .NET Core 3.0 provides System.Math.FusedMultiplyAdd.  The rationale for not using this operation automatically is explained in a github issue.</p>

Title: Can C# make use of fused multiply-add?


问:
How to properly call a variable for Get-WmiObject using a list of computers
I'm trying to determine how to properly call a variable for Get-WmiObject using a list of computers.

No matter what I do I cannot get this code to work.

I have spent a few hours reviewing code to compile the code I have and feel like I'm 90% there but can't get past this last little thing. I'm also new to Powershell but am trying my butt off

```<code>$comp = Import-CSV .\testlist.csv

foreach $comp{

    $cs = Get-CimInstance -ClassName Win32_ComputerSystem -ComputerName $comp
    $bios = Get-CimInstance -ClassName Win32_BIOS -ComputerName $comp
    $tpm = Get-WmiObject -Namespace root\cimv2\security\microsofttpm -Class Win32_Tpm -computername $comp -Authentication PacketPrivacy
    $cos = Get-CimInstance -ClassName Win32_OperatingSystem -computername $comp | select-object Caption, BuildNumber, OSArchitecture

    $properties = [ordered]@{
        'ComputerName' = $comp;
        'Model' = $cs.Model;
        'Operating System' = $cos.Caption
        'OS build' = $cos.BuildNumber
        'OS Type' = $cos.OSArchitecture
        'BIOSVersion' = $bios.SMBIOSBIOSVersion
        'TPM ManufacturerId' = $tpm.ManufacturerId
        'TPM Firmware version' = $tpm.ManufacturerVersion
        'TPM SpecVersion' = $tpm.SpecVersion
        )

}| Export-Csv -Path .\Result.csv -NoTypeInformation
</code>```

Error Message:

New Text Document.ps1:4 char:8
  + foreach $comp{
  +        ~ Missing opening '(' after keyword 'foreach'.

New Text Document.ps1:4 char:14
  + foreach $comp{
  +              ~ Unexpected token '{' in expression or statement.

New Text Document.ps1:22 char:39
  +         'TPM SpecVersion' = $tpm.SpecVersion
  +                                             ~ The hash literal was incomplete.

New Text Document.ps1:4 char:14
  + foreach $comp{
  +              ~ Missing closing '}' in statement block or type definition.

New Text Document.ps1:23 char:3
  +         )
  +         ~ Unexpected token ')' in expression or statement.

New Text Document.ps1:26 char:1
  + }| Export-Csv -Path .\Result.csv -NoTypeInformation
  + ~ Unexpected token '}' in expression or statement.

New Text Document.ps1:26 char:2
  + }| Export-Csv -Path .\Result.csv -NoTypeInformation
  +  ~

An empty pipe element is not allowed.
      + CategoryInfo          : ParserError: (:) [], ParentContainsErrorRecordException
      + FullyQualifiedErrorId : MissingOpenParenthesisAfterKeyword

答:
Some basic things I have changed:

ForEach : if you don't use the () you can loop through the $comp using Foreach-Object:

$comp | ForEach-Object  { write-host "computername: $_ "} .

No ; at the end of the line :)

Pipe every element to export csv and use -append (you were piping the final result)

I prefer to use convertTo-csv | out-file somefile.csv . Export-csv is doing the same but applies some filters on the output that will sometimes make unexpected results

foreach ($c in $comp) {
            $cs = Get-CimInstance -ClassName Win32_ComputerSystem -ComputerName $c
            $bios = Get-CimInstance -ClassName Win32_BIOS -ComputerName $c
            $tpm = Get-WmiObject -Namespace root\cimv2\security\microsofttpm -Class Win32_Tpm -computername $c -Authentication PacketPrivacy
            $cos = Get-CimInstance -ClassName Win32_OperatingSystem -computername $c | select-object Caption, BuildNumber, OSArchitecture
        $properties = [ordered]@{
            'ComputerName'         = $c
            'Model'                = $cs.Model
            'Operating System'     = $cos.Caption
            'OS build'             = $cos.BuildNumber
            'OS Type'              = $cos.OSArchitecture
            'BIOSVersion'          = $bios.SMBIOSBIOSVersion
            'TPM ManufacturerId'   = $tpm.ManufacturerId
            'TPM Firmware version' = $tpm.ManufacturerVersion
            'TPM SpecVersion'      = $tpm.SpecVersion
        }  |
        Export-Csv -Path .\Result.csv -NoTypeInformation
}
```

After the  }  |  there is a back-tick character (  `  ) that tells powershell the line is broken in two . It was messing the formatting, so i removed it, don't forget to put it back.

Body:
I'm trying to determine how to properly call a variable for Get-WmiObject using a list of computers.

No matter what I do I cannot get this code to work.

I have spent a few hours reviewing code to compile the code I have and feel like I'm 90% there but can't get past this last little thing. I'm also new to Powershell but am trying my butt off

$comp = Import-CSV .\testlist.csv

foreach $comp{

    $cs = Get-CimInstance -ClassName Win32_ComputerSystem -ComputerName $comp
    $bios = Get-CimInstance -ClassName Win32_BIOS -ComputerName $comp
    $tpm = Get-WmiObject -Namespace root\cimv2\security\microsofttpm -Class Win32_Tpm -computername $comp -Authentication PacketPrivacy
    $cos = Get-CimInstance -ClassName Win32_OperatingSystem -computername $comp | select-object Caption, BuildNumber, OSArchitecture

    $properties = [ordered]@{
        'ComputerName' = $comp;
        'Model' = $cs.Model;
        'Operating System' = $cos.Caption
        'OS build' = $cos.BuildNumber
        'OS Type' = $cos.OSArchitecture
        'BIOSVersion' = $bios.SMBIOSBIOSVersion
        'TPM ManufacturerId' = $tpm.ManufacturerId
        'TPM Firmware version' = $tpm.ManufacturerVersion
        'TPM SpecVersion' = $tpm.SpecVersion
        )

}| Export-Csv -Path .\Result.csv -NoTypeInformation

Error Message:

New Text Document.ps1:4 char:8
  + foreach $comp{
  +        ~ Missing opening '(' after keyword 'foreach'.

New Text Document.ps1:4 char:14
  + foreach $comp{
  +              ~ Unexpected token '{' in expression or statement.

New Text Document.ps1:22 char:39
  +         'TPM SpecVersion' = $tpm.SpecVersion
  +                                             ~ The hash literal was incomplete.

New Text Document.ps1:4 char:14
  + foreach $comp{
  +              ~ Missing closing '}' in statement block or type definition.

New Text Document.ps1:23 char:3
  +         )
  +         ~ Unexpected token ')' in expression or statement.

New Text Document.ps1:26 char:1
  + }| Export-Csv -Path .\Result.csv -NoTypeInformation
  + ~ Unexpected token '}' in expression or statement.

New Text Document.ps1:26 char:2
  + }| Export-Csv -Path .\Result.csv -NoTypeInformation
  +  ~

An empty pipe element is not allowed.
      + CategoryInfo          : ParserError: (:) [], ParentContainsErrorRecordException
      + FullyQualifiedErrorId : MissingOpenParenthesisAfterKeyword

Body:
Some basic things I have changed:

ForEach : if you don't use the () you can loop through the $comp using Foreach-Object:

$comp | ForEach-Object  { write-host "computername: $_ "} .

No ; at the end of the line :)

Pipe every element to export csv and use -append (you were piping the final result)

I prefer to use convertTo-csv | out-file somefile.csv . Export-csv is doing the same but applies some filters on the output that will sometimes make unexpected results

foreach ($c in $comp) {
            $cs = Get-CimInstance -ClassName Win32_ComputerSystem -ComputerName $c
            $bios = Get-CimInstance -ClassName Win32_BIOS -ComputerName $c
            $tpm = Get-WmiObject -Namespace root\cimv2\security\microsofttpm -Class Win32_Tpm -computername $c -Authentication PacketPrivacy
            $cos = Get-CimInstance -ClassName Win32_OperatingSystem -computername $c | select-object Caption, BuildNumber, OSArchitecture
        $properties = [ordered]@{
            'ComputerName'         = $c
            'Model'                = $cs.Model
            'Operating System'     = $cos.Caption
            'OS build'             = $cos.BuildNumber
            'OS Type'              = $cos.OSArchitecture
            'BIOSVersion'          = $bios.SMBIOSBIOSVersion
            'TPM ManufacturerId'   = $tpm.ManufacturerId
            'TPM Firmware version' = $tpm.ManufacturerVersion
            'TPM SpecVersion'      = $tpm.SpecVersion
        }  |
        Export-Csv -Path .\Result.csv -NoTypeInformation
}

After the  }  |  there is a back-tick character (  `  ) that tells powershell the line is broken in two . It was messing the formatting, so i removed it, don't forget to put it back.


问:
How to convert List<String> to Map<String,List<String>> based on a delimeter
I have a List of String like:

```<code>List<String> locations = Arrays.asList("US:5423","US:6321","CA:1326","AU:5631");
</code>```

And I want to convert in Map<String, List<String>> as like:

```<code>AU = [5631]
CA = [1326]
US = [5423, 6321]
</code>```

I have tried this code and it works but in this case, I have to create a new class GeoLocation.java.

```<code>List<String> locations=Arrays.asList("US:5423", "US:6321", "CA:1326", "AU:5631");
Map<String, List<String>> locationMap = locations
        .stream()
        .map(s -> new GeoLocation(s.split(":")[0], s.split(":")[1]))
        .collect(
                Collectors.groupingBy(GeoLocation::getCountry,
                Collectors.mapping(GeoLocation::getLocation, Collectors.toList()))
        );

locationMap.forEach((key, value) -> System.out.println(key + " = " + value));
</code>```

GeoLocation.java

```<code>private class GeoLocation {
    private String country;
    private String location;

    public GeoLocation(String country, String location) {
        this.country = country;
        this.location = location;
    }

    public String getCountry() {
        return country;
    }

    public void setCountry(String country) {
        this.country = country;
    }

    public String getLocation() {
        return location;
    }

    public void setLocation(String location) {
        this.location = location;
    }
}
</code>```

But I want to know, Is there any way to convert List<String> to Map<String, List<String>> without introducing new class.

答:
What about POJO. It looks not complicated comparing with streams.</p>

```<code>public static Map<String, Set<String>> groupByCountry(List<String> locations) {
    Map<String, Set<String>> map = new HashMap<>();

    locations.forEach(location -> {
        String[] parts = location.split(":");
        map.compute(parts[0], (country, codes) -> {
            codes = codes == null ? new HashSet<>() : codes;
            codes.add(parts[1]);
            return codes;
        });
    });

    return map;
}
</code>```

Body:
I have a List of String like:

List<String> locations = Arrays.asList("US:5423","US:6321","CA:1326","AU:5631");

And I want to convert in Map<String, List<String>> as like:

AU = [5631]
CA = [1326]
US = [5423, 6321]

I have tried this code and it works but in this case, I have to create a new class GeoLocation.java.

List<String> locations=Arrays.asList("US:5423", "US:6321", "CA:1326", "AU:5631");
Map<String, List<String>> locationMap = locations
        .stream()
        .map(s -> new GeoLocation(s.split(":")[0], s.split(":")[1]))
        .collect(
                Collectors.groupingBy(GeoLocation::getCountry,
                Collectors.mapping(GeoLocation::getLocation, Collectors.toList()))
        );

locationMap.forEach((key, value) -> System.out.println(key + " = " + value));

GeoLocation.java

private class GeoLocation {
    private String country;
    private String location;

    public GeoLocation(String country, String location) {
        this.country = country;
        this.location = location;
    }

    public String getCountry() {
        return country;
    }

    public void setCountry(String country) {
        this.country = country;
    }

    public String getLocation() {
        return location;
    }

    public void setLocation(String location) {
        this.location = location;
    }
}

But I want to know, Is there any way to convert List<String> to Map<String, List<String>> without introducing new class.

Body:
What about POJO. It looks not complicated comparing with streams.

public static Map<String, Set<String>> groupByCountry(List<String> locations) {
    Map<String, Set<String>> map = new HashMap<>();

    locations.forEach(location -> {
        String[] parts = location.split(":");
        map.compute(parts[0], (country, codes) -> {
            codes = codes == null ? new HashSet<>() : codes;
            codes.add(parts[1]);
            return codes;
        });
    });

    return map;
}