问:
Compare date values in expression using govaluate
I am trying to build a rule engine using govaluate: https://github.com/Knetic/govaluate

Here is my code:

```<code>package main

import (
    "github.com/Knetic/govaluate"
    "fmt"
)

func main()  {
    expression, err := govaluate.NewEvaluableExpression("first_name == 'Julian' && emp_id == 302 && birth_date >= '2016-12-12' && birth_date <= '2016-12-25'")

    parameters := make(map[string]interface{}, 8)
    parameters["first_name"] = "Julian"
    parameters["emp_id"] = 302
    parameters["birth_date"] = "2016-12-15"
    result, err := expression.Evaluate(parameters)

    if err != nil {
        fmt.Println("Error while evaluating the expression")
    }

    if result.(bool) {
        fmt.Println("Condition is evaluated to true")
    } else {
        fmt.Println("Condition is evaluated to false")
    }
}
</code>```

While browsing through govaluate Types documentation (https://github.com/Knetic/govaluate/blob/master/MANUAL.md), I noticed this statement "Any string literal (not parameter) which is interpretable as a date will be converted to a float64 representation of that date's unix time."

When i execute the above program, i see an issue with result being null:

```<code>Error while evaluating the expression
panic: interface conversion: interface is nil, not bool
</code>```

My question is whether date value can be passed in as a parameter? As i want to compare date values in runtime, this functionality would be needed.

Is there a way to achieve it? May be my usage pattern is wrong. Please suggest.

Edit:

```<code>expression, err := govaluate.NewEvaluableExpression("first_name == 'Julian' && emp_id == 302 && birth_date >= '2016-12-12' && birth_date <= '2016-12-25'")
dateFloat, _ := strconv.ParseFloat("2016-12-15", 64)
parameters["birth_date"] = dateFloat
result, err := expression.Evaluate(parameters)
</code>```

Changed the date to float format and invoked Evaluate function. Now the condition is evaluated to false. But logically,  2016-12-15 falls between 2016-12-12 and 2016-12-25. The expression should be evaluated to true.

Thanks in advance!

答:
Cross-posting my answer from the associated github issue, for future googlers;

The library doesn't try to parse string parameters as dates - it expects that birth_date will be the Unix() value of that date. This means you'll have to parse the date before passing it to govaluate.

If you're getting birth_date as part of a REST api, I'd suggest settling on one specific date format (such as ISO8601) and doing something like:

```<code>var birthDateString string // <-- the birth_date string you get from the request

iso8601 := "2006-01-02T15:04:05Z0700"

birthDate, err := time.ParseInLocation(iso8601, birthDateString,
time.Local)
parameters["birth_date"] = birthDate.Unix()
</code>```

Body:
I am trying to build a rule engine using govaluate: https://github.com/Knetic/govaluate

Here is my code:

package main

import (
    "github.com/Knetic/govaluate"
    "fmt"
)

func main()  {
    expression, err := govaluate.NewEvaluableExpression("first_name == 'Julian' && emp_id == 302 && birth_date >= '2016-12-12' && birth_date <= '2016-12-25'")

    parameters := make(map[string]interface{}, 8)
    parameters["first_name"] = "Julian"
    parameters["emp_id"] = 302
    parameters["birth_date"] = "2016-12-15"
    result, err := expression.Evaluate(parameters)

    if err != nil {
        fmt.Println("Error while evaluating the expression")
    }

    if result.(bool) {
        fmt.Println("Condition is evaluated to true")
    } else {
        fmt.Println("Condition is evaluated to false")
    }
}

While browsing through govaluate Types documentation (https://github.com/Knetic/govaluate/blob/master/MANUAL.md), I noticed this statement "Any string literal (not parameter) which is interpretable as a date will be converted to a float64 representation of that date's unix time."

When i execute the above program, i see an issue with result being null:

Error while evaluating the expression
panic: interface conversion: interface is nil, not bool

My question is whether date value can be passed in as a parameter? As i want to compare date values in runtime, this functionality would be needed.

Is there a way to achieve it? May be my usage pattern is wrong. Please suggest.

Edit:

expression, err := govaluate.NewEvaluableExpression("first_name == 'Julian' && emp_id == 302 && birth_date >= '2016-12-12' && birth_date <= '2016-12-25'")
dateFloat, _ := strconv.ParseFloat("2016-12-15", 64)
parameters["birth_date"] = dateFloat
result, err := expression.Evaluate(parameters)

Changed the date to float format and invoked Evaluate function. Now the condition is evaluated to false. But logically,  2016-12-15 falls between 2016-12-12 and 2016-12-25. The expression should be evaluated to true.

Thanks in advance!

Body:
Cross-posting my answer from the associated github issue, for future googlers;

The library doesn't try to parse string parameters as dates - it expects that birth_date will be the Unix() value of that date. This means you'll have to parse the date before passing it to govaluate.

If you're getting birth_date as part of a REST api, I'd suggest settling on one specific date format (such as ISO8601) and doing something like:

var birthDateString string // <-- the birth_date string you get from the request

iso8601 := "2006-01-02T15:04:05Z0700"

birthDate, err := time.ParseInLocation(iso8601, birthDateString,
time.Local)
parameters["birth_date"] = birthDate.Unix()


来源: stackexchange

问:
AWS Lambda: Could not load 'active_record/connection_adapters/postgresql_adapter'
I'm using AWS Lambda to run a simple ruby script with a github project that has a framework that suits my needs.

After facing several ruby and bundler version conflicts due to the limitations of Traveling Ruby that is part of the stack.

I'm able to run the script locally successfully but then when I package it and update the Lambda function I get a weird error on the AWS console as I test it:

```<code>START RequestId: feab102b-5da5-11e7-bf18-739c73eb4ef0 Version: $LATEST
2017-06-30T15:08:39.144Z    feab102b-5da5-11e7-bf18-739c73eb4ef0    Starting process: ./app
2017-06-30T15:08:51.403Z    feab102b-5da5-11e7-bf18-739c73eb4ef0    stderr:
/var/task/lib/vendor/ruby/2.1.0/gems/activesupport-4.2.9/lib/active_support/dependencies.rb:274:in `require'
2017-06-30T15:08:51.403Z    feab102b-5da5-11e7-bf18-739c73eb4ef0    stderr:
: Could not load 'active_record/connection_adapters/postgresql_adapter'. Make sure that the adapter in config/database.yml is valid. If you use an adapter other than 'mysql', 'mysql2', 'postgresql' or 'sqlite3' add the necessary adapter gem to the Gemfile. (LoadError)
from /var/task/lib/vendor/ruby/2.1.0/gems/activesupport-4.2.9/lib/active_support/dependencies.rb:274:in `block in require'
from /var/task/lib/vendor/ruby/2.1.0/gems/activesupport-4.2.9/lib/active_support/dependencies.rb:240:in `load_dependency'
from /var/task/lib/vendor/ruby/2.1.0/gems/activesupport-4.2.9/lib/active_support/dependencies.rb:274:in `require'
from /var/task/lib/vendor/ruby/2.1.0/gems/pg-0.21.0/lib/pg.rb:4:in `<top (required)>'
from /var/task/lib/vendor/ruby/2.1.0/gems/activesupport-4.2.9/lib/active_support/dependencies.rb:274:in `require'
from /var/task/lib/vendor/ruby/2.1.0/gems/activesupport-4.2.9/lib/active_support/dependencies.rb:274:in `block in require'
from /var/task/lib/vendor/ruby/2.1.0/gems/activesupport-4.2.9/lib/active_support/dependencies.rb:240:in `load_dependency'
from /var/task/lib/vendor/ruby/2.1.0/gems/activesupport-4.2.9/lib/active_support/dependencies.rb:274:in `require'
from /var/task/lib/vendor/ruby/2.1.0/gems/activerecord-4.2.9/lib/active_record/connection_adapters/postgresql_adapter.rb:17:in `<top (required)>'
from /var/task/lib/vendor/ruby/2.1.0/gems/activesupport-4.2.9/lib/active_support/dependencies.rb:274:in `require'
from /var/task/lib/vendor/ruby/2.1.0/gems/activesupport-4.2.9/lib/active_support/dependencies.rb:274:in `block in require'
from /var/task/lib/vendor/ruby/2.1.0/gems/activesupport-4.2.9/lib/active_support/dependencies.rb:240:in `load_dependency'
from /var/task/lib/vendor/ruby/2.1.0/gems/activesupport-4.2.9/lib/active_support/dependencies.rb:274:in `require'
from /var/task/lib/vendor/ruby/2.1.0/gems/activerecord 4.2.9/lib/active_record/connection_adapters/connection_specification.rb:175:in `spec'
from /var/task/lib/vendor/ruby/2.1.0/gems/activerecord 4.2.9/lib/active_record/connection_handling.rb:50:in `establish_connection'
from /var/task/lib/app/app.rb:12:in `<main>'

2017-06-30T15:08:51.744Z    feab102b-5da5-11e7-bf18-739c73eb4ef0    {"errorMessage":"Process \"./app\" exited with code: 1"}
END RequestId: feab102b-5da5-11e7-bf18-739c73eb4ef0
</code>```

In the db/config.yml(which it calls config/database.yml as it should be defaulted to rails tree) I have set adapter: postgresql and the all other required settings.

The code is entirely stored on a .zip file and I've unpacked it and was able to find the lib/vendor/ruby/2.1.0/gems/activerecord-4.2.9/lib/active_record/connection_adapters/postgresql_adapter.rb which I guess is extracted on the /var/task within the Lambda environment as it shows in logs.

The only thing I can think of is that at the moment of the require it is getting lost on the base path and therefore not finding the file to load.

I'd appreciate any insights of anything I may be missing or any clues towards fixing this.

Thanks!

答:
It ends up that the error above is misleading because activerecord actually rescues the exception and raises a customized error message and therefore does not reflect the reality happening somewhere else in the stack while loading the pg gem. The actual error is this:

```<code>START RequestId: a9e88496-6005-11e7-924c-e7c37f2df3e0 Version: $LATEST
2017-07-03T15:38:30.977Z    a9e88496-6005-11e7-924c-e7c37f2df3e0    Starting process: ./app
2017-07-03T15:38:42.337Z    a9e88496-6005-11e7-924c-e7c37f2df3e0    stderr:
/var/task/lib/vendor/ruby/2.1.0/gems/activesupport-4.2.9/lib/active_support/dependencies.rb:274:in `require'
2017-07-03T15:38:42.456Z    a9e88496-6005-11e7-924c-e7c37f2df3e0    stderr:
: libpq.so.5: cannot open shared object file: No such file or directory - /var/task/lib/vendor/ruby/2.1.0/extensions/x86_64-linux/2.1.0-static/pg-0.21.0/pg_ext.so - libpq.so.5: cannot open shared object file: No such file or directory - /var/task/lib/vendor/ruby/2.1.0/extensions/x86_64-linux/2.1.0-static/pg-0.21.0/pg_ext.so - Could not load 'active_record/connection_adapters/postgresql_adapter'. Make sure that the adapter in config/database.yml is valid. If you use an adapter other than 'mysql', 'mysql2', 'postgresql' or 'sqlite3' add the necessary adapter gem to the Gemfile. (LoadError)
from /var/task/lib/vendor/ruby/2.1.0/gems/activesupport-4.2.9/lib/active_support/dependencies.rb:274:in `block in require'
from /var/task/lib/vendor/ruby/2.1.0/gems/activesupport-4.2.9/lib/active_support/dependencies.rb:240:in `load_dependency'
from /var/task/lib/vendor/ruby/2.1.0/gems/activesupport-4.2.9/lib/active_support/dependencies.rb:274:in `require'
from /var/task/lib/vendor/ruby/2.1.0/gems/pg-0.21.0/lib/pg.rb:4:in `<top (required)>'
from /var/task/lib/vendor/ruby/2.1.0/gems/activesupport-4.2.9/lib/active_support/dependencies.rb:274:in `require'
from /var/task/lib/vendor/ruby/2.1.0/gems/activesupport-4.2.9/lib/active_support/dependencies.rb:274:in `block in require'
from /var/task/lib/vendor/ruby/2.1.0/gems/activesupport-4.2.9/lib/active_support/dependencies.rb:240:in `load_dependency'
from /var/task/lib/vendor/ruby/2.1.0/gems/activesupport-4.2.9/lib/active_support/dependencies.rb:274:in `require'
from /var/task/lib/vendor/ruby/2.1.0/gems/activerecord-4.2.9/lib/active_record/connection_adapters/postgresql_adapter.rb:17:in `<top (required)>'
from /var/task/lib/vendor/ruby/2.1.0/gems/activesupport-4.2.9/lib/active_support/dependencies.rb:274:in `require'
from /var/task/lib/vendor/ruby/2.1.0/gems/activesupport-4.2.9/lib/active_support/dependencies.rb:274:in `block in require'
from /var/task/lib/vendor/ruby/2.1.0/gems/activesupport-4.2.9/lib/active_support/dependencies.rb:240:in `load_dependency'
from /var/task/lib/vendor/ruby/2.1.0/gems/activesupport-4.2.9/lib/active_support/dependencies.rb:274:in `require'
from /var/task/lib/vendor/ruby/2.1.0/gems/activerecord-4.2.9/lib/active_record/connection_adapters/connection_specification.rb:175:in `spec'
from /var/task/lib/vendor/ruby/2.1.0/gems/activerecord-4.2.9/lib/active_record/connection_handling.rb:50:in `establish_connection'
from /var/task/lib/app/app.rb:12:in `<main>'

2017-07-03T15:38:42.676Z    a9e88496-6005-11e7-924c-e7c37f2df3e0    {"errorMessage":"Process \"./app\" exited with code: 1"}
END RequestId: a9e88496-6005-11e7-924c-e7c37f2df3e0
</code>```

The real reason is also hidden behind this error. It is not that the pg_ext.so was not found as it is there in this very path.

After some more research, the final issue is that libpg.so.5 itself is the one missing and to fix that I had to add it within Traveling Ruby's libraries path.

Hope that can become helpful to others in the future!

ContentLicense: CC BY-SA 3.0

Body:
I'm using AWS Lambda to run a simple ruby script with a github project that has a framework that suits my needs.

After facing several ruby and bundler version conflicts due to the limitations of Traveling Ruby that is part of the stack.

I'm able to run the script locally successfully but then when I package it and update the Lambda function I get a weird error on the AWS console as I test it:

START RequestId: feab102b-5da5-11e7-bf18-739c73eb4ef0 Version: $LATEST
2017-06-30T15:08:39.144Z    feab102b-5da5-11e7-bf18-739c73eb4ef0    Starting process: ./app
2017-06-30T15:08:51.403Z    feab102b-5da5-11e7-bf18-739c73eb4ef0    stderr:
/var/task/lib/vendor/ruby/2.1.0/gems/activesupport-4.2.9/lib/active_support/dependencies.rb:274:in `require'
2017-06-30T15:08:51.403Z    feab102b-5da5-11e7-bf18-739c73eb4ef0    stderr:
: Could not load 'active_record/connection_adapters/postgresql_adapter'. Make sure that the adapter in config/database.yml is valid. If you use an adapter other than 'mysql', 'mysql2', 'postgresql' or 'sqlite3' add the necessary adapter gem to the Gemfile. (LoadError)
from /var/task/lib/vendor/ruby/2.1.0/gems/activesupport-4.2.9/lib/active_support/dependencies.rb:274:in `block in require'
from /var/task/lib/vendor/ruby/2.1.0/gems/activesupport-4.2.9/lib/active_support/dependencies.rb:240:in `load_dependency'
from /var/task/lib/vendor/ruby/2.1.0/gems/activesupport-4.2.9/lib/active_support/dependencies.rb:274:in `require'
from /var/task/lib/vendor/ruby/2.1.0/gems/pg-0.21.0/lib/pg.rb:4:in `<top (required)>'
from /var/task/lib/vendor/ruby/2.1.0/gems/activesupport-4.2.9/lib/active_support/dependencies.rb:274:in `require'
from /var/task/lib/vendor/ruby/2.1.0/gems/activesupport-4.2.9/lib/active_support/dependencies.rb:274:in `block in require'
from /var/task/lib/vendor/ruby/2.1.0/gems/activesupport-4.2.9/lib/active_support/dependencies.rb:240:in `load_dependency'
from /var/task/lib/vendor/ruby/2.1.0/gems/activesupport-4.2.9/lib/active_support/dependencies.rb:274:in `require'
from /var/task/lib/vendor/ruby/2.1.0/gems/activerecord-4.2.9/lib/active_record/connection_adapters/postgresql_adapter.rb:17:in `<top (required)>'
from /var/task/lib/vendor/ruby/2.1.0/gems/activesupport-4.2.9/lib/active_support/dependencies.rb:274:in `require'
from /var/task/lib/vendor/ruby/2.1.0/gems/activesupport-4.2.9/lib/active_support/dependencies.rb:274:in `block in require'
from /var/task/lib/vendor/ruby/2.1.0/gems/activesupport-4.2.9/lib/active_support/dependencies.rb:240:in `load_dependency'
from /var/task/lib/vendor/ruby/2.1.0/gems/activesupport-4.2.9/lib/active_support/dependencies.rb:274:in `require'
from /var/task/lib/vendor/ruby/2.1.0/gems/activerecord 4.2.9/lib/active_record/connection_adapters/connection_specification.rb:175:in `spec'
from /var/task/lib/vendor/ruby/2.1.0/gems/activerecord 4.2.9/lib/active_record/connection_handling.rb:50:in `establish_connection'
from /var/task/lib/app/app.rb:12:in `'

2017-06-30T15:08:51.744Z    feab102b-5da5-11e7-bf18-739c73eb4ef0    {"errorMessage":"Process \"./app\" exited with code: 1"}
END RequestId: feab102b-5da5-11e7-bf18-739c73eb4ef0

In the db/config.yml(which it calls config/database.yml as it should be defaulted to rails tree) I have set adapter: postgresql and the all other required settings.

The code is entirely stored on a .zip file and I've unpacked it and was able to find the lib/vendor/ruby/2.1.0/gems/activerecord-4.2.9/lib/active_record/connection_adapters/postgresql_adapter.rb which I guess is extracted on the /var/task within the Lambda environment as it shows in logs.

The only thing I can think of is that at the moment of the require it is getting lost on the base path and therefore not finding the file to load.

I'd appreciate any insights of anything I may be missing or any clues towards fixing this.

Thanks!

Body:
It ends up that the error above is misleading because activerecord actually rescues the exception and raises a customized error message and therefore does not reflect the reality happening somewhere else in the stack while loading the pg gem. The actual error is this:

START RequestId: a9e88496-6005-11e7-924c-e7c37f2df3e0 Version: $LATEST
2017-07-03T15:38:30.977Z    a9e88496-6005-11e7-924c-e7c37f2df3e0    Starting process: ./app
2017-07-03T15:38:42.337Z    a9e88496-6005-11e7-924c-e7c37f2df3e0    stderr:
/var/task/lib/vendor/ruby/2.1.0/gems/activesupport-4.2.9/lib/active_support/dependencies.rb:274:in `require'
2017-07-03T15:38:42.456Z    a9e88496-6005-11e7-924c-e7c37f2df3e0    stderr:
: libpq.so.5: cannot open shared object file: No such file or directory - /var/task/lib/vendor/ruby/2.1.0/extensions/x86_64-linux/2.1.0-static/pg-0.21.0/pg_ext.so - libpq.so.5: cannot open shared object file: No such file or directory - /var/task/lib/vendor/ruby/2.1.0/extensions/x86_64-linux/2.1.0-static/pg-0.21.0/pg_ext.so - Could not load 'active_record/connection_adapters/postgresql_adapter'. Make sure that the adapter in config/database.yml is valid. If you use an adapter other than 'mysql', 'mysql2', 'postgresql' or 'sqlite3' add the necessary adapter gem to the Gemfile. (LoadError)
from /var/task/lib/vendor/ruby/2.1.0/gems/activesupport-4.2.9/lib/active_support/dependencies.rb:274:in `block in require'
from /var/task/lib/vendor/ruby/2.1.0/gems/activesupport-4.2.9/lib/active_support/dependencies.rb:240:in `load_dependency'
from /var/task/lib/vendor/ruby/2.1.0/gems/activesupport-4.2.9/lib/active_support/dependencies.rb:274:in `require'
from /var/task/lib/vendor/ruby/2.1.0/gems/pg-0.21.0/lib/pg.rb:4:in `<top (required)>'
from /var/task/lib/vendor/ruby/2.1.0/gems/activesupport-4.2.9/lib/active_support/dependencies.rb:274:in `require'
from /var/task/lib/vendor/ruby/2.1.0/gems/activesupport-4.2.9/lib/active_support/dependencies.rb:274:in `block in require'
from /var/task/lib/vendor/ruby/2.1.0/gems/activesupport-4.2.9/lib/active_support/dependencies.rb:240:in `load_dependency'
from /var/task/lib/vendor/ruby/2.1.0/gems/activesupport-4.2.9/lib/active_support/dependencies.rb:274:in `require'
from /var/task/lib/vendor/ruby/2.1.0/gems/activerecord-4.2.9/lib/active_record/connection_adapters/postgresql_adapter.rb:17:in `<top (required)>'
from /var/task/lib/vendor/ruby/2.1.0/gems/activesupport-4.2.9/lib/active_support/dependencies.rb:274:in `require'
from /var/task/lib/vendor/ruby/2.1.0/gems/activesupport-4.2.9/lib/active_support/dependencies.rb:274:in `block in require'
from /var/task/lib/vendor/ruby/2.1.0/gems/activesupport-4.2.9/lib/active_support/dependencies.rb:240:in `load_dependency'
from /var/task/lib/vendor/ruby/2.1.0/gems/activesupport-4.2.9/lib/active_support/dependencies.rb:274:in `require'
from /var/task/lib/vendor/ruby/2.1.0/gems/activerecord-4.2.9/lib/active_record/connection_adapters/connection_specification.rb:175:in `spec'
from /var/task/lib/vendor/ruby/2.1.0/gems/activerecord-4.2.9/lib/active_record/connection_handling.rb:50:in `establish_connection'
from /var/task/lib/app/app.rb:12:in `<main>'

2017-07-03T15:38:42.676Z    a9e88496-6005-11e7-924c-e7c37f2df3e0    {"errorMessage":"Process \"./app\" exited with code: 1"}
END RequestId: a9e88496-6005-11e7-924c-e7c37f2df3e0

The real reason is also hidden behind this error. It is not that the pg_ext.so was not found as it is there in this very path.

After some more research, the final issue is that libpg.so.5 itself is the one missing and to fix that I had to add it within Traveling Ruby's libraries path.

Hope that can become helpful to others in the future!


问:
How Do I Make A Controller Accessible Menu | Unity
I have a menu on a game I'm working on. The menu consists of a few logos in the form of images, and 2 buttons in a canvas. I'm trying to give the game full controller support. How do I make it so that the controller can navigate through the menus?

The controller I'm using is a wired Xbox 360 Controller.

答: You need to define "First selected" in the event Manager. Thats all.</p>


问:
Properly use 'this' in jquery
I have created this iOS-like menu and I'm trying to make the slide right work when you click on a certain category. I have made something that works here but with only one div that needs clicking (showing .page.second).

Now when I try to do the same on this longer menu, it needs more editing because there are several clickable
 that can lead to different .page.second. I wanted to know if I could succeed thanks to a 'this' or if the only option was to name all the pages and refer to them one by one in the jquery code?

I'm not sure this is very clear, please ask questions if you didn't understand something, or what I wanted to do!

Thanks for the help!

$('.mtitle').click(function(){
  $('.page.second').show()
});
$('.back').click(function(){
  $('.page.second').hide()
})```
<pre class="snippet-code-css lang-css prettyprint-override"><code>#main{
  position:relative;
  width:600px;
  height:700px;
  overflow-y:scroll;
  overflow-x:hidden;
  border:2px solid #aaa;
  border-radius:10px;
}
.space{
  height:35px;
  margin:0;
  border-bottom:1px solid #aaa;
}
.page{
  top:0;
  left:0;
  background:#ddd;
  -webkit-transition: 1s ease;
  -moz-transition: 1s ease;
  -ms-transition: 1s ease;
  -o-transition: 1s ease;
  transition: 1s ease;
}
.page p{
  text-align:center;
  font-size:25px;
  font-family:Helvetica, arial, sans-serif;
  font-weight:700;
}
.top{
  border-bottom:1px solid #333;
  background:#fff;
  margin-bottom:20px;
}
.page.second{
  display:none;
  position:absolute;
  top:0;
  left:0;
}
.back{
  cursor:pointer;
  border:none;
  color:#0084ff;
  font-family:helvetica, arial, sans-serif;
  background:transparent;
}
.mtitle{
  background:#fff;
  cursor:pointer;
  width:100%;
  display:inline-block;
}

.mtitle img{
  float:left;
  width:30px;
  height:30px;
  margin:8px 10px;
}
.mtitle h1{
  color:#222;
  border-bottom:1px solid #aaa;
  margin:0;
  padding:10px;
  font-family:Helvetica, Arial, sans-serif;
  font-size:18px;
  font-weight:500;
}
.mtitle i{
  float:right;
  color:#aaa;
  margin-right:5px;
  font-size:20px;
  -webkit-text-stroke: 2px white;
  line-height:40px;
}

.tags{
  width:100%;
  float:right;
  cursor:pointer;
  display:inline-block;
}
.tags a, .droptitle{
  display:inline-block;
  text-decoration:none;
  width:100%;
  color:#222;
  background:#fff;
  border-bottom:1px solid #aaa;
  margin:0;
  padding:10px;
  line-height:25px;
  font-family:Helvetica, Arial, sans-serif;
  font-size:18px;
  font-weight:500;
}
.droptitle i{  float:right;
  color:#aaa;
  margin-right:5px;
  font-size:20px;
  -webkit-text-stroke: 2px white;
}</code>```

<link href="//maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet">

{Title} - All links

General

Home

Contact

Soundtrack

Icons

TV Shows

  <button class="back"> General</button>

TV Shows

brooklyn nine-nine

Amy Santiago
Charles Boyle
Gina Linetti
Hitchcock
Jake Peralta
Raymond Holt
Rosa Diaz
Scully
Terry Jeffords

friends

Rachel Green
Monica Geller
Phoebe Buffay
Joey Tribbiani
Chandler Bing
Ross Geller

game of thrones
how i met your mother
how to get away with murder
jane the virgin
new girl
one tree hill
orange is the new black

orphan black

Alison Hendrix
Beth Childs
Cosima Niehaus
Delphine Cormier
Donnie Hendrix
Felix Dawkins
Helena
Kira Manning
Krystal Goderitch
Paul Dierden
Rachel Duncan
Sarah Manning
Siobhan Sadler

skam

main characters

Eva Kviig Mohn
Noora Amalie Sætre
Isak Valtersen
Sana Bakkoush

Chris Berg
Christoffer Schistad
Eskild Tryggvason
Even Bech Næsheim
Ingrid Theis Gaupseth
Jonas Noah Vasquez
Linn Larsen Hansen
Magnus Fossbakken
Mahdi Disi
Sara Nørrstelien
Vilde Lien Hellerud
William Magnusson

once upon a time

August Booth
Belle French
David Nolan
Emma Swan
Graham Humbert
Henry Daniel Mills
Jefferson
Killian Jones
Mary Margaret Blanchard
Neal Cassidy
Regina Mills
Robin Hood
Ruby
Rumplestiltskin
Zelena

stranger things
13 reasons why

Ships

Emma & Regina
Noora & William
Frank & Laurel
Magnus & Vilde

Actors

Alfie Enoch
Andy Samberg
Bruno Mars
Charlie Heaton
Chloe Bennet
Chris Hemsworth
Chris Pratt
Cobie Smulders
Daniel Sharman
Danielle Panabaker
Dylan Minnette
Emilia Clarke
Evelyne Brochu
Gina Rodriguez
Halsey
Jack Falahee
Jamie Dornan
Jennifer Aniston
Jennifer Morrison
Jessica Alba
Justin Baldoni
Karla Souza
Kate Mara
Katherine Langford
Katherine McNamara
Katie Cassidy
Kit Harington
Lana Parrilla
Leighton Meester
Lily Collins
Lisa Kudrow
Madelaine Petsch
Margot Robbie
Max Greenfield
Melissa Fumero
Natalie Dormer
Natalia Dyer
Richard Madden
Rose Leslie
Rose McIver
Sarah Paulson
Selena Gomez
Stephanie Beatriz
Stephen Amell
Sophia Bush
Sophie Turner
Tatiana Maslany
Theo James
Theresa Eggesbø
Yael Grobglas
Zooey Deschanel

Post types

gif
photo
icons
tutorial
answer
edit

Movies

Guardians of the Galaxy
The End of the Longing
Suicide Squad
La La Land

Magazines

Complex
Evening Standard
Daman
Darling
LA Times
NKD
Popular TV
Shape
Vanity Fair
Vogue
WWD

   ```

答:
You could try adding a 'data' attribute to each link and check the value each time it is clicked. I created a very minified version of what you have in jsFiddle as sort of a proof-of-concept.

```<code>$('p.link').click(function(evt) {
    $('#home').hide();
    switch ($(this).attr('data')) {
    case 'page1': $('#page1').show(); break;
    case 'page2': $('#page2').show(); break;
    case 'page3': $('#page3').show(); break;
    case 'page4': $('#page4').show(); break;
    case 'page5': $('#page5').show(); break;
  };
});
</code>```

JsFiddle

Title: Properly use 'this' in jquery

Body:
I have created this iOS-like menu and I'm trying to make the slide right work when you click on a certain category. I have made something that works here but with only one div that needs clicking (showing .page.second).

Now when I try to do the same on this longer menu, it needs more editing because there are several clickable
 that can lead to different .page.second. I wanted to know if I could succeed thanks to a 'this' or if the only option was to name all the pages and refer to them one by one in the jquery code?

I'm not sure this is very clear, please ask questions if you didn't understand something, or what I wanted to do!

Thanks for the help!

$('.mtitle').click(function(){
  $('.page.second').show()
});
$('.back').click(function(){
  $('.page.second').hide()
})

#main{
  position:relative;
  width:600px;
  height:700px;
  overflow-y:scroll;
  overflow-x:hidden;
  border:2px solid #aaa;
  border-radius:10px;
}
.space{
  height:35px;
  margin:0;
  border-bottom:1px solid #aaa;
}
.page{
  top:0;
  left:0;
  background:#ddd;
  -webkit-transition: 1s ease;
  -moz-transition: 1s ease;
  -ms-transition: 1s ease;
  -o-transition: 1s ease;
  transition: 1s ease;
}
.page p{
  text-align:center;
  font-size:25px;
  font-family:Helvetica, arial, sans-serif;
  font-weight:700;
}
.top{
  border-bottom:1px solid #333;
  background:#fff;
  margin-bottom:20px;
}
.page.second{
  display:none;
  position:absolute;
  top:0;
  left:0;
}
.back{
  cursor:pointer;
  border:none;
  color:#0084ff;
  font-family:helvetica, arial, sans-serif;
  background:transparent;
}
.mtitle{
  background:#fff;
  cursor:pointer;
  width:100%;
  display:inline-block;
}

.mtitle img{
  float:left;
  width:30px;
  height:30px;
  margin:8px 10px;
}
.mtitle h1{
  color:#222;
  border-bottom:1px solid #aaa;
  margin:0;
  padding:10px;
  font-family:Helvetica, Arial, sans-serif;
  font-size:18px;
  font-weight:500;
}
.mtitle i{
  float:right;
  color:#aaa;
  margin-right:5px;
  font-size:20px;
  -webkit-text-stroke: 2px white;
  line-height:40px;
}

.tags{
  width:100%;
  float:right;
  cursor:pointer;
  display:inline-block;
}
.tags a, .droptitle{
  display:inline-block;
  text-decoration:none;
  width:100%;
  color:#222;
  background:#fff;
  border-bottom:1px solid #aaa;
  margin:0;
  padding:10px;
  line-height:25px;
  font-family:Helvetica, Arial, sans-serif;
  font-size:18px;
  font-weight:500;
}
.droptitle i{  float:right;
  color:#aaa;
  margin-right:5px;
  font-size:20px;
  -webkit-text-stroke: 2px white;
}

<link href="//maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet">

{Title} - All links

General

Home

Contact

Soundtrack

Icons

TV Shows

  <button class="back"> General</button>

TV Shows

brooklyn nine-nine

Amy Santiago
Charles Boyle
Gina Linetti
Hitchcock
Jake Peralta
Raymond Holt
Rosa Diaz
Scully
Terry Jeffords

friends

Rachel Green
Monica Geller
Phoebe Buffay
Joey Tribbiani
Chandler Bing
Ross Geller

game of thrones
how i met your mother
how to get away with murder
jane the virgin
new girl
one tree hill
orange is the new black

orphan black

Alison Hendrix
Beth Childs
Cosima Niehaus
Delphine Cormier
Donnie Hendrix
Felix Dawkins
Helena
Kira Manning
Krystal Goderitch
Paul Dierden
Rachel Duncan
Sarah Manning
Siobhan Sadler

skam

main characters

Eva Kviig Mohn
Noora Amalie Sætre
Isak Valtersen
Sana Bakkoush

Chris Berg
Christoffer Schistad
Eskild Tryggvason
Even Bech Næsheim
Ingrid Theis Gaupseth
Jonas Noah Vasquez
Linn Larsen Hansen
Magnus Fossbakken
Mahdi Disi
Sara Nørrstelien
Vilde Lien Hellerud
William Magnusson

once upon a time

August Booth
Belle French
David Nolan
Emma Swan
Graham Humbert
Henry Daniel Mills
Jefferson
Killian Jones
Mary Margaret Blanchard
Neal Cassidy
Regina Mills
Robin Hood
Ruby
Rumplestiltskin
Zelena

stranger things
13 reasons why

Ships

Emma & Regina
Noora & William
Frank & Laurel
Magnus & Vilde

Actors

Alfie Enoch
Andy Samberg
Bruno Mars
Charlie Heaton
Chloe Bennet
Chris Hemsworth
Chris Pratt
Cobie Smulders
Daniel Sharman
Danielle Panabaker
Dylan Minnette
Emilia Clarke
Evelyne Brochu
Gina Rodriguez
Halsey
Jack Falahee
Jamie Dornan
Jennifer Aniston
Jennifer Morrison
Jessica Alba
Justin Baldoni
Karla Souza
Kate Mara
Katherine Langford
Katherine McNamara
Katie Cassidy
Kit Harington
Lana Parrilla
Leighton Meester
Lily Collins
Lisa Kudrow
Madelaine Petsch
Margot Robbie
Max Greenfield
Melissa Fumero
Natalie Dormer
Natalia Dyer
Richard Madden
Rose Leslie
Rose McIver
Sarah Paulson
Selena Gomez
Stephanie Beatriz
Stephen Amell
Sophia Bush
Sophie Turner
Tatiana Maslany
Theo James
Theresa Eggesbø
Yael Grobglas
Zooey Deschanel

Post types

gif
photo
icons
tutorial
answer
edit

Movies

Guardians of the Galaxy
The End of the Longing
Suicide Squad
La La Land

Magazines

Complex
Evening Standard
Daman
Darling
LA Times
NKD
Popular TV
Shape
Vanity Fair
Vogue
WWD

Body:
You could try adding a 'data' attribute to each link and check the value each time it is clicked. I created a very minified version of what you have in jsFiddle as sort of a proof-of-concept.

$('p.link').click(function(evt) {
    $('#home').hide();
    switch ($(this).attr('data')) {
    case 'page1': $('#page1').show(); break;
    case 'page2': $('#page2').show(); break;
    case 'page3': $('#page3').show(); break;
    case 'page4': $('#page4').show(); break;
    case 'page5': $('#page5').show(); break;
  };
});

JsFiddle


问:
How to modify this JS code to search for exact, whole word/number
I'm currently working on a search engine (masonry + isotope + custom code provided below). I would like it to display only exact matches of only whole words or numbers entered by a user, apart from searching by classes of divs etc (this and everything else works fine).

Current situation:
When user inputs "1", paragraphs containing e.g. "12" are displayed too

Desired result:
When user inputs "1", only results containing "1" are displayed - NOT paragraphs containing numbers like 221, 111, 12 etc.

I would be very grateful for providing working code.

```<code>var qsRegex;
var buttonFilter;

var $grid = $('.grid').isotope({
  itemSelector: '.element-item',
  layoutMode: 'fitRows',
  filter: function() {
    var $this = $(this);
    var searchResult = qsRegex ? $this.text().match( qsRegex ) : true;
    var buttonResult = buttonFilter ? $this.is( buttonFilter ) : true;
    return searchResult && buttonResult;
  }
});

$('#filters').on( 'click', 'button', function() {
  buttonFilter = $( this ).attr('data-filter');
  $grid.isotope();
});

var $quicksearch = $('#quicksearch').keyup( debounce( function() {
  qsRegex = new RegExp( $quicksearch.val(), 'gi' );
  $grid.isotope();
}) );

$('.button-group').each( function( i, buttonGroup ) {
  var $buttonGroup = $( buttonGroup );
  $buttonGroup.on( 'click', 'button', function() {
    $buttonGroup.find('.is-checked').removeClass('is-checked');
    $( this ).addClass('is-checked');
  });
});

function debounce( fn, threshold ) {
  var timeout;
  return function debounced() {
    if ( timeout ) {
      clearTimeout( timeout );
    }
    function delayed() {
      fn();
      timeout = null;
    }
    setTimeout( delayed, threshold || 100 );
  };
}
</code>```

答:
OK, I figured it out myself:</p>

```<code> qsRegex = new RegExp( "\\b" + $quicksearch.val() + "\\b", 'gi' );
</code>```

Body:
I'm currently working on a search engine (masonry + isotope + custom code provided below). I would like it to display only exact matches of only whole words or numbers entered by a user, apart from searching by classes of divs etc (this and everything else works fine).

Current situation:
When user inputs "1", paragraphs containing e.g. "12" are displayed too

Desired result:
When user inputs "1", only results containing "1" are displayed - NOT paragraphs containing numbers like 221, 111, 12 etc.

I would be very grateful for providing working code.

var qsRegex;
var buttonFilter;

var $grid = $('.grid').isotope({
  itemSelector: '.element-item',
  layoutMode: 'fitRows',
  filter: function() {
    var $this = $(this);
    var searchResult = qsRegex ? $this.text().match( qsRegex ) : true;
    var buttonResult = buttonFilter ? $this.is( buttonFilter ) : true;
    return searchResult && buttonResult;
  }
});

$('#filters').on( 'click', 'button', function() {
  buttonFilter = $( this ).attr('data-filter');
  $grid.isotope();
});

var $quicksearch = $('#quicksearch').keyup( debounce( function() {
  qsRegex = new RegExp( $quicksearch.val(), 'gi' );
  $grid.isotope();
}) );

$('.button-group').each( function( i, buttonGroup ) {
  var $buttonGroup = $( buttonGroup );
  $buttonGroup.on( 'click', 'button', function() {
    $buttonGroup.find('.is-checked').removeClass('is-checked');
    $( this ).addClass('is-checked');
  });
});

function debounce( fn, threshold ) {
  var timeout;
  return function debounced() {
    if ( timeout ) {
      clearTimeout( timeout );
    }
    function delayed() {
      fn();
      timeout = null;
    }
    setTimeout( delayed, threshold || 100 );
  };
}

Body:
OK, I figured it out myself:

 qsRegex = new RegExp( "\\b" + $quicksearch.val() + "\\b", 'gi' );


问:
Make a link for each string
I have table videos with field tags

```<code>tags |  word1, word2, word3, word4,
</code>```

And i have this php code that display me tags from each movie

```<code>    $sql = "SELECT tags FROM videos";
$result = mysqli_query($mysqli, $sql);
$tags='';
while ($rez = $result->fetch_assoc()) {
    $tags .= $rez['tags'];
    echo str_replace(',', '<br />', $rez['tags']);
}
</code>```

it show me like this:

```<code>word1
word2
word3
word4
</code>```

How i can make a link for each word?

I have tried this

```<code>echo 'http://example.com/'.str_replace(',','</ br>',$rez['tags']);
</code>```

But it show me

```<code>    http://example.com/word1
    word2
    word3
    word4
</code>```

答:
You have to modify your little code bit. See the below code using these you can easily achieve your result.</p>

```<code>while ($rez = $result->fetch_assoc()) {
  $array = array_filter(explode(',', $rez['tags']));

  foreach ($array as $value) {
    echo 'http://example.com/' . $value . '<br>';
  }
}
</code>```

Title: Make a link for each string

Body:
I have table videos with field tags

tags |  word1, word2, word3, word4,

And i have this php code that display me tags from each movie

    $sql = "SELECT tags FROM videos";
$result = mysqli_query($mysqli, $sql);
$tags='';
while ($rez = $result->fetch_assoc()) {
    $tags .= $rez['tags'];
    echo str_replace(',', '
', $rez['tags']);
}

it show me like this:

word1
word2
word3
word4

How i can make a link for each word?

I have tried this

echo 'http://example.com/'.str_replace(',','
',$rez['tags']);

But it show me

    http://example.com/word1
    word2
    word3
    word4

Body:
You have to modify your little code bit. See the below code using these you can easily achieve your result.

while ($rez = $result->fetch_assoc()) {
  $array = array_filter(explode(',', $rez['tags']));

  foreach ($array as $value) {
    echo 'http://example.com/' . $value . '<br>';
  }
}


问:
Static assert whether or not add operation is available
I'm trying to make a static assert that checks whether type A can be added to type B. Is there any way to check whether template type A is addable to template type B at compile time? A and B could really be anything at all.</p>

答:
With is_detected, you may do something like:</p>

```<code>template <typename LHS, typename RHS>
using sum_t = decltype(std::declval<LHS>() + std::declval<RHS>());

template <typename LHS, typename RHS>
using has_sum = is_detected<sum_t, LHS, RHS>;
</code>```

Body:
With is_detected, you may do something like:

template <typename LHS, typename RHS>
using sum_t = decltype(std::declval<LHS>() + std::declval<RHS>());

template <typename LHS, typename RHS>
using has_sum = is_detected<sum_t, LHS, RHS>;


问:
Laravel Raw and Eloquent Queries
I've got a table transactions which has a paymentable_id and paymentable_type column, for polymorphic relations. I have a Plan model, used for payment plans. Whenever a transaction for that plan is made, the transactions will be related to that plan, using the polymorphic relation.

Now, I want to fetch all Plans from the database, including a field called total_amount. The total_amount field should include the sum of all transactions.amount related for that plan.

So far, and with help from another question I asked, I came up with the following:

```<code>$plans = App\Models\Plan::all('*', DB::RAW("(SELECT SUM(amount) FROM transactions WHERE paymentable_id = plans.id AND paymentable_type = 'App\\\\Models\\\\Plan' ) as total_amount") );
</code>```

Which works totally fine. However, I feel this is just plain wrong:

```<code>WHERE paymentable_id = plans.id AND paymentable_type = 'App\\\\Models\\\\Plan'
</code>```

Also, the need to specify the paymentable_id AND paymentable_type seems wrong to me. I need to be doing this for a lot of other queries as well, since the polymorphic relation can contain up to 5 different models.

Question 1. Is the above a correct query to use and if so, is there perhaps also a "better way" to create that query?

Question 2. The below query also works but I perhaps do not understand this part:

```<code>->join('transactions', 'plans.id', '=', 'transactions.paymentable_id')
</code>```

Whenever I include the ->where('transactions.paymentable_id', '=', 'plans.id'), it works as expected. But without that part, it basically ignores the paymentable_id.

```<code>$plans = DB::table('plans')->join('transactions', 'plans.id', '=', 'transactions.paymentable_id')
                           ->where('transactions.paymentable_type', '=', 'App\\Models\\Plan')
                           ->get([DB::raw('sum(transactions.amount) as total_amount')]);
</code>```

Any pointers are much appreciated.

答:
i do not know you data base </p>

```<code>$plans = DB::table('plans')->join('transactions', 'plans.id', '=', 'transactions.paymentable_id')
                       ->where('transactions.paymentable_type', '=', 'you_plan_type')
                       ->select('plans.*','transactions.*')
                       ->selectRaw('sum(transactions.amount) as total_amount')
                       ->get();
</code>```

ContentLicense: CC BY-SA 4.0

Title: Laravel Raw and Eloquent Queries

Body:
I've got a table transactions which has a paymentable_id and paymentable_type column, for polymorphic relations. I have a Plan model, used for payment plans. Whenever a transaction for that plan is made, the transactions will be related to that plan, using the polymorphic relation.

Now, I want to fetch all Plans from the database, including a field called total_amount. The total_amount field should include the sum of all transactions.amount related for that plan.

So far, and with help from another question I asked, I came up with the following:

$plans = App\Models\Plan::all('*', DB::RAW("(SELECT SUM(amount) FROM transactions WHERE paymentable_id = plans.id AND paymentable_type = 'App\\\\Models\\\\Plan' ) as total_amount") );

Which works totally fine. However, I feel this is just plain wrong:

WHERE paymentable_id = plans.id AND paymentable_type = 'App\\\\Models\\\\Plan'

Also, the need to specify the paymentable_id AND paymentable_type seems wrong to me. I need to be doing this for a lot of other queries as well, since the polymorphic relation can contain up to 5 different models.

Question 1. Is the above a correct query to use and if so, is there perhaps also a "better way" to create that query?

Question 2. The below query also works but I perhaps do not understand this part:

->join('transactions', 'plans.id', '=', 'transactions.paymentable_id')

Whenever I include the ->where('transactions.paymentable_id', '=', 'plans.id'), it works as expected. But without that part, it basically ignores the paymentable_id.

$plans = DB::table('plans')->join('transactions', 'plans.id', '=', 'transactions.paymentable_id')
                           ->where('transactions.paymentable_type', '=', 'App\\Models\\Plan')
                           ->get([DB::raw('sum(transactions.amount) as total_amount')]);

Any pointers are much appreciated.

Body:
i do not know you data base

$plans = DB::table('plans')->join('transactions', 'plans.id', '=', 'transactions.paymentable_id')
                       ->where('transactions.paymentable_type', '=', 'you_plan_type')
                       ->select('plans.*','transactions.*')
                       ->selectRaw('sum(transactions.amount) as total_amount')
                       ->get();


问:
JS/jQuery/PHP: trying to generate an URL using PHP variables
i'm generating this code

```<code>$.ajax({
        url: '/orders/modify/action/',
        type: "POST",
        dataType: 'json',
        data: 'id='+10+
              '&commento='+$('#shop_order_status_history_comments').val()+
              '&id_status='+$('#shop_order_status_history_orders_status_id').val()+
              '&notify_client='+$('#shop_order_status_history_notify_client').val()+
              '&local_part_email='+j.garpe+   // the error goes here
              '&domain_email='+domain.com,
        success:function(data){
</code>```

But I'm getting this error:

"Uncaught referenceError: j is not
  defined".

The code is this:

```<code>      ...
      '&local_part_email='+<?php echo $local_part_email?>+
      ...
</code>```

Any help?

Regards

Javi

答:
It needs to be in quotes, like this:

```<code>'&local_part_email=<?php echo $local_part_email?>'+
</code>```

...but you'll have the same problem with domain next, it's best to put it in quotes and let jQuery create the string, by passing an object to data like this:

```<code>data: {id: 10,
       commento: $('#shop_order_status_history_comments').val(),
       id_status: $('#shop_order_status_history_orders_status_id').val(),
       notify_client: $('#shop_order_status_history_notify_client').val(),
       local_part_email: '<?php echo $local_part_email?>',
       domain_email: '<?php echo $whatever_domain_variable_here?>' }
</code>```

ContentLicense: CC BY-SA 2.5

Body:
i'm generating this code

$.ajax({
        url: '/orders/modify/action/',
        type: "POST",
        dataType: 'json',
        data: 'id='+10+
              '&commento='+$('#shop_order_status_history_comments').val()+
              '&id_status='+$('#shop_order_status_history_orders_status_id').val()+
              '&notify_client='+$('#shop_order_status_history_notify_client').val()+
              '&local_part_email='+j.garpe+   // the error goes here
              '&domain_email='+domain.com,
        success:function(data){

But I'm getting this error:

"Uncaught referenceError: j is not
  defined".

The code is this:

      ...
      '&local_part_email='+<?php echo $local_part_email?>+
      ...

Any help?

Regards

Javi

Body:
It needs to be in quotes, like this:

'&local_part_email=<?php echo $local_part_email?>'+

...but you'll have the same problem with domain next, it's best to put it in quotes and let jQuery create the string, by passing an object to data like this:

data: {id: 10,
       commento: $('#shop_order_status_history_comments').val(),
       id_status: $('#shop_order_status_history_orders_status_id').val(),
       notify_client: $('#shop_order_status_history_notify_client').val(),
       local_part_email: '<?php echo $local_part_email?>',
       domain_email: '<?php echo $whatever_domain_variable_here?>' }


答:
Here is the working solution:

```<code>package main

import (
    "github.com/Knetic/govaluate"
    "fmt"
    "time"
)

func main()  {
    expression, err := govaluate.NewEvaluableExpression("first_name == 'Julian' && emp_id == 302 && birth_date >= '2016-12-15' && birth_date <= '2016-12-25'")

    parameters := make(map[string]interface{}, 8)
    parameters["first_name"] = "Julian"
    parameters["emp_id"] = 302
    iso8601 := "2006-01-02"
    birthDate, err := time.ParseInLocation(iso8601, "2016-12-15", time.Local)
    parameters["birth_date"] = birthDate.Unix()
    result, err := expression.Evaluate(parameters)

    if err != nil {
        fmt.Println("Error while evaluating the expression")
    }

    if result.(bool) {
        fmt.Println("Condition is evaluated to true")
    } else {
        fmt.Println("Condition is evaluated to false")
    }
}
</code>```

Thank you Library owner and @RayfenWindspear for helping me out on this! Really appreciate!

Title: Compare date values in expression using govaluate

Body:
Here is the working solution:

package main

import (
    "github.com/Knetic/govaluate"
    "fmt"
    "time"
)

func main()  {
    expression, err := govaluate.NewEvaluableExpression("first_name == 'Julian' && emp_id == 302 && birth_date >= '2016-12-15' && birth_date <= '2016-12-25'")

    parameters := make(map[string]interface{}, 8)
    parameters["first_name"] = "Julian"
    parameters["emp_id"] = 302
    iso8601 := "2006-01-02"
    birthDate, err := time.ParseInLocation(iso8601, "2016-12-15", time.Local)
    parameters["birth_date"] = birthDate.Unix()
    result, err := expression.Evaluate(parameters)

    if err != nil {
        fmt.Println("Error while evaluating the expression")
    }

    if result.(bool) {
        fmt.Println("Condition is evaluated to true")
    } else {
        fmt.Println("Condition is evaluated to false")
    }
}

Thank you Library owner and @RayfenWindspear for helping me out on this! Really appreciate!


问:
How would i add a drop down menu to my jquery table which uses mysql?
So currently I am trying to figure out how I would add a dropdown menu to the code I've posted below. I've searched the internet but could not find a way that worked for me, I'm very new to coding so this is kind of difficult for me others may find this easy.</p>

```<code><table class="table table-bordered table-striped">
  <thead> <!-- add class="thead-inverse" for a dark header -->
    <tr>
        <th>ID</th>
        <th>USERNAME</th>
        <th>Crime(s)</th>
        <th>Active</th>
        <th>EDIT</th>
    </tr>
  </thead>
  <tfoot>
    <tr>
    </tr>
        </div>
      </th>
  </tfoot>';
  if(mysqli_num_rows($result) > 0)
  {
      while($row = mysqli_fetch_array($result))
      {
           $output .= '
                <tr>
                     <td>'.$row["id"].'</td>
                     <td class="username" data-id1="'.$row["id"].'" contenteditable>'.$row["name"].'</td>
                     <td class="crime" data-id2="'.$row["id"].'" contenteditable>'.$row["crime"].'</td>
                     <td class="activated" data-id2="'.$row["id"].'" contenteditable>'.$row["activated"].'</td>
                     <td><button type="button" name="delete_btn" data-id3="'.$row["id"].'" class="btn btn-xs btn-danger btn_delete">DELETE</button></td>
                </tr>
           ';
      }
      $output .= '
         <tr>
              <td></td>
              <td id="name" contenteditable></td>
              <td id="crime" contenteditable></td>
              <td id="activated" contenteditable></td>
              <td><button type="button" name="btn_add" id="btn_add" class="btn btn-xs btn-success">ADD ACCOUNT</button></td>
           </tr>
      ';
   }
   else
   {
      $output .= '<tr>
                          <td colspan="4">Data not Found</td>
                  </tr>';
   }
   $output .= '</table>
      </div>';
   echo $output;
 ?>
</code>```

答:
Since you mentioned that you'd like to add the dropdown to the activated section of your table and that it should contain Yes, No and Being Verified, you can update that table column to be

```<code><td class="activated" data-id2="'.$row["id"].'" contenteditable>
        <select name="activated" id="activated">
            <option value="Yes" '.(($row["activated"] == "Yes") ? 'selected="selected"':"").'>Yes</option>
            <option value="No" '.(($row["activated"] == "No") ? 'selected="selected"':"").'>No</option>
            <option value="Being Verified" '.(($row["activated"] == "Being Verified") ? 'selected="selected"':"").'>Being Verified</option>
        </select>
    </td>
</code>```

This would allow the value from the db $row["activated"] get automatically selected in the dropdown.

Body:
So currently I am trying to figure out how I would add a dropdown menu to the code I've posted below. I've searched the internet but could not find a way that worked for me, I'm very new to coding so this is kind of difficult for me others may find this easy.

        ID
        USERNAME
        Crime(s)
        Active
        EDIT

';
  if(mysqli_num_rows($result) > 0)
  {
      while($row = mysqli_fetch_array($result))
      {
           $output .= '

                     '.$row["id"].'
                     '.$row["name"].'
                     '.$row["crime"].'
                     '.$row["activated"].'
                     <button type="button" name="delete_btn" data-id3="'.$row["id"].'" class="btn btn-xs btn-danger btn_delete">DELETE</button>

           ';
      }
      $output .= '

              <button type="button" name="btn_add" id="btn_add" class="btn btn-xs btn-success">ADD ACCOUNT</button>

      ';
   }
   else
   {
      $output .= '

                          Data not Found

';
   }
   $output .= '

';
   echo $output;
 ?>

Body:
Since you mentioned that you'd like to add the dropdown to the activated section of your table and that it should contain Yes, No and Being Verified, you can update that table column to be

<td class="activated" data-id2="'.$row["id"].'" contenteditable>
        <select name="activated" id="activated">
            <option value="Yes" '.(($row["activated"] == "Yes") ? 'selected="selected"':"").'>Yes</option>
            <option value="No" '.(($row["activated"] == "No") ? 'selected="selected"':"").'>No</option>
            <option value="Being Verified" '.(($row["activated"] == "Being Verified") ? 'selected="selected"':"").'>Being Verified</option>
        </select>
    </td>

This would allow the value from the db $row["activated"] get automatically selected in the dropdown.


问:
allauth problems extending SignupForm class
I keep finding outdated solutions that don't seem to be working.

I'm trying to change the error messages from English to Hebrew, for my website in django-allauth, I haven't checked if their are any translations because I would like to write them myself anyhow.

I tried changing for example the duplicate email error with the following code.

forms.py

```<code>from allauth.account.forms import SignupForm

class CustomSignupForm(SignupForm):
    def raise_duplicate_email_error(self):
        raise forms.ValidationError("שם משתמש כבר קיים עם כתובת אימייל")
</code>```

base.py (base settings file)

```<code>SOCIALACCOUNT_FORMS = {
    'signup': 'website.forms.CustomSignupForm',
}
</code>```

this resulted in the following error:

```<code>__init__() got an unexpected keyword argument 'sociallogin'
</code>```

Traceback:

```<code>File "/home/david/.virtualenvs/sikumim/lib/python3.4/site-packages/django/core/handlers/base.py" in get_response
  132.                     response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "/home/david/.virtualenvs/sikumim/lib/python3.4/site-packages/django/views/generic/base.py" in view
  71.             return self.dispatch(request, *args, **kwargs)
File "/home/david/.virtualenvs/sikumim/lib/python3.4/site-packages/allauth/socialaccount/views.py" in dispatch
  38.         return super(SignupView, self).dispatch(request, *args, **kwargs)
File "/home/david/.virtualenvs/sikumim/lib/python3.4/site-packages/allauth/account/views.py" in dispatch
  68.                                             **kwargs)
File "/home/david/.virtualenvs/sikumim/lib/python3.4/site-packages/allauth/account/views.py" in dispatch
  151.                                                           **kwargs)
File "/home/david/.virtualenvs/sikumim/lib/python3.4/site-packages/django/views/generic/base.py" in dispatch
  89.         return handler(request, *args, **kwargs)
File "/home/david/.virtualenvs/sikumim/lib/python3.4/site-packages/django/views/generic/edit.py" in get
  205.         form = self.get_form()
File "/home/david/.virtualenvs/sikumim/lib/python3.4/site-packages/django/views/generic/edit.py" in get_form
  74.         return form_class(**self.get_form_kwargs())
File "/home/david/.virtualenvs/sikumim/lib/python3.4/site-packages/allauth/account/forms.py" in __init__
  289.         super(SignupForm, self).__init__(*args, **kwargs)
File "/home/david/.virtualenvs/sikumim/lib/python3.4/site-packages/allauth/account/forms.py" in __init__
  223.         super(BaseSignupForm, self).__init__(*args, **kwargs)

Exception Type: TypeError at /accounts/social/signup/
Exception Value: __init__() got an unexpected keyword argument 'sociallogin'
</code>```

What am I doing wrong?

答:
You are inheriting from allauth.account.forms.SignupForm but using it in the setting SOCIALACCOUNT_FORMS, which is for social accounts. Your code should look like this:

website/forms.py

```<code>from allauth.socialaccount.forms import SignupForm

class CustomSignupForm(SignupForm):
     def raise_duplicate_email_error(self):
         raise forms.ValidationError("שם משתמש כבר קיים עם כתובת אימייל")
</code>```

settings.py

```<code>SOCIALACCOUNT_FORMS = {
    'signup': 'website.forms.CustomSignupForm',
}
</code>```

Body:
I keep finding outdated solutions that don't seem to be working.

I'm trying to change the error messages from English to Hebrew, for my website in django-allauth, I haven't checked if their are any translations because I would like to write them myself anyhow.

I tried changing for example the duplicate email error with the following code.

forms.py

from allauth.account.forms import SignupForm

class CustomSignupForm(SignupForm):
    def raise_duplicate_email_error(self):
        raise forms.ValidationError("שם משתמש כבר קיים עם כתובת אימייל")

base.py (base settings file)

SOCIALACCOUNT_FORMS = {
    'signup': 'website.forms.CustomSignupForm',
}

this resulted in the following error:

__init__() got an unexpected keyword argument 'sociallogin'

Traceback:

File "/home/david/.virtualenvs/sikumim/lib/python3.4/site-packages/django/core/handlers/base.py" in get_response
  132.                     response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "/home/david/.virtualenvs/sikumim/lib/python3.4/site-packages/django/views/generic/base.py" in view
  71.             return self.dispatch(request, *args, **kwargs)
File "/home/david/.virtualenvs/sikumim/lib/python3.4/site-packages/allauth/socialaccount/views.py" in dispatch
  38.         return super(SignupView, self).dispatch(request, *args, **kwargs)
File "/home/david/.virtualenvs/sikumim/lib/python3.4/site-packages/allauth/account/views.py" in dispatch
  68.                                             **kwargs)
File "/home/david/.virtualenvs/sikumim/lib/python3.4/site-packages/allauth/account/views.py" in dispatch
  151.                                                           **kwargs)
File "/home/david/.virtualenvs/sikumim/lib/python3.4/site-packages/django/views/generic/base.py" in dispatch
  89.         return handler(request, *args, **kwargs)
File "/home/david/.virtualenvs/sikumim/lib/python3.4/site-packages/django/views/generic/edit.py" in get
  205.         form = self.get_form()
File "/home/david/.virtualenvs/sikumim/lib/python3.4/site-packages/django/views/generic/edit.py" in get_form
  74.         return form_class(**self.get_form_kwargs())
File "/home/david/.virtualenvs/sikumim/lib/python3.4/site-packages/allauth/account/forms.py" in __init__
  289.         super(SignupForm, self).__init__(*args, **kwargs)
File "/home/david/.virtualenvs/sikumim/lib/python3.4/site-packages/allauth/account/forms.py" in __init__
  223.         super(BaseSignupForm, self).__init__(*args, **kwargs)

Exception Type: TypeError at /accounts/social/signup/
Exception Value: __init__() got an unexpected keyword argument 'sociallogin'

What am I doing wrong?

Body:
You are inheriting from allauth.account.forms.SignupForm but using it in the setting SOCIALACCOUNT_FORMS, which is for social accounts. Your code should look like this:

website/forms.py

from allauth.socialaccount.forms import SignupForm

class CustomSignupForm(SignupForm):
     def raise_duplicate_email_error(self):
         raise forms.ValidationError("שם משתמש כבר קיים עם כתובת אימייל")

settings.py

SOCIALACCOUNT_FORMS = {
    'signup': 'website.forms.CustomSignupForm',
}


问:
How can I delete unwanted elements from this JSON array?
I have the following response from an API containing a JSON array and I am trying to remove all elements except for title, column, and searchSourceJSON:

```<code>"hits": [
    {
        "_index": ".example_demo",
        "_type": "search",
        "_id": "demo-Media-Integration-Enabled",
        "_score": 1,
        "_source": {
            "title": "demo Media Integration - Enabled",
            "description": "",
            "hits": 0,
            "columns": [
                "_source"
            ],
            "sort": [
                "timestamp",
                "asc"
            ],
            "version": 1,
            "exampleSavedObjectMeta": {
                "searchSourceJSON": "{\"index\":\"[demo-]YYYY.MM\",\"highlight\":{\"pre_tags\":[\"@example-highlighted-field@\"],\"post_tags\":[\"@/example-highlighted-field@\"],\"fields\":{\"*\":{}},\"fragment_size\":2147483647},\"filter\":[{\"meta\":{\"negate\":false,\"index\":\"[demo-]YYYY.MM\",\"key\":\"_type\",\"value\":\"Media Integration\",\"disabled\":false},\"query\":{\"match\":{\"_type\":{\"query\":\"Media Integration\",\"type\":\"phrase\"}}}},{\"meta\":{\"negate\":false,\"index\":\"[demo-]YYYY.MM\",\"key\":\"Action\",\"value\":\"Enable\",\"disabled\":false},\"query\":{\"match\":{\"Action\":{\"query\":\"Enable\",\"type\":\"phrase\"}}}}],\"query\":{\"query_string\":{\"query\":\"*\",\"analyze_wildcard\":true}}}"
            }
        }
    },
    {
        "_index": ".example_demo",
        "_type": "search",
        "_id": "demo-Media-Import-True",
        "_score": 1,
        "_source": {
            "title": "demo Media Import - True",
            "description": "",
            "hits": 0,
            "columns": [
                "FormFactor",
                "_type",
                "Identity"
            ],
            "sort": [
                "_type",
                "asc"
            ],
            "version": 1,
            "exampleSavedObjectMeta": {
                "searchSourceJSON": "{\"index\":\"[demo-]YYYY.MM\",\"query\":{\"query_string\":{\"analyze_wildcard\":true,\"query\":\"*\"}},\"highlight\":{\"pre_tags\":[\"@example-highlighted-field@\"],\"post_tags\":[\"@/example-highlighted-field@\"],\"fields\":{\"*\":{}},\"fragment_size\":2147483647},\"filter\":[{\"meta\":{\"disabled\":false,\"index\":\"[demo-]YYYY.MM\",\"key\":\"_type\",\"negate\":false,\"value\":\"Media Import\"},\"query\":{\"match\":{\"_type\":{\"query\":\"Media Import\",\"type\":\"phrase\"}}}},{\"meta\":{\"negate\":false,\"index\":\"[demo-]YYYY.MM\",\"key\":\"Successful\",\"value\":\"True\",\"disabled\":false},\"query\":{\"match\":{\"Successful\":{\"query\":\"True\",\"type\":\"phrase\"}}}}]}"
            }
        }
    }
]
</code>```

Could someone help me figure out how to delete the unwanted elements from this JSON document using JavaScript?

EDIT: Answered, thank you everyone for the great information!

答:
```<code>var result=(function(){//IIFE to enshure garbage collection
  var hits=[...];//your data
  return hits.map(hit=>{hit["_source"].title,hit["_source"].colums,hit.exampleSavedObjectMeta.searchSourceJSON});
});
</code>```

This deletes all properties (garbage collects them) except the wanted.

Body:
I have the following response from an API containing a JSON array and I am trying to remove all elements except for title, column, and searchSourceJSON:

"hits": [
    {
        "_index": ".example_demo",
        "_type": "search",
        "_id": "demo-Media-Integration-Enabled",
        "_score": 1,
        "_source": {
            "title": "demo Media Integration - Enabled",
            "description": "",
            "hits": 0,
            "columns": [
                "_source"
            ],
            "sort": [
                "timestamp",
                "asc"
            ],
            "version": 1,
            "exampleSavedObjectMeta": {
                "searchSourceJSON": "{\"index\":\"[demo-]YYYY.MM\",\"highlight\":{\"pre_tags\":[\"@example-highlighted-field@\"],\"post_tags\":[\"@/example-highlighted-field@\"],\"fields\":{\"*\":{}},\"fragment_size\":2147483647},\"filter\":[{\"meta\":{\"negate\":false,\"index\":\"[demo-]YYYY.MM\",\"key\":\"_type\",\"value\":\"Media Integration\",\"disabled\":false},\"query\":{\"match\":{\"_type\":{\"query\":\"Media Integration\",\"type\":\"phrase\"}}}},{\"meta\":{\"negate\":false,\"index\":\"[demo-]YYYY.MM\",\"key\":\"Action\",\"value\":\"Enable\",\"disabled\":false},\"query\":{\"match\":{\"Action\":{\"query\":\"Enable\",\"type\":\"phrase\"}}}}],\"query\":{\"query_string\":{\"query\":\"*\",\"analyze_wildcard\":true}}}"
            }
        }
    },
    {
        "_index": ".example_demo",
        "_type": "search",
        "_id": "demo-Media-Import-True",
        "_score": 1,
        "_source": {
            "title": "demo Media Import - True",
            "description": "",
            "hits": 0,
            "columns": [
                "FormFactor",
                "_type",
                "Identity"
            ],
            "sort": [
                "_type",
                "asc"
            ],
            "version": 1,
            "exampleSavedObjectMeta": {
                "searchSourceJSON": "{\"index\":\"[demo-]YYYY.MM\",\"query\":{\"query_string\":{\"analyze_wildcard\":true,\"query\":\"*\"}},\"highlight\":{\"pre_tags\":[\"@example-highlighted-field@\"],\"post_tags\":[\"@/example-highlighted-field@\"],\"fields\":{\"*\":{}},\"fragment_size\":2147483647},\"filter\":[{\"meta\":{\"disabled\":false,\"index\":\"[demo-]YYYY.MM\",\"key\":\"_type\",\"negate\":false,\"value\":\"Media Import\"},\"query\":{\"match\":{\"_type\":{\"query\":\"Media Import\",\"type\":\"phrase\"}}}},{\"meta\":{\"negate\":false,\"index\":\"[demo-]YYYY.MM\",\"key\":\"Successful\",\"value\":\"True\",\"disabled\":false},\"query\":{\"match\":{\"Successful\":{\"query\":\"True\",\"type\":\"phrase\"}}}}]}"
            }
        }
    }
]

Could someone help me figure out how to delete the unwanted elements from this JSON document using JavaScript?

EDIT: Answered, thank you everyone for the great information!

Body:
var result=(function(){//IIFE to enshure garbage collection
  var hits=[...];//your data
  return hits.map(hit=>{hit["_source"].title,hit["_source"].colums,hit.exampleSavedObjectMeta.searchSourceJSON});
});

This deletes all properties (garbage collects them) except the wanted.


问:
Alarm Functionality In ReactNative For Android And iOS
I want to make app that play music every day at specific time (for example : 07:00) even if the app in background or turned off

I had done it in android with Java & Android SDK using Alarm Manager , i'm looking for something like that for ReactNative

I had searched for libraries but i did not found useful resources

答: check this out https://github.com/wmcmahan/react-native-calendar-events , The alarms associated with the calendar event, as an array of alarm objects.</p>


问:
Convert string in textbox to datetime column in sql
Good day.
I'm very newbie in asp.net/c#/linq/etc, and I'm  trying to figure it all out.
But it's need to do one small project.

In my view I have a table with datetime/string values and i need to insert this values to mssql database.

On View I have several Html.TextBox'es. By clicking button, TextBox is filled by current datetime.
View header(JS):

```<code>   <script type="text/javascript">
        function setDate(boxID) {
            var dateNow = new Date();
            var dd = dateNow.getDate();
            var mm = dateNow.getMonth() + 1;
            var yy = dateNow.getFullYear();
            var hh = dateNow.getHours();
            var MM = dateNow.getMinutes();
            var ss = dateNow.getSeconds();
            if (dd < 10) { dd = '0' + dd }
            if (mm < 10) { mm = '0' + mm }
            if (MM < 10) { MM = '0' + MM }
            if (ss < 10) { ss = '0' + ss }
            var today = dd + '-' + mm + '-' + yy + ' ' + hh + ':' + MM + ':' + ss;
            document.getElementById(boxID).value = today;
        }
    </script>
</code>```

View body:

```<code><div class="divTableCell">
   @Html.TextBox("p1_t1")
   <input type="button" value="OK" onclick='setDate("p1_t1")' />
</div>
<div class="divTableCell">
    @Html.TextBox("p1_notice")
</div>
<button id="result "type="submit">Insert data</button>
</code>```

By clicking the last button i'm trying to insert this values to external database. Table contains columns p1_notice varchar(250) and p1_t1 datetime;

Controller:

```<code>public ActionResult EntranceInspection()
{
    return View();
}

EntranceInspectionTableDataContext d = new EntranceInspectionTableDataContext();

public ActionResult EntranceInspectionResult()
{

    EntranceInspection s = new EntranceInspection();
    s.p1_notice = Request["p1_notice"]; // to SQL - ok
    s.p1_t1 = Request["p1_t1"]; // error convert string to datetime
    d.EntranceInspection.InsertOnSubmit(s);
    d.SubmitChanges();
    return View("EntranceInspection");
}
</code>```

Is there any acceptable way to convert value in textbox to datetime and insert to datetime-column? Or I need to do something different at the start?

Thx

答:
You must convert the text value into the datetime thus:

```<code>s.p1_t1 = Convert.ToDateTime(Request["p1_t1"]);
</code>```

This will help you to insert datetime value in database without error. But, maybe can be usefull you garantie that p1_t1 has not a null value if in database the field is not nullabe.
If it is nullabe, you should insert datemin value or other value that is logical for your business.

Body:
Good day.
I'm very newbie in asp.net/c#/linq/etc, and I'm  trying to figure it all out.
But it's need to do one small project.

In my view I have a table with datetime/string values and i need to insert this values to mssql database.

On View I have several Html.TextBox'es. By clicking button, TextBox is filled by current datetime.
View header(JS):

View body:

   @Html.TextBox("p1_t1")
   <input type="button" value="OK" onclick='setDate("p1_t1")' />

    @Html.TextBox("p1_notice")

<button id="result "type="submit">Insert data</button>

By clicking the last button i'm trying to insert this values to external database. Table contains columns p1_notice varchar(250) and p1_t1 datetime;

Controller:

public ActionResult EntranceInspection()
{
    return View();
}

EntranceInspectionTableDataContext d = new EntranceInspectionTableDataContext();

public ActionResult EntranceInspectionResult()
{

    EntranceInspection s = new EntranceInspection();
    s.p1_notice = Request["p1_notice"]; // to SQL - ok
    s.p1_t1 = Request["p1_t1"]; // error convert string to datetime
    d.EntranceInspection.InsertOnSubmit(s);
    d.SubmitChanges();
    return View("EntranceInspection");
}

Is there any acceptable way to convert value in textbox to datetime and insert to datetime-column? Or I need to do something different at the start?

Thx

Body:
You must convert the text value into the datetime thus:

s.p1_t1 = Convert.ToDateTime(Request["p1_t1"]);

This will help you to insert datetime value in database without error. But, maybe can be usefull you garantie that p1_t1 has not a null value if in database the field is not nullabe.
If it is nullabe, you should insert datemin value or other value that is logical for your business.


答:
```<code>StringBuilder requestBuilder = new StringBuilder("Request from Centercord.\n");
StringBuilder responseBuilder = new StringBuilder("Response from Centercord.\n");

boolean isResponse = false;
for (String line:getLinesFromLogFile()) {
  if (line.startsWith("Response")) {
      if(isResponse)
        responseBuilder.append("\n");
      isResponse = true;
  } else if (line.startsWith("Request")) {
      if(!isResponse)
        requestBuilder.append("\n");
      isResponse = false;
  } else {
      if (isResponse) {
         responseBuilder.append(line).append("\n");
      } else {
         requestBuilder.append(line).append("\n");
      }
  }
}
</code>```

Now dump the contents of both StringBuilders to the target files.

Title: Parsing a log file in Java

Body:
All,

I have a log file with the below content.

Request from Centercord.
2010-12-14 12:42:13.724 [ 6796] ****************************
2010-12-14 12:42:13.724 [ 6796] 1111111111111111
2010-12-14 12:42:13.724 [ 6796]22222222222

Response from Centercord.
2010-12-14 12:42:21.802 [ 5960] 11111111111111
2010-12-14 12:42:21.802 [ 5960]  ffffffffffffffffffffffffffff
2010-12-14 12:42:21.802 [ 5960]  tttttttttttttttttttttttttttt

Request from Centercord.
2010-12-14 12:42:13.724 [ 6796] ****************************

I need to create two log files one is for storing all the Request details and the other one is for storing all the Response details. How can I parse this and prepare two log files?.

I need the below answer.

Log 1:

Request from Centercord.
2010-12-14 12:42:13.724 [ 6796] ****************************
2010-12-14 12:42:13.724 [ 6796] 1111111111111111
2010-12-14 12:42:13.724 [ 6796]22222222222

2010-12-14 12:42:13.724 [ 6796] ****************************

Log 2:

Response from Centercord.
2010-12-14 12:42:21.802 [ 5960] 11111111111111
2010-12-14 12:42:21.802 [ 5960]  ffffffffffffffffffffffffffff
2010-12-14 12:42:21.802 [ 5960]  tttttttttttttttttttttttttttt

Regards,
Kanagaraj

Body:
StringBuilder requestBuilder = new StringBuilder("Request from Centercord.\n");
StringBuilder responseBuilder = new StringBuilder("Response from Centercord.\n");

boolean isResponse = false;
for (String line:getLinesFromLogFile()) {
  if (line.startsWith("Response")) {
      if(isResponse)
        responseBuilder.append("\n");
      isResponse = true;
  } else if (line.startsWith("Request")) {
      if(!isResponse)
        requestBuilder.append("\n");
      isResponse = false;
  } else {
      if (isResponse) {
         responseBuilder.append(line).append("\n");
      } else {
         requestBuilder.append(line).append("\n");
      }
  }
}

Now dump the contents of both StringBuilders to the target files.


问:
Why difference between two pointers is not equals to size of type?
I have the simple program:

```<code>#include <iostream>

using namespace std;

int main()
{
    int a = 5;
    int b = 6;
    int* p1 = &a;
    int* p2 = &b;
    std::cout << p1 << " " << p2 << " ,sizeof(int)=" << sizeof(int) << std::endl;

    system("pause");
    return 0;
}
</code>```

It produces the following output:

```<code>00DBF9B8 00DBF9AC ,sizeof(int)=4
</code>```

but, 00DBF9B8 - 00DBF9AC == С. I cannot understand this result.

If I modify the program like this:

```<code>#include <iostream>

using namespace std;

int main()
{
    static int a = 5;
    static int b = 6;
    int* p1 = &a;
    int* p2 = &b;
    std::cout << p1 << " " << p2 << " ,sizeof(int)=" << sizeof(int) << std::endl;

    system("pause");
    return 0;
}
</code>```

I got correct result:

```<code>00394000 00394004 ,sizeof(int)=4
</code>```

答:
There is no guarantee that local variables (or even static variables) are put on consecutive memory addresses. And actually it would be undefined behaviour if you substracted two pointer values that do not point into the same array.

But you could use pointer arithmetics as follows:

```<code>int main()
{
    int a;
    int* p1 = &a;
    int* p2 = p1+1;
    std::cout << p1 << " " << p2 << " ,sizeof(int)=" << sizeof(int) << std::endl;

    return 0;
}
</code>```

Note that a single integral value may be considered as an array of size 1, and that p1+1 therefore points to "one after the last element of an array", such that the operation p2 = p1+1 is actually valid (dereferencing p2 then would not be valid, of course).

Body:
I have the simple program:

#include <iostream>

using namespace std;

int main()
{
    int a = 5;
    int b = 6;
    int* p1 = &a;
    int* p2 = &b;
    std::cout << p1 << " " << p2 << " ,sizeof(int)=" << sizeof(int) << std::endl;

    system("pause");
    return 0;
}

It produces the following output:

00DBF9B8 00DBF9AC ,sizeof(int)=4

but, 00DBF9B8 - 00DBF9AC == С. I cannot understand this result.

If I modify the program like this:

#include <iostream>

using namespace std;

int main()
{
    static int a = 5;
    static int b = 6;
    int* p1 = &a;
    int* p2 = &b;
    std::cout << p1 << " " << p2 << " ,sizeof(int)=" << sizeof(int) << std::endl;

    system("pause");
    return 0;
}

I got correct result:

00394000 00394004 ,sizeof(int)=4

Body:
There is no guarantee that local variables (or even static variables) are put on consecutive memory addresses. And actually it would be undefined behaviour if you substracted two pointer values that do not point into the same array.

But you could use pointer arithmetics as follows:

int main()
{
    int a;
    int* p1 = &a;
    int* p2 = p1+1;
    std::cout << p1 << " " << p2 << " ,sizeof(int)=" << sizeof(int) << std::endl;

    return 0;
}

Note that a single integral value may be considered as an array of size 1, and that p1+1 therefore points to "one after the last element of an array", such that the operation p2 = p1+1 is actually valid (dereferencing p2 then would not be valid, of course).


问:
How to recompile a user defined function in SQL Server when a dependency is updated?
I have a table valued function A that calls table valued functions B and C. Functions B and C are being updated (altered) as part of a migration however table A is not being updated as a result of this. How can I rebuild A without altering it?

Example (rollback is just added for convenience) SQL Fiddle:

```<code>BEGIN TRANSACTION

SET NOCOUNT ON;

CREATE TABLE DOGS
(
    Id UNIQUEIDENTIFIER PRIMARY KEY,
    Name NVARCHAR(255) NOT NULL,
    Age INT NOT NULL,
)

INSERT INTO DOGS VALUES (NEWID(), 'Rocky', 12);
INSERT INTO DOGS VALUES (NEWID(), 'Sammy', 2);
INSERT INTO DOGS VALUES (NEWID(), 'Porthos', 5);

CREATE TABLE CATS
(
    Id UNIQUEIDENTIFIER PRIMARY KEY,
    Name NVARCHAR(255) NOT NULL,
    Age INT NOT NULL,
)

INSERT INTO CATS VALUES (NEWID(), 'Mr. T', 15);
INSERT INTO CATS VALUES (NEWID(), 'Old Timer', 37);
INSERT INTO CATS VALUES (NEWID(), 'Mittens', 1);

SET NOCOUNT OFF;

GO
CREATE FUNCTION [GetCatsYoungerThan]
(
   @age INT
)
RETURNS TABLE AS
RETURN (
    SELECT Name FROM CATS WHERE Age < @age
);
GO

CREATE FUNCTION [GetDogsYoungerThan]
(
   @age INT
)
RETURNS TABLE AS
RETURN (
    SELECT Name FROM DOGS WHERE Age < @age
);
GO

CREATE FUNCTION [GetAnimalsYoungerThan]
(
   @age INT
)
RETURNS TABLE AS
RETURN (
    SELECT * FROM [GetCatsYoungerThan](@age)
    UNION
    SELECT * FROM [GetDogsYoungerThan](@age)
);
GO

ALTER FUNCTION [dbo].[GetDogsYoungerThan]
(
   @age INT
)
RETURNS TABLE AS
RETURN (
    SELECT Name, Age FROM DOGS WHERE Age < @age
);
GO

ALTER FUNCTION [dbo].[GetCatsYoungerThan]
(
   @age INT
)
RETURNS TABLE AS
RETURN (
    SELECT Name, Age FROM CATS WHERE Age < @age
);
GO

EXEC sp_recompile '[GetAnimalsYoungerThan]';

--results
SELECT * FROM [GetAnimalsYoungerThan](15);

--Shows expected results
SELECT * FROM [GetCatsYoungerThan](15)
UNION
SELECT * FROM [GetDogsYoungerThan](15)

ROLLBACK TRANSACTION
</code>```

Result:

```<code>Name
-------
Mittens
Porthos
Rocky
Sammy
</code>```

Expected Result:

```<code>Name    Age
-----------
Mittens 1
Porthos 5
Rocky   12
Sammy   2
</code>```

My expectation is that sp_recompile would cause the function to be recompiled; however, that is either not happening or that is not good enough to update the values return by A.

My original plan was to recompile all the objects in the database using the following code but that requires sp_recompile to work.

```<code>DECLARE @ObjectName NVARCHAR(MAX);
DECLARE MY_CURSOR CURSOR
  LOCAL STATIC READ_ONLY FORWARD_ONLY
FOR
SELECT [ROUTINE_SCHEMA] + '.' + [ROUTINE_NAME] AS [NAME]
FROM information_schema.routines
WHERE [ROUTINE_SCHEMA] = 'my_domain';

OPEN MY_CURSOR
FETCH NEXT FROM MY_CURSOR INTO @ObjectName
WHILE @@FETCH_STATUS = 0
BEGIN
    PRINT 'Recompiling ' + @ObjectName + '...';
    EXEC sp_recompile @ObjectName;
    FETCH NEXT FROM MY_CURSOR INTO @ObjectName;
END
CLOSE MY_CURSOR
DEALLOCATE MY_CURSOR
</code>```

Thank you in advanced for your help.

答:
This is a result of using SELECT * and the result of that performing early schema binding of your TVF.

You can get the desired result by running:

```<code>sp_refreshsqlmodule <tvf-name>
</code>```

Which effectively re-binds the schema to the TVF, without the verbosity of an ALTER x...

But in the long run, try and avoid using SELECT *.

Body:
I have a table valued function A that calls table valued functions B and C. Functions B and C are being updated (altered) as part of a migration however table A is not being updated as a result of this. How can I rebuild A without altering it?

Example (rollback is just added for convenience) SQL Fiddle:

BEGIN TRANSACTION

SET NOCOUNT ON;

CREATE TABLE DOGS
(
    Id UNIQUEIDENTIFIER PRIMARY KEY,
    Name NVARCHAR(255) NOT NULL,
    Age INT NOT NULL,
)

INSERT INTO DOGS VALUES (NEWID(), 'Rocky', 12);
INSERT INTO DOGS VALUES (NEWID(), 'Sammy', 2);
INSERT INTO DOGS VALUES (NEWID(), 'Porthos', 5);

CREATE TABLE CATS
(
    Id UNIQUEIDENTIFIER PRIMARY KEY,
    Name NVARCHAR(255) NOT NULL,
    Age INT NOT NULL,
)

INSERT INTO CATS VALUES (NEWID(), 'Mr. T', 15);
INSERT INTO CATS VALUES (NEWID(), 'Old Timer', 37);
INSERT INTO CATS VALUES (NEWID(), 'Mittens', 1);

SET NOCOUNT OFF;

GO
CREATE FUNCTION [GetCatsYoungerThan]
(
   @age INT
)
RETURNS TABLE AS
RETURN (
    SELECT Name FROM CATS WHERE Age < @age
);
GO

CREATE FUNCTION [GetDogsYoungerThan]
(
   @age INT
)
RETURNS TABLE AS
RETURN (
    SELECT Name FROM DOGS WHERE Age < @age
);
GO

CREATE FUNCTION [GetAnimalsYoungerThan]
(
   @age INT
)
RETURNS TABLE AS
RETURN (
    SELECT * FROM [GetCatsYoungerThan](@age)
    UNION
    SELECT * FROM [GetDogsYoungerThan](@age)
);
GO

ALTER FUNCTION [dbo].[GetDogsYoungerThan]
(
   @age INT
)
RETURNS TABLE AS
RETURN (
    SELECT Name, Age FROM DOGS WHERE Age < @age
);
GO

ALTER FUNCTION [dbo].[GetCatsYoungerThan]
(
   @age INT
)
RETURNS TABLE AS
RETURN (
    SELECT Name, Age FROM CATS WHERE Age < @age
);
GO

EXEC sp_recompile '[GetAnimalsYoungerThan]';

--results
SELECT * FROM [GetAnimalsYoungerThan](15);

--Shows expected results
SELECT * FROM [GetCatsYoungerThan](15)
UNION
SELECT * FROM [GetDogsYoungerThan](15)

ROLLBACK TRANSACTION

Result:

Name
-------
Mittens
Porthos
Rocky
Sammy

Expected Result:

Name    Age
-----------
Mittens 1
Porthos 5
Rocky   12
Sammy   2

My expectation is that sp_recompile would cause the function to be recompiled; however, that is either not happening or that is not good enough to update the values return by A.

My original plan was to recompile all the objects in the database using the following code but that requires sp_recompile to work.

DECLARE @ObjectName NVARCHAR(MAX);
DECLARE MY_CURSOR CURSOR
  LOCAL STATIC READ_ONLY FORWARD_ONLY
FOR
SELECT [ROUTINE_SCHEMA] + '.' + [ROUTINE_NAME] AS [NAME]
FROM information_schema.routines
WHERE [ROUTINE_SCHEMA] = 'my_domain';

OPEN MY_CURSOR
FETCH NEXT FROM MY_CURSOR INTO @ObjectName
WHILE @@FETCH_STATUS = 0
BEGIN
    PRINT 'Recompiling ' + @ObjectName + '...';
    EXEC sp_recompile @ObjectName;
    FETCH NEXT FROM MY_CURSOR INTO @ObjectName;
END
CLOSE MY_CURSOR
DEALLOCATE MY_CURSOR

Thank you in advanced for your help.

Body:
This is a result of using SELECT * and the result of that performing early schema binding of your TVF.

You can get the desired result by running:

sp_refreshsqlmodule <tvf-name>

Which effectively re-binds the schema to the TVF, without the verbosity of an ALTER x...

But in the long run, try and avoid using SELECT *.


问:
Perl Path::Class::file with "use constant" gives blessed ref, not string - why?
Running Perl 5.18 on Ubuntu 14.04 LTS, I wanted to create some pathname constants so I did

```<code>use Path::Class;
use constant FILEPATH => file('directory', 'filename');
</code>```

However, when I came to use the constant in a hash aggregate ...

```<code>my $hash = { filepath => FILEPATH };
use Data::Dumper;
print Dumper $href;
</code>```

... I was surprised to discover that the value of the filepath key was a blessed reference, not the string result from the function call that I was expecting.

I can work around the problem like this ...

```<code>use constant FILEPATH => file('directory', 'filename') . "";
</code>```

... which forces the Perl interpreter to evaluate the blessed reference, but

(a) is there a better way, and
(b) what the heck is going on?!

I know that use constant is evaluated in a list context, but normally use constant MYCONST => mysub(arg1, arg2); does The Right Thing, evaluates the subroutine call and uses the return value. What's the cleverness with Path::Class::file that breaks this expectation?

答:
You're right about Path::Class::file returning an object.  That's what all the "bless" stuff was in the Dumper output.  Sorry I didn't realise that sooner.

As you'll see from my comments, I ran into the problem using HTML::Tiny, which you can see as follows:-

```<code>$ perl -MPath::Class -MHTML::Tiny -le 'print HTML::Tiny->new(mode=>"html")->form({action=>file("cgi-bin", "script")})'
<form action></form>
</code>```

As you can see, the action attribute is missing the path.  However,

```<code>$ perl -MPath::Class -MHTML::Tiny -le 'print HTML::Tiny->new(mode=>"html")->form({action=>file("cgi", "script").""})'
<form action="cgi/script"></form>
</code>```

This works because the ."" string concatenation operator causes the Class::Path::File object's automatic stringifier to be called, so an actual string is passed in the {action=>value} hash, not an object.

If you dig into the HTML::Tiny 1.05 code, you'll find sub _tag on line 622, which goes

```<code>if ( ref $val ) {
    return $attr if not $self->_xml_mode;
</code>```

This test allows you to use { attr=>[] } to output an attribute name without a value, but unfortunately the test is also TRUE if $val is an object.  I'll raise a bug report for this against HTML::Tiny.

Body:
Running Perl 5.18 on Ubuntu 14.04 LTS, I wanted to create some pathname constants so I did

use Path::Class;
use constant FILEPATH => file('directory', 'filename');

However, when I came to use the constant in a hash aggregate ...

my $hash = { filepath => FILEPATH };
use Data::Dumper;
print Dumper $href;

... I was surprised to discover that the value of the filepath key was a blessed reference, not the string result from the function call that I was expecting.

I can work around the problem like this ...

use constant FILEPATH => file('directory', 'filename') . "";

... which forces the Perl interpreter to evaluate the blessed reference, but

(a) is there a better way, and
(b) what the heck is going on?!

I know that use constant is evaluated in a list context, but normally use constant MYCONST => mysub(arg1, arg2); does The Right Thing, evaluates the subroutine call and uses the return value. What's the cleverness with Path::Class::file that breaks this expectation?

Body:
You're right about Path::Class::file returning an object.  That's what all the "bless" stuff was in the Dumper output.  Sorry I didn't realise that sooner.

As you'll see from my comments, I ran into the problem using HTML::Tiny, which you can see as follows:-

$ perl -MPath::Class -MHTML::Tiny -le 'print HTML::Tiny->new(mode=>"html")->form({action=>file("cgi-bin", "script")})'
<form action></form>

As you can see, the action attribute is missing the path.  However,

$ perl -MPath::Class -MHTML::Tiny -le 'print HTML::Tiny->new(mode=>"html")->form({action=>file("cgi", "script").""})'
<form action="cgi/script"></form>

This works because the ."" string concatenation operator causes the Class::Path::File object's automatic stringifier to be called, so an actual string is passed in the {action=>value} hash, not an object.

If you dig into the HTML::Tiny 1.05 code, you'll find sub _tag on line 622, which goes

if ( ref $val ) {
    return $attr if not $self->_xml_mode;

This test allows you to use { attr=>[] } to output an attribute name without a value, but unfortunately the test is also TRUE if $val is an object.  I'll raise a bug report for this against HTML::Tiny.


问:
Appending a Matrix in Python within loop
I have a matrix y with size (3,3). Say it is a 3 by 3 matrix with all elements = 1.

I then have a loop to create multiple (3,3) matrices.
So these are the outputs:

First loop I get this matrix:

```<code> [[  88.    42.5    9. ]
 [ 121.5   76.    42.5]
 [ 167.   121.5   88. ]]
</code>```

The second loop I get:

```<code> [[  88.    42.5   13. ]
 [ 117.5   72.    42.5]
 [ 163.   117.5   88. ]]
</code>```

So what I would like to achieve is essentially

```<code> [[1, 1, 1] [88, 42.5, 9] [88, 42.5, 13],
 [1, 1, 1] [121.5, 76, 42.5] [117.5, 72, 42.5],
 [1, 1, 1] [167, 121.5, 88] [163, 117.5, 88]]
</code>```

This is assuming the loop iterates twice, and I am not sure if I have placed the commas or the spacing etc in the right place but ideally I obtain a 3 by 3 matrix with each element having a list with 3 elements.

My code I have so far for the loop is (Up_xyz,Mid_xyz,Down_xyz outputs in [x,x,x] format)  :

```<code>for i in range (1,len(PeopleName)):
  x = np.vstack((Up_xyz(TempName[i]),Mid_xyz(TempName[i]),Down_xyz(TempName[i])))
restA.append(x)
l+=1
</code>```

Which results in:

```<code>   [array([[  88. ,   42.5,   13. ],
   [ 117.5,   72. ,   42.5],
   [ 163. ,  117.5,   88. ]])]
</code>```

Which is simply the value from the last iteration of the loop.

Also, when I append y to restA with

```<code>print(y.append(restA))
</code>```

I get this error:

```<code>'numpy.ndarray' object has no attribute 'append'
</code>```

I assume this is due to the difference in sizing. But I would appreciate any help, and I am fairly new to Python, so would be open to any other ways that would be more efficient as well. Thanks

答:
You should append within the for loop

```<code>for i in range (1,len(PeopleName)):
    x = np.vstack((Up_xyz(TempName[i]),Mid_xyz(TempName[i]),Down_xyz(TempName[i])))
    restA.append(x)
l+=1
</code>```

Numpy array object does not have a method append. You might want:

```<code>y = np.append(y, restA)
</code>```

Body:
I have a matrix y with size (3,3). Say it is a 3 by 3 matrix with all elements = 1.

I then have a loop to create multiple (3,3) matrices.
So these are the outputs:

First loop I get this matrix:

 [[  88.    42.5    9. ]
 [ 121.5   76.    42.5]
 [ 167.   121.5   88. ]]

The second loop I get:

 [[  88.    42.5   13. ]
 [ 117.5   72.    42.5]
 [ 163.   117.5   88. ]]

So what I would like to achieve is essentially

 [[1, 1, 1] [88, 42.5, 9] [88, 42.5, 13],
 [1, 1, 1] [121.5, 76, 42.5] [117.5, 72, 42.5],
 [1, 1, 1] [167, 121.5, 88] [163, 117.5, 88]]

This is assuming the loop iterates twice, and I am not sure if I have placed the commas or the spacing etc in the right place but ideally I obtain a 3 by 3 matrix with each element having a list with 3 elements.

My code I have so far for the loop is (Up_xyz,Mid_xyz,Down_xyz outputs in [x,x,x] format)  :

for i in range (1,len(PeopleName)):
  x = np.vstack((Up_xyz(TempName[i]),Mid_xyz(TempName[i]),Down_xyz(TempName[i])))
restA.append(x)
l+=1

Which results in:

   [array([[  88. ,   42.5,   13. ],
   [ 117.5,   72. ,   42.5],
   [ 163. ,  117.5,   88. ]])]

Which is simply the value from the last iteration of the loop.

Also, when I append y to restA with

print(y.append(restA))

I get this error:

'numpy.ndarray' object has no attribute 'append'

I assume this is due to the difference in sizing. But I would appreciate any help, and I am fairly new to Python, so would be open to any other ways that would be more efficient as well. Thanks

Body:
You should append within the for loop

for i in range (1,len(PeopleName)):
    x = np.vstack((Up_xyz(TempName[i]),Mid_xyz(TempName[i]),Down_xyz(TempName[i])))
    restA.append(x)
l+=1

Numpy array object does not have a method append. You might want:

y = np.append(y, restA)


问:
Planning an exception handling strategy in advance
When I look at a method in the .NET Framework, it can throw several possible exceptions.

From a planning perspective, what do I need to ask to plan and handle these exceptions? I understand that depending on the impact of an exception, that would influence showing it in the UI layer. For example, if a process at the back end which is opaque to the user experience throws an exception, you would not want to show that to the user as s/he would have no idea what that is.

Thanks

答:
You'd normally have a business logic layer in your application, and you'd wrap the methods in that library in safe calls.  Those methods may even say what exceptions they can throw, and you may want to handle those exceptions in a unique way if you so wish.

Here's an example of a couple of classes that can handle both unexpected and custom exceptions:

```<code>class Program
{
    static void Main(string[] args)
    {
        MethodInvokationResult result = SafeActionInvokator.HandleSafely(() =>
        {
            MyFakeBusinessEngine.DivideTwoNumbers(5, 0);
        });
        if (result.Exception is System.DivideByZeroException)
        {
            Debug.WriteLine($"A divide by zerp exception was caught");
        }
        else if (!result.Success)
        {
            Debug.WriteLine($"An unknown error occured.");
        }
    }
}
</code>```

^ You can see that you can wrap the calls and handle them in a sensible way.

```<code>public class MethodInvokationResult
{
    public bool Success { get; set; }
    public Exception Exception { get; set; }
}
</code>```

^ A simple result class

```<code>public static class MyFakeBusinessEngine
{
    /// <summary>
    /// Divides two numbers
    /// </summary>
    /// <param name="a">numerator</param>
    /// <param name="b">denominator</param>
    /// <returns>the result</returns>
    /// <exception cref="System.DivideByZeroException">When b is zero, divide by zero exception is thrown.</exception>
    public static int DivideTwoNumbers(int a, int b)
    {
        return a / b;
    }
}
</code>```

^ A well documented method, that even tells other developers what exceptions it expects to throw

```<code>public static class SafeActionInvokator
{
    /// <summary>
    /// Executes a method, and if any exception is thrown, will log the error and swallow the exception.
    /// </summary>
    /// <param name="methodToExecute"></param>
    public static MethodInvokationResult HandleSafely(Action methodToExecute)
    {
        try
        {
            methodToExecute.Invoke();
            return new MethodInvokationResult()
            {
                Exception = null,
                Success = true
            };
        }
        catch (Exception ex)
        {
            Debug.WriteLine($"{ex}");
            return new MethodInvokationResult()
            {
                Exception = ex,
                Success = false
            };
        }
    }
}
</code>```

^ The wrapper for the method you call, wrapping this in a try catch allows you to handle all exceptions in the same way, or put any custom logic you'd like in there.

This can be expanded to be a call that can return any actual result value too.  You could make a generic result class instead of the simple one I've shown.

FINALLY!  As to your actual question, I'd create some of these layers throughout your application, and re-throw any exceptions with a severity rating included.  These would propagate to your UI layer and you can chose what to do based on Severity.

Maybe even something like this!

```<code>public class MajorException : Exception { }
public class MediumException : Exception { }
public class MinorException : Exception { }
public class UserError : Exception { }
</code>```

Hope this helps!

Body:
You'd normally have a business logic layer in your application, and you'd wrap the methods in that library in safe calls.  Those methods may even say what exceptions they can throw, and you may want to handle those exceptions in a unique way if you so wish.

Here's an example of a couple of classes that can handle both unexpected and custom exceptions:

class Program
{
    static void Main(string[] args)
    {
        MethodInvokationResult result = SafeActionInvokator.HandleSafely(() =>
        {
            MyFakeBusinessEngine.DivideTwoNumbers(5, 0);
        });
        if (result.Exception is System.DivideByZeroException)
        {
            Debug.WriteLine($"A divide by zerp exception was caught");
        }
        else if (!result.Success)
        {
            Debug.WriteLine($"An unknown error occured.");
        }
    }
}

^ You can see that you can wrap the calls and handle them in a sensible way.

public class MethodInvokationResult
{
    public bool Success { get; set; }
    public Exception Exception { get; set; }
}

^ A simple result class

public static class MyFakeBusinessEngine
{
    /// <summary>
    /// Divides two numbers
    /// </summary>
    /// <param name="a">numerator</param>
    /// <param name="b">denominator</param>
    /// <returns>the result</returns>
    /// <exception cref="System.DivideByZeroException">When b is zero, divide by zero exception is thrown.</exception>
    public static int DivideTwoNumbers(int a, int b)
    {
        return a / b;
    }
}

^ A well documented method, that even tells other developers what exceptions it expects to throw

public static class SafeActionInvokator
{
    /// <summary>
    /// Executes a method, and if any exception is thrown, will log the error and swallow the exception.
    /// </summary>
    /// <param name="methodToExecute"></param>
    public static MethodInvokationResult HandleSafely(Action methodToExecute)
    {
        try
        {
            methodToExecute.Invoke();
            return new MethodInvokationResult()
            {
                Exception = null,
                Success = true
            };
        }
        catch (Exception ex)
        {
            Debug.WriteLine($"{ex}");
            return new MethodInvokationResult()
            {
                Exception = ex,
                Success = false
            };
        }
    }
}

^ The wrapper for the method you call, wrapping this in a try catch allows you to handle all exceptions in the same way, or put any custom logic you'd like in there.

This can be expanded to be a call that can return any actual result value too.  You could make a generic result class instead of the simple one I've shown.

FINALLY!  As to your actual question, I'd create some of these layers throughout your application, and re-throw any exceptions with a severity rating included.  These would propagate to your UI layer and you can chose what to do based on Severity.

Maybe even something like this!

public class MajorException : Exception { }
public class MediumException : Exception { }
public class MinorException : Exception { }
public class UserError : Exception { }

Hope this helps!