问:
Formula expression to result
In Java, if I have a string:

```<code>String abc = "(5)*(2+2)/(2)";
</code>```

How could I get the result of abc = 10?

答:
```<code>import javax.script.*;
public class EvalScript {
    public static void main(String[] args) throws Exception {
        // create a script engine manager
        ScriptEngineManager factory = new ScriptEngineManager();
        // create a JavaScript engine
        ScriptEngine engine = factory.getEngineByName("JavaScript");
        // evaluate JavaScript code from String
        Number number = (Number)engine.eval("(5)*(2+2)/(2)");
        System.out.println("abc = " + number);
    }
}
</code>```

Title: Formula expression to result

Body:
In Java, if I have a string:

String abc = "(5)*(2+2)/(2)";

How could I get the result of abc = 10?


来源: stackexchange

问:
Vertical align the child elements with different height
I am trying to achieve a vertically aligned child elements which have different heights.

Following is what I want to implement. Currently I set a different negative top margin on both buttons. I feel this can be done in a more cleaner way with a single generic ruling. Please share your thoughts.

Following is the code to illustrate the problem:

.container {
  padding: 35px 2px;
  border: 1px solid gray;
}

.title {
  font-size: 18px;
}

.action-button {
  float: right;
  height: 50px;
  width: 100px;

}

.small-screen {
  width: 160px;
  display: inline-block;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code>HTML:

<div class="container">

  <span class="title">
    Card header
  </span>

  <button class="action-button">
    Action
  </button>

</div>

<br/>

<div class="container">

  <span class="title small-screen">
    Card header title here is longer
  </span>

  <button class="action-button">
    Action
  </button>

</div></code>```

Link to JSFiddle

答:
Replace your .container style  with.

```<code>height: 120px;
display: flex;
border: 1px solid gray;
align-items: center;
justify-content: space-between;
</code>```

Check the snippet

.container {
  height: 120px;
  display: flex;
  border: 1px solid gray;
  align-items: center;
  justify-content: space-between;
}

.title {
  font-size: 18px;
}

.action-button {
  float: right;
  height: 50px;
  width: 100px;
}

.small-screen {
  width: 160px;
  display: inline-block;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="container">

  <span class="title">
        Card header
      </span>

  <button class="action-button">
        Action
      </button>

</div>

<br />

<div class="container">

  <span class="title small-screen">
        Card header title here is longer
      </span>

  <button class="action-button">
        Action
      </button>

</div></code>```

ContentLicense: CC BY-SA 4.0

Body:
I am trying to achieve a vertically aligned child elements which have different heights.

Following is what I want to implement. Currently I set a different negative top margin on both buttons. I feel this can be done in a more cleaner way with a single generic ruling. Please share your thoughts.

Following is the code to illustrate the problem:

.container {
  padding: 35px 2px;
  border: 1px solid gray;
}

.title {
  font-size: 18px;
}

.action-button {
  float: right;
  height: 50px;
  width: 100px;

}

.small-screen {
  width: 160px;
  display: inline-block;
}

HTML:

    Card header

  <button class="action-button">
    Action
  </button>

    Card header title here is longer

  <button class="action-button">
    Action
  </button>

Link to JSFiddle

Body:
Replace your .container style  with.

height: 120px;
display: flex;
border: 1px solid gray;
align-items: center;
justify-content: space-between;

Check the snippet

.container {
  height: 120px;
  display: flex;
  border: 1px solid gray;
  align-items: center;
  justify-content: space-between;
}

.title {
  font-size: 18px;
}

.action-button {
  float: right;
  height: 50px;
  width: 100px;
}

.small-screen {
  width: 160px;
  display: inline-block;
}

<div class="container">

  <span class="title">
        Card header
      </span>

  <button class="action-button">
        Action
      </button>

</div>

<br />

<div class="container">

  <span class="title small-screen">
        Card header title here is longer
      </span>

  <button class="action-button">
        Action
      </button>

</div>


问:
Manipulating array of objects into new array
I have the following array:

var my_json = [{
  DATE: "2020-02-01",
  PRODUCT_NAME: "PROD1",
  PRODUCT_QUANTITY_MT: "845",
}, {
  DATE: "2020-02-01",
  PRODUCT_NAME: "PROD2",
  PRODUCT_QUANTITY_MT: "1002",
}, {
  DATE: "2020-02-01",
  PRODUCT_NAME: "PROD3",
  PRODUCT_QUANTITY_MT: "45",
}, {
  DATE: "2020-02-02",
  PRODUCT_NAME: "PROD1",
  PRODUCT_QUANTITY_MT: "20",
}, {
  DATE: "2020-02-03",
  PRODUCT_NAME: "PROD1",
  PRODUCT_QUANTITY_MT: "10",
}, {
  DATE: "2020-02-03",
  PRODUCT_NAME: "PROD2",
  PRODUCT_QUANTITY_MT: "230",
}]
```

<p>From the above array I want to create two new arrays, for each day for each product how much was sold. The final array should look like this.</p>

<p>The first value would be a default value call <code>DATE</code> followed by each product name.</p>

```var final = [{
  title: "DATE"
}, {
  title: "PROD1"
}, {
  title: "PROD2"
}, {
  title: "PROD3"
}]
```

<p>I managed to create this by doing the following </p>

```var columns = [{ "title":"DATE" }];

$.each(my_json, function(index, element) {
  columns.push({ "title": element.PRODUCT_NAME })
});
```

<p>The second array should be in this format:</p>

```var data = [
  [ "2020-02-01", 845", "1002" , "45"],
  [ "2020-02-02", "20", "",  "" ],
  [ "2020-02-03", "10", "230",  "" ],
];
```

<p>As you can see, on <code>Feb 1</code> we have a value for all products sold but on <code>Feb 2</code> it's only <code>PROD1</code>. Likewise on <code>Feb 3</code> only <code>PROD2</code> and <code>PROD3</code>. </p>

<p>Each row col should match the first array like bellow</p>

<p><img src="https://i.stack.imgur.com/uegg3.png" alt="enter image description here"></p>

<p>desired output of two arrays as bellow</p>

```         var Array1 = [{title: "DATE"},{title: "PROD1"},{title: "PROD2"},
                      {title: "PROD3"}]

         var Array2 = [
                       [ "2020-02-01", 845", "1002" , "45"],
                       [ "2020-02-02", "20", "",  "" ],
                       [ "2020-02-03", "10", "230",  "" ],
                    ];
```

答:
We can use reduce method:

```<code>let final = my_json.reduce((a, {DATE, PRODUCT_NAME, PRODUCT_QUANTITY_MT}) => {
  a['DATE'] = a['DATE'] || {title: 'DATE'};
  a[PRODUCT_NAME] = a[PRODUCT_NAME] || {title: PRODUCT_NAME};
  return a;
},{})

let prepareData = my_json.reduce((a, c) => {
  a[c.DATE] = a[c.DATE] || {date: c.DATE, values:[]};
  if (c.PRODUCT_QUANTITY_MT) {
    a[c.DATE].values.push(c.PRODUCT_QUANTITY_MT);
  }
  return a;
},{})

let maxArrayLength = 0;
const data = Object.entries(prepareData).reduce((a, [k, v], i)=> {
  if (maxArrayLength < v.values.length) {
      maxArrayLength = v.values.length;
  } else {
    let fillByQuotes = Array.from({ length: maxArrayLength - v.values.length }, (i) => '');
    v.values.push(...fillByQuotes);
  }

  a.push([k, ...v.values]);
  return a;
}, []);
</code>```

An example:

let my_json = [{
  DATE: "2020-02-01",
  PRODUCT_NAME: "PROD1",
  PRODUCT_QUANTITY_MT: "845",
}, {
  DATE: "2020-02-01",
  PRODUCT_NAME: "PROD2",
  PRODUCT_QUANTITY_MT: "1002",
}, {
  DATE: "2020-02-01",
  PRODUCT_NAME: "PROD3",
  PRODUCT_QUANTITY_MT: "45",
}, {
  DATE: "2020-02-02",
  PRODUCT_NAME: "PROD1",
  PRODUCT_QUANTITY_MT: "20",
}, {
  DATE: "2020-02-03",
  PRODUCT_NAME: "PROD1",
  PRODUCT_QUANTITY_MT: "10",
}, {
  DATE: "2020-02-03",
  PRODUCT_NAME: "PROD2",
  PRODUCT_QUANTITY_MT: "230",
}]

let final = my_json.reduce((a, {DATE, PRODUCT_NAME, PRODUCT_QUANTITY_MT}) => {
  a['DATE'] = a['DATE'] || {title: 'DATE'};
  a[PRODUCT_NAME] = a[PRODUCT_NAME] || {title: PRODUCT_NAME};
  return a;
},{})

let prepareData = my_json.reduce((a, c) => {
  a[c.DATE] = a[c.DATE] || {date: c.DATE, values:[]};
  if (c.PRODUCT_QUANTITY_MT) {
    a[c.DATE].values.push(c.PRODUCT_QUANTITY_MT);
  }
  return a;
},{})

let maxArrayLength = 0;
const data = Object.entries(prepareData).reduce((a, [k, v], i)=> {
  if (maxArrayLength < v.values.length) {
      maxArrayLength = v.values.length;
  } else {
    let fillByQuotes = Array.from({ length: maxArrayLength - v.values.length }, (i) => '');
    v.values.push(...fillByQuotes);
  }

  a.push([k, ...v.values]);
  return a;
}, []);

console.log(Object.values(final));
console.log(data);```

Body:
I have the following array:

var my_json = [{
  DATE: "2020-02-01",
  PRODUCT_NAME: "PROD1",
  PRODUCT_QUANTITY_MT: "845",
}, {
  DATE: "2020-02-01",
  PRODUCT_NAME: "PROD2",
  PRODUCT_QUANTITY_MT: "1002",
}, {
  DATE: "2020-02-01",
  PRODUCT_NAME: "PROD3",
  PRODUCT_QUANTITY_MT: "45",
}, {
  DATE: "2020-02-02",
  PRODUCT_NAME: "PROD1",
  PRODUCT_QUANTITY_MT: "20",
}, {
  DATE: "2020-02-03",
  PRODUCT_NAME: "PROD1",
  PRODUCT_QUANTITY_MT: "10",
}, {
  DATE: "2020-02-03",
  PRODUCT_NAME: "PROD2",
  PRODUCT_QUANTITY_MT: "230",
}]

From the above array I want to create two new arrays, for each day for each product how much was sold. The final array should look like this.

The first value would be a default value call DATE followed by each product name.

var final = [{
  title: "DATE"
}, {
  title: "PROD1"
}, {
  title: "PROD2"
}, {
  title: "PROD3"
}]

I managed to create this by doing the following

var columns = [{ "title":"DATE" }];

$.each(my_json, function(index, element) {
  columns.push({ "title": element.PRODUCT_NAME })
});

The second array should be in this format:

var data = [
  [ "2020-02-01", 845", "1002" , "45"],
  [ "2020-02-02", "20", "",  "" ],
  [ "2020-02-03", "10", "230",  "" ],
];

As you can see, on Feb 1 we have a value for all products sold but on Feb 2 it's only PROD1. Likewise on Feb 3 only PROD2 and PROD3.

Each row col should match the first array like bellow

desired output of two arrays as bellow

         var Array1 = [{title: "DATE"},{title: "PROD1"},{title: "PROD2"},
                      {title: "PROD3"}]

         var Array2 = [
                       [ "2020-02-01", 845", "1002" , "45"],
                       [ "2020-02-02", "20", "",  "" ],
                       [ "2020-02-03", "10", "230",  "" ],
                    ];

Body:
We can use reduce method:

let final = my_json.reduce((a, {DATE, PRODUCT_NAME, PRODUCT_QUANTITY_MT}) => {
  a['DATE'] = a['DATE'] || {title: 'DATE'};
  a[PRODUCT_NAME] = a[PRODUCT_NAME] || {title: PRODUCT_NAME};
  return a;
},{})

let prepareData = my_json.reduce((a, c) => {
  a[c.DATE] = a[c.DATE] || {date: c.DATE, values:[]};
  if (c.PRODUCT_QUANTITY_MT) {
    a[c.DATE].values.push(c.PRODUCT_QUANTITY_MT);
  }
  return a;
},{})

let maxArrayLength = 0;
const data = Object.entries(prepareData).reduce((a, [k, v], i)=> {
  if (maxArrayLength < v.values.length) {
      maxArrayLength = v.values.length;
  } else {
    let fillByQuotes = Array.from({ length: maxArrayLength - v.values.length }, (i) => '');
    v.values.push(...fillByQuotes);
  }

  a.push([k, ...v.values]);
  return a;
}, []);

An example:

let my_json = [{
  DATE: "2020-02-01",
  PRODUCT_NAME: "PROD1",
  PRODUCT_QUANTITY_MT: "845",
}, {
  DATE: "2020-02-01",
  PRODUCT_NAME: "PROD2",
  PRODUCT_QUANTITY_MT: "1002",
}, {
  DATE: "2020-02-01",
  PRODUCT_NAME: "PROD3",
  PRODUCT_QUANTITY_MT: "45",
}, {
  DATE: "2020-02-02",
  PRODUCT_NAME: "PROD1",
  PRODUCT_QUANTITY_MT: "20",
}, {
  DATE: "2020-02-03",
  PRODUCT_NAME: "PROD1",
  PRODUCT_QUANTITY_MT: "10",
}, {
  DATE: "2020-02-03",
  PRODUCT_NAME: "PROD2",
  PRODUCT_QUANTITY_MT: "230",
}]

let final = my_json.reduce((a, {DATE, PRODUCT_NAME, PRODUCT_QUANTITY_MT}) => {
  a['DATE'] = a['DATE'] || {title: 'DATE'};
  a[PRODUCT_NAME] = a[PRODUCT_NAME] || {title: PRODUCT_NAME};
  return a;
},{})

let prepareData = my_json.reduce((a, c) => {
  a[c.DATE] = a[c.DATE] || {date: c.DATE, values:[]};
  if (c.PRODUCT_QUANTITY_MT) {
    a[c.DATE].values.push(c.PRODUCT_QUANTITY_MT);
  }
  return a;
},{})

let maxArrayLength = 0;
const data = Object.entries(prepareData).reduce((a, [k, v], i)=> {
  if (maxArrayLength < v.values.length) {
      maxArrayLength = v.values.length;
  } else {
    let fillByQuotes = Array.from({ length: maxArrayLength - v.values.length }, (i) => '');
    v.values.push(...fillByQuotes);
  }

  a.push([k, ...v.values]);
  return a;
}, []);

console.log(Object.values(final));
console.log(data);


问:
Retrieve only date from datetime
I  am using a derived column with ssis with this condition :

```<code>UpdatedDate == (DT_DATE)"9999-12-31" ? (DT_DATE)CreatedDate : (DT_DATE)UpdatedDate
</code>```

This is my actual output, I'm storing the result in BI_StartDate :

```<code>EmployeeId createdDate updatedDate BI_StartDate
54         2013-07-10  9999-12-31  2013-07-10 00:00:00.0000000
245        2016-06-29  2016-07-03  2016-07-03 00:00:00.0000000
</code>```

I want to get only the date:

```<code>EmployeeId createdDate updatedDate BI_StartDate
54         2013-07-10  9999-12-31  2013-07-10
245        2016-06-29  2016-07-03  2016-07-03
</code>```

答:
Alternatively (for Knowledge Sake),

Use DT_DBDATE instrad of DT_DATE

```<code>UpdatedDate == (DT_DBDATE)"9999-12-31" ? (DT_DBDATE)CreatedDate : (DT_DBDATE)UpdatedDate
</code>```

Title: Retrieve only date from datetime

Body:
I  am using a derived column with ssis with this condition :

UpdatedDate == (DT_DATE)"9999-12-31" ? (DT_DATE)CreatedDate : (DT_DATE)UpdatedDate

This is my actual output, I'm storing the result in BI_StartDate :

EmployeeId createdDate updatedDate BI_StartDate
54         2013-07-10  9999-12-31  2013-07-10 00:00:00.0000000
245        2016-06-29  2016-07-03  2016-07-03 00:00:00.0000000

I want to get only the date:

EmployeeId createdDate updatedDate BI_StartDate
54         2013-07-10  9999-12-31  2013-07-10
245        2016-06-29  2016-07-03  2016-07-03

Body:
Alternatively (for Knowledge Sake),

Use DT_DBDATE instrad of DT_DATE

UpdatedDate == (DT_DBDATE)"9999-12-31" ? (DT_DBDATE)CreatedDate : (DT_DBDATE)UpdatedDate


问:
Convert log into json and store it into memory
I have this snippet of code which converts a user-selected log file into json and stores it to a file (using pandas' to_json function).

```<code>import pandas as pd

with open(self.get_logfile_path()) as log_file:
     log_file = log_file.read().splitlines()

df = pd.DataFrame(log_file)

df.to_json(r'C:\Users\xx\Downloads\abc.json')
</code>```

My question is, how do I store the converted json file into memory temporarily (with every key being the start of a newline), instead of outputting it into some directory? I'm using Python 3.8.1.

答:
Try this:</p>

```<code>import pandas as pd
import json

# Convert dataframe "df" to dictionary
df_dict = df.to_dict()

#Store the dictionary into a json string variable in memory
df_json = json.dumps(df_dict)

#Print the json contents
print(df_json)
</code>```

Body:
I have this snippet of code which converts a user-selected log file into json and stores it to a file (using pandas' to_json function).

import pandas as pd

with open(self.get_logfile_path()) as log_file:
     log_file = log_file.read().splitlines()

df = pd.DataFrame(log_file)

df.to_json(r'C:\Users\xx\Downloads\abc.json')

My question is, how do I store the converted json file into memory temporarily (with every key being the start of a newline), instead of outputting it into some directory? I'm using Python 3.8.1.

Body:
Try this:

import pandas as pd
import json

# Convert dataframe "df" to dictionary
df_dict = df.to_dict()

#Store the dictionary into a json string variable in memory
df_json = json.dumps(df_dict)

#Print the json contents
print(df_json)


问:
Encode JSON in bash script
I'm trying to import a Template to my Zabbix server with Zabbix API, i used this:

```<code>fileJSON=\""$(cat template_file)"\"

curl  -s -X POST -H 'Content-Type: application/json-rpc' -d '{
    "jsonrpc": "2.0",
    "method": "configuration.import",
    "params": {
        "format": "json",
        "rules": {
            "templates": {
                "createMissing": true,
                "updateExisting": true
            }
        },
        "source": $fileJSON
    },
    "auth": "6a977cd94b26b6156698459ac4d0f769",
    "id": 1
}' 'http://127.0.0.1/zabbix/api_jsonrpc.php' | jq '.'
</code>```

Here is the output:

```<code>{"jsonrpc":"2.0","error":{"code":-32700,"message":"Parse error","data":"Invalid JSON. An error occurred on the server while parsing the JSON text."},"id":null}
</code>```

I just don't see any error… i tried to use an online parser website but he Don't see any error.
This var is directly filled with the export method of Zabbix (in JSON).
Here is the content of the file:

```<code>{
  "jsonrpc": "2.0",
  "result": "{\"zabbix_export\":{\"version\":\"4.4\",\"date\":\"2020-02-18T08:47:31Z\",\"groups\":[{\"name\":\"System\"}],\"templates\":[{\"template\":\"Template Systeme\",\"name\":\"Template Systeme\",\"groups\":[{\"name\":\"System\"}],\"discovery_rules\":[{\"name\":\"D\\u00e9couverte des services\",\"key\":\"service.discovery\",\"delay\":\"30s\"}]}]}}",
  "id": 1
}
</code>```

I think that the error is the format of the fileJSON, how to encode this variable in JSON format ?

答:
From the API documentation:

source (required) -   string  -  Serialized string containing the
  configuration data.

You can find an XML source example:

```<code>"source": "<?xml version=\"1.0\" encoding=\"UTF-8\"?><zabbix_export><version> [cut]
</code>```

You are sending as source the full output of a configuration.export call:

```<code>{
  "jsonrpc": "2.0",
  "result": "{\"zabbix_export\":{\"version\":\"4.4\",\"date\":\"2020-02-18T08:47:31Z\",\"groups\":[{\"name\":\"System\"}],\"templates\":[{\"template\":\"Template Systeme\",\"name\":\"Template Systeme\",\"groups\":[{\"name\":\"System\"}],\"discovery_rules\":[{\"name\":\"D\\u00e9couverte des services\",\"key\":\"service.discovery\",\"delay\":\"30s\"}]}]}}",
  "id": 1
}
</code>```

while you have to send only the serialized string, which should be the value of the "result" field of your fileJSON:

```<code>"source": "{\"zabbix_export\":{\"  [cut]
</code>```

Title: Encode JSON in bash script

Body:
I'm trying to import a Template to my Zabbix server with Zabbix API, i used this:

fileJSON=\""$(cat template_file)"\"

curl  -s -X POST -H 'Content-Type: application/json-rpc' -d '{
    "jsonrpc": "2.0",
    "method": "configuration.import",
    "params": {
        "format": "json",
        "rules": {
            "templates": {
                "createMissing": true,
                "updateExisting": true
            }
        },
        "source": $fileJSON
    },
    "auth": "6a977cd94b26b6156698459ac4d0f769",
    "id": 1
}' 'http://127.0.0.1/zabbix/api_jsonrpc.php' | jq '.'

Here is the output:

{"jsonrpc":"2.0","error":{"code":-32700,"message":"Parse error","data":"Invalid JSON. An error occurred on the server while parsing the JSON text."},"id":null}

I just don't see any error… i tried to use an online parser website but he Don't see any error.
This var is directly filled with the export method of Zabbix (in JSON).
Here is the content of the file:

{
  "jsonrpc": "2.0",
  "result": "{\"zabbix_export\":{\"version\":\"4.4\",\"date\":\"2020-02-18T08:47:31Z\",\"groups\":[{\"name\":\"System\"}],\"templates\":[{\"template\":\"Template Systeme\",\"name\":\"Template Systeme\",\"groups\":[{\"name\":\"System\"}],\"discovery_rules\":[{\"name\":\"D\\u00e9couverte des services\",\"key\":\"service.discovery\",\"delay\":\"30s\"}]}]}}",
  "id": 1
}

I think that the error is the format of the fileJSON, how to encode this variable in JSON format ?

Body:
From the API documentation:

source (required) -   string  -  Serialized string containing the
  configuration data.

You can find an XML source example:

"source": "<?xml version=\"1.0\" encoding=\"UTF-8\"?><zabbix_export><version> [cut]

You are sending as source the full output of a configuration.export call:

{
  "jsonrpc": "2.0",
  "result": "{\"zabbix_export\":{\"version\":\"4.4\",\"date\":\"2020-02-18T08:47:31Z\",\"groups\":[{\"name\":\"System\"}],\"templates\":[{\"template\":\"Template Systeme\",\"name\":\"Template Systeme\",\"groups\":[{\"name\":\"System\"}],\"discovery_rules\":[{\"name\":\"D\\u00e9couverte des services\",\"key\":\"service.discovery\",\"delay\":\"30s\"}]}]}}",
  "id": 1
}

while you have to send only the serialized string, which should be the value of the "result" field of your fileJSON:

"source": "{\"zabbix_export\":{\"  [cut]


问:
Detect exiting route changes in Vue
I'm working on a component which enables the user to undo the deletion of an item. However, the item should be deleted when the user navigates to another route. To achieve this I'm watching the route like so:

```<code>  `watch: {
    $route(to, from) {
      if (this.showUndo === true) {
        console.log('item will be deleted');
        this.confirmDelete();
      }
    },
  },
</code>```

`

Unfortunately, this gets only triggered when I enter this specific route and not on exiting it. An explanation why that is or an alternative to my     watch: - method would be much appreciated!

Basically I'm looking for an alternative to     beforeRouteLeave since this is a sub-component and therefore I can't use Navigation Guards. Thanks!

答:
Vue lifecycle hook- BeforeDestroy is fired right before teardown. Your component will still be fully present and functional. If you need to cleanup events or reactive subscriptions,
beforeDestroy would probably be the time to do it.

```<code><script>
export default {

  beforeDestroy() {
   //Try like this
    this.confirmDelete();
    console.log('item will be deleted');

  }
}
</script>
</code>```

Ref - https://v2.vuejs.org/v2/api/#beforeDestroy

Title: Detect exiting route changes in Vue

Body:
I'm working on a component which enables the user to undo the deletion of an item. However, the item should be deleted when the user navigates to another route. To achieve this I'm watching the route like so:

  `watch: {
    $route(to, from) {
      if (this.showUndo === true) {
        console.log('item will be deleted');
        this.confirmDelete();
      }
    },
  },

`

Unfortunately, this gets only triggered when I enter this specific route and not on exiting it. An explanation why that is or an alternative to my     watch: - method would be much appreciated!

Basically I'm looking for an alternative to     beforeRouteLeave since this is a sub-component and therefore I can't use Navigation Guards. Thanks!

Body:
Vue lifecycle hook- BeforeDestroy is fired right before teardown. Your component will still be fully present and functional. If you need to cleanup events or reactive subscriptions,
beforeDestroy would probably be the time to do it.

<script>
export default {

  beforeDestroy() {
   //Try like this
    this.confirmDelete();
    console.log('item will be deleted');

  }
}
</script>

Ref - https://v2.vuejs.org/v2/api/#beforeDestroy


问:
How can I convert a Saxon XdmNode to an XmlDocument?
I have a fully populated XdmNode and need to create an XmlDocument from it. How can I do that?</p>

答:
It's possible that the XdmNode is already a wrapper for an XmlDocument, in which case you can dive down through the wrappers to extract the underlying XmlDocument using XdmNode.getUnderlyingXmlNode().

On the other hand, in the general case, you will need to copy the data across. The easiest way to do this is probably to run the XQuery "." using XQueryEvaluator.Run() with a DomDestination as the supplied XmlDestination; on completion, DomDestination.XmlDocument gives you the DOM document node.

If you're constructing the tree using an XSLT transformation or XSD validation, then you can supply a DomDestination as the output for that process, in which case you can avoid the copying process.


问:
How to use JavaScript in google colab?
I have added Javascript kernel to Google Colab using following commands:

```<code>!npm install -g --unsafe-perm ijavascript zeromq
!ijsinstall --install=global
!jupyter-kernelspec list
</code>```

Now I want to code using JavaScript. How can I change the kernel?

答:
I made a simple to bootstrap template that allows you to run TensroflowJS on Google Colab, install modules in notebook, and run long running async code. Just open

tinyurl.com/tf-js-colab

and you ready to go! :)

For detailed walkthrough
https://dev.to/obenjiro/silence-of-the-fans-part-1-javascript-quickstart-5f3m

Title: How to use JavaScript in google colab?

Body:
I have added Javascript kernel to Google Colab using following commands:

!npm install -g --unsafe-perm ijavascript zeromq
!ijsinstall --install=global
!jupyter-kernelspec list

Now I want to code using JavaScript. How can I change the kernel?


问:
How to have a public APIG access a lambda inside a VPC?
I have a small web app deployed as an aws lambda that correctly operates when tested via the lambda management console. However running a test via the apig console yeilds this error:

```<code>Sun Jan 26 21:43:30 UTC 2020 : Execution failed due to configuration error: Invalid permissions on Lambda function
</code>```

However the apig is provisioned with the execute permission:

```<code>  apiGatewayRole:
    DependsOn:
      - squashApp
    Type: "AWS::IAM::Role"
    Properties:
      AssumeRolePolicyDocument:
        Version: "2012-10-17"
        Statement:
          - Effect: Allow
            Principal:
              Service:
                - "apigateway.amazonaws.com"
            Action: "sts:AssumeRole"
      Path: "/"
      ManagedPolicyArns:
        - !Sub "arn:${AWS::Partition}:iam::aws:policy/service-role/AmazonAPIGatewayPushToCloudWatchLogs"
      Policies:
        - PolicyName: "API_Service_Role_Policy"
          PolicyDocument:
            Version: "2012-10-17"
            Statement:
              - Action: "lambda:InvokeFunction"
                Resource: !GetAtt "squashApp.Arn"
                Effect: "Allow"
  lambdaApiGatewayInvoke:
    Type: "AWS::Lambda::Permission"
    Properties:
      Action: "lambda:InvokeFunction"
      FunctionName: !GetAtt "squashApp.Arn"
      Principal: "apigateway.amazonaws.com"
      SourceArn: !Sub "arn:aws:execute-api:${AWS::Region}:${AWS::AccountId}:${apiGateway}/*/*/"
</code>```

Previously the permission was sufficient (The IAM policy is recently added) to permit the lambda invocation. The error started occuring after I moved the lambda inside a VPC.

```<code>squashApp:
    Type: AWS::Lambda::Function
    Properties:
      Environment:
        Variables:
          GO_ENV: production
          DB_HOST: !GetAtt "squashRDS.Endpoint.Address"
          DB_PORT: !GetAtt "squashRDS.Endpoint.Port"
          DB_USER_NAME: !Sub "${rdsUser}"
          DB_USER_PASS: !Sub "${rdsPassword}"
      Code:
        S3Bucket: '${lambdaHandoffBucket}'
        S3Key: !Sub 'functions/${lambdaVersion}/${lambdaHash}' # TODO make parameter
      Handler: 'app'
      Role: !GetAtt "squashLambdaRole.Arn"
      Runtime: 'go1.x'
      Timeout: 2
      FunctionName: !Ref "lambdaFunctionName"
      VpcConfig:
        SecurityGroupIds:
          - !Ref "lambdaSecurtiyGroup"
        SubnetIds:
          - !Ref "privateSubnet1"
          - !Ref "privateSubnet2"
  vpc:
    Type: AWS::EC2::VPC
    Properties:
      CidrBlock: 10.192.0.0/16
      EnableDnsSupport: true
      EnableDnsHostnames: true
  privateSubnet1:
    Type: AWS::EC2::Subnet
    Properties:
      VpcId: !Ref vpc
      CidrBlock: 10.192.21.0/24
      MapPublicIpOnLaunch: false
      AvailabilityZone: !Ref "PrimaryAZ"
      Tags:
        - Key: Name
          Value: !Sub ${apiGatewayStageName} Private Subnet (AZ1)
  privateSubnet2:
    Type: "AWS::EC2::Subnet"
    Properties:
      VpcId: !Ref vpc
      CidrBlock: 10.192.30.0/24
      MapPublicIpOnLaunch: false
      AvailabilityZone: !Ref "SecondaryAZ"

  privateRouteTable1:
    Type: AWS::EC2::RouteTable
    Properties:
      VpcId: !Ref vpc
  privateSubnetRouteTableAssociation1:
    Type: AWS::EC2::SubnetRouteTableAssociation
    Properties:
      RouteTableId: !Ref privateRouteTable1
      SubnetId: !Ref privateSubnet1
  privateRouteTable2:
    Type: AWS::EC2::RouteTable
    Properties:
      VpcId: !Ref vpc
  privateSubnetRouteTableAssociation2:
    Type: AWS::EC2::SubnetRouteTableAssociation
    Properties:
      RouteTableId: !Ref privateRouteTable1
      SubnetId: !Ref privateSubnet1
  noIngressSecurityGroup:
    Type: AWS::EC2::SecurityGroup
    Properties:
      GroupName: "no-ingress-sg"
      GroupDescription: "Security group with no ingress rule"
      VpcId: !Ref vpc
</code>```

The full cloud formation resource section:

```<code>Resources:
  apiGateway:
    Type: "AWS::ApiGateway::RestApi"
    Properties:
      Name: "SquashAPI"
      Description: "Squash Box Ladder"

  apiGatewayRootMethod:
    Type: "AWS::ApiGateway::Method"
    Properties:
      AuthorizationType: "NONE"
      # This can be ANY | GET| POST | etc and references the api http method as seen by a client
      HttpMethod: "ANY"
      Integration:
        # This must be post or the integration between gateway and lambda fails
        IntegrationHttpMethod: "POST"
        Type: "AWS_PROXY"
        Uri: !Sub
          - "arn:aws:apigateway:${AWS::Region}:lambda:path/2015-03-31/functions/${lambdaArn}/invocations"
          - lambdaArn: !GetAtt "squashApp.Arn"
      ResourceId: !GetAtt "apiGateway.RootResourceId"
      RestApiId: !Ref "apiGateway"

  apiGatewayCatchAllProxy:
    Type: AWS::ApiGateway::Resource
    Properties:
      PathPart: "{proxy+}"
      RestApiId: !Ref "apiGateway"
      ParentId: !GetAtt "apiGateway.RootResourceId"

  apiGatewayCatchAllMethod:
    Type: "AWS::ApiGateway::Method"
    Properties:
      AuthorizationType: "NONE"
      HttpMethod: "ANY"
      Integration:
        # This must be post or the integration between gateway and lambda fails
        IntegrationHttpMethod: "POST"
        Type: "AWS_PROXY"
        Uri: !Sub
          - "arn:aws:apigateway:${AWS::Region}:lambda:path/2015-03-31/functions/${lambdaArn}/invocations"
          - lambdaArn: !GetAtt "squashApp.Arn"
      ResourceId: !Ref "apiGatewayCatchAllProxy"
      RestApiId: !Ref "apiGateway"

  apiGatewayDeployment:
    Type: "AWS::ApiGateway::Deployment"
    DependsOn:
      - "apiGatewayRootMethod"
      - "apiGatewayCatchAllMethod"
    Properties:
      RestApiId: !Ref "apiGateway"
      StageName: !Ref "apiGatewayStageName"

  squashApp:
    Type: AWS::Lambda::Function
    Properties:
      Environment:
        Variables:
          GO_ENV: production
          DB_HOST: !GetAtt "squashRDS.Endpoint.Address"
          DB_PORT: !GetAtt "squashRDS.Endpoint.Port"
          DB_USER_NAME: !Sub "${rdsUser}"
          DB_USER_PASS: !Sub "${rdsPassword}"
      Code:
        S3Bucket: '${lambdaHandoffBucket}'
        S3Key: !Sub 'functions/${lambdaVersion}/${lambdaHash}' # TODO make parameter
      Handler: 'app'
      Role: !GetAtt "squashLambdaRole.Arn"
      Runtime: 'go1.x'
      Timeout: 2
      FunctionName: !Ref "lambdaFunctionName"
      VpcConfig:
        SecurityGroupIds:
          - !Ref "lambdaSecurtiyGroup"
        SubnetIds:
          - !Ref "privateSubnet1"
          - !Ref "privateSubnet2"

  lambdaSecurtiyGroup:
    Type: "AWS::EC2::SecurityGroup"
    Properties:
      GroupDescription: For Lambda Application
      VpcId: !Ref vpc

  lambdaEgres:
    Type: AWS::EC2::SecurityGroupEgress
    Properties:
      GroupId: !Ref lambdaSecurtiyGroup
      IpProtocol: tcp
      FromPort: !GetAtt "squashRDS.Endpoint.Port"
      ToPort: !GetAtt "squashRDS.Endpoint.Port"
      CidrIp: !GetAtt 'vpc.CidrBlock'

  lambdaApiGatewayInvoke:
    Type: "AWS::Lambda::Permission"
    Properties:
      Action: "lambda:InvokeFunction"
      FunctionName: !GetAtt "squashApp.Arn"
      Principal: "apigateway.amazonaws.com"
      SourceArn: !Sub "arn:aws:execute-api:${AWS::Region}:${AWS::AccountId}:${apiGateway}/*/*/"

  squashLambdaRole:
    Type: "AWS::IAM::Role"
    Properties:
      AssumeRolePolicyDocument:
        Version: "2012-10-17"
        Statement:
          - Action:
              - "sts:AssumeRole"
            Effect: "Allow"
            Principal:
              Service:
                - "lambda.amazonaws.com"
      ManagedPolicyArns:
        - "arn:aws:iam::aws:policy/service-role/AWSLambdaVPCAccessExecutionRole"
      Policies:
        - PolicyDocument:
            Version: "2012-10-17"
            Statement:
              - Action:
                  - "logs:CreateLogGroup"
                  - "logs:CreateLogStream"
                  - "logs:PutLogEvents"
                Effect: "Allow"
                Resource:
                  - !Sub "arn:aws:logs:${AWS::Region}:${AWS::AccountId}:log-group:/aws/lambda/${lambdaFunctionName}:*"
          PolicyName: "lambda"

  lambdaLogGroup:
    Type: "AWS::Logs::LogGroup"
    Properties:
      LogGroupName: !Sub "/aws/lambda/${lambdaFunctionName}"
      RetentionInDays: 14
  apiGatewayRole:
    DependsOn:
      - squashApp
    Type: "AWS::IAM::Role"
    Properties:
      AssumeRolePolicyDocument:
        Version: "2012-10-17"
        Statement:
          - Effect: Allow
            Principal:
              Service:
                - "apigateway.amazonaws.com"
            Action: "sts:AssumeRole"
      Path: "/"
      ManagedPolicyArns:
        - !Sub "arn:${AWS::Partition}:iam::aws:policy/service-role/AmazonAPIGatewayPushToCloudWatchLogs"
      Policies:
        - PolicyName: "API_Service_Role_Policy"
          PolicyDocument:
            Version: "2012-10-17"
            Statement:
              - Action: "lambda:InvokeFunction"
                Resource: !GetAtt "squashApp.Arn"
                Effect: "Allow"
  apiGwAccountConfig:
    Type: "AWS::ApiGateway::Account"
    Properties:
      CloudWatchRoleArn: !GetAtt "apiGatewayRole.Arn"
  squashRDS:
    Type: AWS::RDS::DBInstance
    Properties:
      DBInstanceClass: db.t2.micro
      AllocatedStorage: 20
      StorageType: "gp2"
      Engine: "postgres"
      MasterUsername: !Sub "${rdsUser}"
      MasterUserPassword: !Sub "${rdsPassword}"
      DBSubnetGroupName: !Ref "rdsSubnetGroup"
      VPCSecurityGroups:
        - !Ref rdsSecurityGroup
    DeletionPolicy: Snapshot

  rdsSecurityGroup:
    Type: AWS::EC2::SecurityGroup
    Properties:
      GroupDescription: For RDS Instance
      VpcId: !Ref vpc
      Tags:
        - Key: Name
          Value: RDS-SecurityGroup

  rdsSubnetGroup:
    Type: "AWS::RDS::DBSubnetGroup"
    Properties:
      DBSubnetGroupName: "RDS Subnet Group"
      DBSubnetGroupDescription: Subnet including the RDS into the VPC
      SubnetIds:
        - !Ref "privateSubnet1"
        - !Ref "privateSubnet2"

  rdsIngres:
    Type: AWS::EC2::SecurityGroupIngress
    Properties:
      GroupId: !Ref rdsSecurityGroup
      IpProtocol: tcp
      FromPort: !GetAtt "squashRDS.Endpoint.Port"
      ToPort: !GetAtt "squashRDS.Endpoint.Port"
      CidrIp: !GetAtt 'vpc.CidrBlock'

  vpc:
    Type: AWS::EC2::VPC
    Properties:
      CidrBlock: 10.192.0.0/16
      EnableDnsSupport: true
      EnableDnsHostnames: true
  privateSubnet1:
    Type: AWS::EC2::Subnet
    Properties:
      VpcId: !Ref vpc
      CidrBlock: 10.192.21.0/24
      MapPublicIpOnLaunch: false
      AvailabilityZone: !Ref "PrimaryAZ"
  privateSubnet2:
    Type: "AWS::EC2::Subnet"
    Properties:
      VpcId: !Ref vpc
      CidrBlock: 10.192.30.0/24
      MapPublicIpOnLaunch: false
      AvailabilityZone: !Ref "SecondaryAZ"

  privateRouteTable1:
    Type: AWS::EC2::RouteTable
    Properties:
      VpcId: !Ref vpc
  privateSubnetRouteTableAssociation1:
    Type: AWS::EC2::SubnetRouteTableAssociation
    Properties:
      RouteTableId: !Ref privateRouteTable1
      SubnetId: !Ref privateSubnet1
  privateRouteTable2:
    Type: AWS::EC2::RouteTable
    Properties:
      VpcId: !Ref vpc
  privateSubnetRouteTableAssociation2:
    Type: AWS::EC2::SubnetRouteTableAssociation
    Properties:
      RouteTableId: !Ref privateRouteTable1
      SubnetId: !Ref privateSubnet1

  noIngressSecurityGroup:
    Type: AWS::EC2::SecurityGroup
    Properties:
      GroupName: "no-ingress-sg"
      GroupDescription: "Security group with no ingress rule"
      VpcId: !Ref vpc

Outputs:
  apiGatewayInvokeURL:
    Value: !Sub "https://${apiGateway}.execute-api.${AWS::Region}.amazonaws.com/${apiGatewayStageName}"

  lambdaArn:
    Value: !GetAtt "squashApp.Arn"
</code>```

答:
In "squashLambdaRole", try adding "apigateway.amazonaws.com" in service principal list +  attach a AWS managed policy named "AWSLambdaRole".
It solved my problem but I did not understand why :/</p>

Body:
I have a small web app deployed as an aws lambda that correctly operates when tested via the lambda management console. However running a test via the apig console yeilds this error:

Sun Jan 26 21:43:30 UTC 2020 : Execution failed due to configuration error: Invalid permissions on Lambda function

However the apig is provisioned with the execute permission:

  apiGatewayRole:
    DependsOn:
      - squashApp
    Type: "AWS::IAM::Role"
    Properties:
      AssumeRolePolicyDocument:
        Version: "2012-10-17"
        Statement:
          - Effect: Allow
            Principal:
              Service:
                - "apigateway.amazonaws.com"
            Action: "sts:AssumeRole"
      Path: "/"
      ManagedPolicyArns:
        - !Sub "arn:${AWS::Partition}:iam::aws:policy/service-role/AmazonAPIGatewayPushToCloudWatchLogs"
      Policies:
        - PolicyName: "API_Service_Role_Policy"
          PolicyDocument:
            Version: "2012-10-17"
            Statement:
              - Action: "lambda:InvokeFunction"
                Resource: !GetAtt "squashApp.Arn"
                Effect: "Allow"
  lambdaApiGatewayInvoke:
    Type: "AWS::Lambda::Permission"
    Properties:
      Action: "lambda:InvokeFunction"
      FunctionName: !GetAtt "squashApp.Arn"
      Principal: "apigateway.amazonaws.com"
      SourceArn: !Sub "arn:aws:execute-api:${AWS::Region}:${AWS::AccountId}:${apiGateway}/*/*/"

Previously the permission was sufficient (The IAM policy is recently added) to permit the lambda invocation. The error started occuring after I moved the lambda inside a VPC.

squashApp:
    Type: AWS::Lambda::Function
    Properties:
      Environment:
        Variables:
          GO_ENV: production
          DB_HOST: !GetAtt "squashRDS.Endpoint.Address"
          DB_PORT: !GetAtt "squashRDS.Endpoint.Port"
          DB_USER_NAME: !Sub "${rdsUser}"
          DB_USER_PASS: !Sub "${rdsPassword}"
      Code:
        S3Bucket: '${lambdaHandoffBucket}'
        S3Key: !Sub 'functions/${lambdaVersion}/${lambdaHash}' # TODO make parameter
      Handler: 'app'
      Role: !GetAtt "squashLambdaRole.Arn"
      Runtime: 'go1.x'
      Timeout: 2
      FunctionName: !Ref "lambdaFunctionName"
      VpcConfig:
        SecurityGroupIds:
          - !Ref "lambdaSecurtiyGroup"
        SubnetIds:
          - !Ref "privateSubnet1"
          - !Ref "privateSubnet2"
  vpc:
    Type: AWS::EC2::VPC
    Properties:
      CidrBlock: 10.192.0.0/16
      EnableDnsSupport: true
      EnableDnsHostnames: true
  privateSubnet1:
    Type: AWS::EC2::Subnet
    Properties:
      VpcId: !Ref vpc
      CidrBlock: 10.192.21.0/24
      MapPublicIpOnLaunch: false
      AvailabilityZone: !Ref "PrimaryAZ"
      Tags:
        - Key: Name
          Value: !Sub ${apiGatewayStageName} Private Subnet (AZ1)
  privateSubnet2:
    Type: "AWS::EC2::Subnet"
    Properties:
      VpcId: !Ref vpc
      CidrBlock: 10.192.30.0/24
      MapPublicIpOnLaunch: false
      AvailabilityZone: !Ref "SecondaryAZ"

  privateRouteTable1:
    Type: AWS::EC2::RouteTable
    Properties:
      VpcId: !Ref vpc
  privateSubnetRouteTableAssociation1:
    Type: AWS::EC2::SubnetRouteTableAssociation
    Properties:
      RouteTableId: !Ref privateRouteTable1
      SubnetId: !Ref privateSubnet1
  privateRouteTable2:
    Type: AWS::EC2::RouteTable
    Properties:
      VpcId: !Ref vpc
  privateSubnetRouteTableAssociation2:
    Type: AWS::EC2::SubnetRouteTableAssociation
    Properties:
      RouteTableId: !Ref privateRouteTable1
      SubnetId: !Ref privateSubnet1
  noIngressSecurityGroup:
    Type: AWS::EC2::SecurityGroup
    Properties:
      GroupName: "no-ingress-sg"
      GroupDescription: "Security group with no ingress rule"
      VpcId: !Ref vpc

The full cloud formation resource section:

Resources:
  apiGateway:
    Type: "AWS::ApiGateway::RestApi"
    Properties:
      Name: "SquashAPI"
      Description: "Squash Box Ladder"

  apiGatewayRootMethod:
    Type: "AWS::ApiGateway::Method"
    Properties:
      AuthorizationType: "NONE"
      # This can be ANY | GET| POST | etc and references the api http method as seen by a client
      HttpMethod: "ANY"
      Integration:
        # This must be post or the integration between gateway and lambda fails
        IntegrationHttpMethod: "POST"
        Type: "AWS_PROXY"
        Uri: !Sub
          - "arn:aws:apigateway:${AWS::Region}:lambda:path/2015-03-31/functions/${lambdaArn}/invocations"
          - lambdaArn: !GetAtt "squashApp.Arn"
      ResourceId: !GetAtt "apiGateway.RootResourceId"
      RestApiId: !Ref "apiGateway"

  apiGatewayCatchAllProxy:
    Type: AWS::ApiGateway::Resource
    Properties:
      PathPart: "{proxy+}"
      RestApiId: !Ref "apiGateway"
      ParentId: !GetAtt "apiGateway.RootResourceId"

  apiGatewayCatchAllMethod:
    Type: "AWS::ApiGateway::Method"
    Properties:
      AuthorizationType: "NONE"
      HttpMethod: "ANY"
      Integration:
        # This must be post or the integration between gateway and lambda fails
        IntegrationHttpMethod: "POST"
        Type: "AWS_PROXY"
        Uri: !Sub
          - "arn:aws:apigateway:${AWS::Region}:lambda:path/2015-03-31/functions/${lambdaArn}/invocations"
          - lambdaArn: !GetAtt "squashApp.Arn"
      ResourceId: !Ref "apiGatewayCatchAllProxy"
      RestApiId: !Ref "apiGateway"

  apiGatewayDeployment:
    Type: "AWS::ApiGateway::Deployment"
    DependsOn:
      - "apiGatewayRootMethod"
      - "apiGatewayCatchAllMethod"
    Properties:
      RestApiId: !Ref "apiGateway"
      StageName: !Ref "apiGatewayStageName"

  squashApp:
    Type: AWS::Lambda::Function
    Properties:
      Environment:
        Variables:
          GO_ENV: production
          DB_HOST: !GetAtt "squashRDS.Endpoint.Address"
          DB_PORT: !GetAtt "squashRDS.Endpoint.Port"
          DB_USER_NAME: !Sub "${rdsUser}"
          DB_USER_PASS: !Sub "${rdsPassword}"
      Code:
        S3Bucket: '${lambdaHandoffBucket}'
        S3Key: !Sub 'functions/${lambdaVersion}/${lambdaHash}' # TODO make parameter
      Handler: 'app'
      Role: !GetAtt "squashLambdaRole.Arn"
      Runtime: 'go1.x'
      Timeout: 2
      FunctionName: !Ref "lambdaFunctionName"
      VpcConfig:
        SecurityGroupIds:
          - !Ref "lambdaSecurtiyGroup"
        SubnetIds:
          - !Ref "privateSubnet1"
          - !Ref "privateSubnet2"

  lambdaSecurtiyGroup:
    Type: "AWS::EC2::SecurityGroup"
    Properties:
      GroupDescription: For Lambda Application
      VpcId: !Ref vpc

  lambdaEgres:
    Type: AWS::EC2::SecurityGroupEgress
    Properties:
      GroupId: !Ref lambdaSecurtiyGroup
      IpProtocol: tcp
      FromPort: !GetAtt "squashRDS.Endpoint.Port"
      ToPort: !GetAtt "squashRDS.Endpoint.Port"
      CidrIp: !GetAtt 'vpc.CidrBlock'

  lambdaApiGatewayInvoke:
    Type: "AWS::Lambda::Permission"
    Properties:
      Action: "lambda:InvokeFunction"
      FunctionName: !GetAtt "squashApp.Arn"
      Principal: "apigateway.amazonaws.com"
      SourceArn: !Sub "arn:aws:execute-api:${AWS::Region}:${AWS::AccountId}:${apiGateway}/*/*/"

  squashLambdaRole:
    Type: "AWS::IAM::Role"
    Properties:
      AssumeRolePolicyDocument:
        Version: "2012-10-17"
        Statement:
          - Action:
              - "sts:AssumeRole"
            Effect: "Allow"
            Principal:
              Service:
                - "lambda.amazonaws.com"
      ManagedPolicyArns:
        - "arn:aws:iam::aws:policy/service-role/AWSLambdaVPCAccessExecutionRole"
      Policies:
        - PolicyDocument:
            Version: "2012-10-17"
            Statement:
              - Action:
                  - "logs:CreateLogGroup"
                  - "logs:CreateLogStream"
                  - "logs:PutLogEvents"
                Effect: "Allow"
                Resource:
                  - !Sub "arn:aws:logs:${AWS::Region}:${AWS::AccountId}:log-group:/aws/lambda/${lambdaFunctionName}:*"
          PolicyName: "lambda"

  lambdaLogGroup:
    Type: "AWS::Logs::LogGroup"
    Properties:
      LogGroupName: !Sub "/aws/lambda/${lambdaFunctionName}"
      RetentionInDays: 14
  apiGatewayRole:
    DependsOn:
      - squashApp
    Type: "AWS::IAM::Role"
    Properties:
      AssumeRolePolicyDocument:
        Version: "2012-10-17"
        Statement:
          - Effect: Allow
            Principal:
              Service:
                - "apigateway.amazonaws.com"
            Action: "sts:AssumeRole"
      Path: "/"
      ManagedPolicyArns:
        - !Sub "arn:${AWS::Partition}:iam::aws:policy/service-role/AmazonAPIGatewayPushToCloudWatchLogs"
      Policies:
        - PolicyName: "API_Service_Role_Policy"
          PolicyDocument:
            Version: "2012-10-17"
            Statement:
              - Action: "lambda:InvokeFunction"
                Resource: !GetAtt "squashApp.Arn"
                Effect: "Allow"
  apiGwAccountConfig:
    Type: "AWS::ApiGateway::Account"
    Properties:
      CloudWatchRoleArn: !GetAtt "apiGatewayRole.Arn"
  squashRDS:
    Type: AWS::RDS::DBInstance
    Properties:
      DBInstanceClass: db.t2.micro
      AllocatedStorage: 20
      StorageType: "gp2"
      Engine: "postgres"
      MasterUsername: !Sub "${rdsUser}"
      MasterUserPassword: !Sub "${rdsPassword}"
      DBSubnetGroupName: !Ref "rdsSubnetGroup"
      VPCSecurityGroups:
        - !Ref rdsSecurityGroup
    DeletionPolicy: Snapshot

  rdsSecurityGroup:
    Type: AWS::EC2::SecurityGroup
    Properties:
      GroupDescription: For RDS Instance
      VpcId: !Ref vpc
      Tags:
        - Key: Name
          Value: RDS-SecurityGroup

  rdsSubnetGroup:
    Type: "AWS::RDS::DBSubnetGroup"
    Properties:
      DBSubnetGroupName: "RDS Subnet Group"
      DBSubnetGroupDescription: Subnet including the RDS into the VPC
      SubnetIds:
        - !Ref "privateSubnet1"
        - !Ref "privateSubnet2"

  rdsIngres:
    Type: AWS::EC2::SecurityGroupIngress
    Properties:
      GroupId: !Ref rdsSecurityGroup
      IpProtocol: tcp
      FromPort: !GetAtt "squashRDS.Endpoint.Port"
      ToPort: !GetAtt "squashRDS.Endpoint.Port"
      CidrIp: !GetAtt 'vpc.CidrBlock'

  vpc:
    Type: AWS::EC2::VPC
    Properties:
      CidrBlock: 10.192.0.0/16
      EnableDnsSupport: true
      EnableDnsHostnames: true
  privateSubnet1:
    Type: AWS::EC2::Subnet
    Properties:
      VpcId: !Ref vpc
      CidrBlock: 10.192.21.0/24
      MapPublicIpOnLaunch: false
      AvailabilityZone: !Ref "PrimaryAZ"
  privateSubnet2:
    Type: "AWS::EC2::Subnet"
    Properties:
      VpcId: !Ref vpc
      CidrBlock: 10.192.30.0/24
      MapPublicIpOnLaunch: false
      AvailabilityZone: !Ref "SecondaryAZ"

  privateRouteTable1:
    Type: AWS::EC2::RouteTable
    Properties:
      VpcId: !Ref vpc
  privateSubnetRouteTableAssociation1:
    Type: AWS::EC2::SubnetRouteTableAssociation
    Properties:
      RouteTableId: !Ref privateRouteTable1
      SubnetId: !Ref privateSubnet1
  privateRouteTable2:
    Type: AWS::EC2::RouteTable
    Properties:
      VpcId: !Ref vpc
  privateSubnetRouteTableAssociation2:
    Type: AWS::EC2::SubnetRouteTableAssociation
    Properties:
      RouteTableId: !Ref privateRouteTable1
      SubnetId: !Ref privateSubnet1

  noIngressSecurityGroup:
    Type: AWS::EC2::SecurityGroup
    Properties:
      GroupName: "no-ingress-sg"
      GroupDescription: "Security group with no ingress rule"
      VpcId: !Ref vpc

Outputs:
  apiGatewayInvokeURL:
    Value: !Sub "https://${apiGateway}.execute-api.${AWS::Region}.amazonaws.com/${apiGatewayStageName}"

  lambdaArn:
    Value: !GetAtt "squashApp.Arn"


问:
Custom Rule class in Laravel - how to get message working?
Working on an existing project, so keeping the code structure the same as other developers is critical.

I've created a new Rule and added my Validator::extend to the boot(). However I can't get the validation error to display my custom message. Instead is just displays a default "validation.ruleName"

I'm writing a Validation rule that uses ImLiam's NHS Number validation package. The validate() and passes() work successfully. But the error message never changes.

How can I get the messages() method to display the custom output of the exception? (Instead of "validation.nhsnumber" in screenshot below?

App\Forms\MyForm: (using Kris Forms)

```<code>public function buildForm()
{
    $this->add('nhs_number', 'number', [
        'label' => 'NHS Number',
        'rules' => 'nullable|nhsnumber',
    ]);
    ...
}
</code>```

App\Providers\AppServiceProvider:

```<code>public function boot()
{

        Validator::extend('nhsnumber', \App\Rules\ValidNhsNumber::class);
}
</code>```

App\Rules\ValidNhsNumber:

```<code>namespace App\Rules;

use Illuminate\Contracts\Validation\Rule;
use ImLiam\NhsNumber\InvalidNhsNumberException;
use ImLiam\NhsNumber\NhsNumber;

class ValidNhsNumber implements Rule
{
    private $message;

    /**
     * Create a new rule instance.
     *
     * @return void
     */
    public function __construct()
    {
        //
    }

    /**
     * Determine if the validation rule passes.
     *
     * @param string $attribute
     * @param mixed $value
     * @return bool
     */
    public function passes($attribute, $value): bool
    {
        try {
            $nhsNumber = new NhsNumber($value);
            $nhsNumber->validate(); // Will throw exception here if false
            return true;
        } catch (InvalidNhsNumberException $e) {
            $this->message = $e->getMessage();
        }
    }

    public function validate($attribute, $value, $params): bool
    {
        return $this->passes($attribute, $value);
    }

    /**
     * Get the validation error message.
     *
     * @return string
     */
    public function message()
    {
        return $this->message;
    }
}
</code>```

答:
Turns out this is a conflict with KrisForms.

But you can get the desired outcome by slightly changing the way you ask it to process rules.

In App\Forms\MyForm:
I changed:

```<code>$this->add('nhs_number', 'number', [
            'label' => 'NHS Number',
            'rules' => 'nullable|nhsnumber',
]);
</code>```

To This:

```<code>$this->add('nhs_number', 'number', [
            'label' => 'NHS Number',
            'rules' => [
                'nullable',
                new ValidNhsNumber()
            ]
]);
</code>```

And then ensured that in the catch block I'm returning false in passes().

Body:
Working on an existing project, so keeping the code structure the same as other developers is critical.

I've created a new Rule and added my Validator::extend to the boot(). However I can't get the validation error to display my custom message. Instead is just displays a default "validation.ruleName"

I'm writing a Validation rule that uses ImLiam's NHS Number validation package. The validate() and passes() work successfully. But the error message never changes.

How can I get the messages() method to display the custom output of the exception? (Instead of "validation.nhsnumber" in screenshot below?

App\Forms\MyForm: (using Kris Forms)

public function buildForm()
{
    $this->add('nhs_number', 'number', [
        'label' => 'NHS Number',
        'rules' => 'nullable|nhsnumber',
    ]);
    ...
}

App\Providers\AppServiceProvider:

public function boot()
{

        Validator::extend('nhsnumber', \App\Rules\ValidNhsNumber::class);
}

App\Rules\ValidNhsNumber:

namespace App\Rules;

use Illuminate\Contracts\Validation\Rule;
use ImLiam\NhsNumber\InvalidNhsNumberException;
use ImLiam\NhsNumber\NhsNumber;

class ValidNhsNumber implements Rule
{
    private $message;

    /**
     * Create a new rule instance.
     *
     * @return void
     */
    public function __construct()
    {
        //
    }

    /**
     * Determine if the validation rule passes.
     *
     * @param string $attribute
     * @param mixed $value
     * @return bool
     */
    public function passes($attribute, $value): bool
    {
        try {
            $nhsNumber = new NhsNumber($value);
            $nhsNumber->validate(); // Will throw exception here if false
            return true;
        } catch (InvalidNhsNumberException $e) {
            $this->message = $e->getMessage();
        }
    }

    public function validate($attribute, $value, $params): bool
    {
        return $this->passes($attribute, $value);
    }

    /**
     * Get the validation error message.
     *
     * @return string
     */
    public function message()
    {
        return $this->message;
    }
}

Body:
Turns out this is a conflict with KrisForms.

But you can get the desired outcome by slightly changing the way you ask it to process rules.

In App\Forms\MyForm:
I changed:

$this->add('nhs_number', 'number', [
            'label' => 'NHS Number',
            'rules' => 'nullable|nhsnumber',
]);

To This:

$this->add('nhs_number', 'number', [
            'label' => 'NHS Number',
            'rules' => [
                'nullable',
                new ValidNhsNumber()
            ]
]);

And then ensured that in the catch block I'm returning false in passes().


问:
How do I capture a CTRL-S without jQuery or any other library?
How do I go about capturing the CTRL + S event in a webpage?

I do not wish to use jQuery or any other special library.

Thanks for your help in advance.

答:
An up to date answer in 2020.

Since the Keyboard event object has been changed lately, and many of its old properties are now deprecated, here's a modernized code:

```<code>document.addEventListener('keydown', e => {
  if (e.ctrlKey && e.key === 's') {
    // Prevent the Save dialog to open
    e.preventDefault();
    // Place your code here
    console.log('CTRL + S');
  }
});
</code>```

Notice the new key property, which contains the information about the stroked key. Additionally, some browsers might not allow code to override the system shortcuts.

ContentLicense: CC BY-SA 3.0

Body:
An up to date answer in 2020.

Since the Keyboard event object has been changed lately, and many of its old properties are now deprecated, here's a modernized code:

document.addEventListener('keydown', e => {
  if (e.ctrlKey && e.key === 's') {
    // Prevent the Save dialog to open
    e.preventDefault();
    // Place your code here
    console.log('CTRL + S');
  }
});

Notice the new key property, which contains the information about the stroked key. Additionally, some browsers might not allow code to override the system shortcuts.


问:
ASP.NET MVC model binding child objects
I'm working on ASP.NET MVC 3 application. I have a Comment class that encapsulates a Post class (each comment is associated with a post in the blog), there is an action method for edit a comment as below,

```<code>    [HttpPost]
    [Authorize(Users = admin)]
    public string EditComment(Comment comment)
    {
        //update the comment by calling NHiberante repository methods
    }
</code>```

From javascript I'm posting only the comment object values like comment id, description to the server, so when binding I see the Post property inside the comment object as null and when I do the ModelState.IsValid i'm getting empty errors. My question is how I can bind the post object to the comment? I can pass the post id to the server along with the other values.

Thanks
Vijaya Anand

答:
I think your looking for the TryUpdateModel or UpdateModel methods on the Controller. You can bind either by passing Comment as an argument (as your doing in your example) or by calling the UpdateModel-methods.

If you're fetching from a db (as you are doing) you should use those methods to update the existing entity instead of creating a new one.

I't might look something like this:

```<code>       [HttpPost]
       [Authorize(Users = admin)]
        public string EditComment(int id, FormCollection form)
        {
               //update the comment by calling NHiberante repository methods

               // Fetch comment from DB
                var comment =  NHibernateHelper.Get<Comment>(id);

                // Update the comment from posted values
                TryUpdateModel(comment);

                // Handle binding errors etc.
                if (!ModelState.IsValid)
                {
                    // On error
                }

            // Commit to DB
            NHibernateHelper.Update<Comment>(comment);

            //Done!

        }
</code>```

I'm also using NHibernate and it works great with this implementation.

Title: ASP.NET MVC model binding child objects

Body:
I'm working on ASP.NET MVC 3 application. I have a Comment class that encapsulates a Post class (each comment is associated with a post in the blog), there is an action method for edit a comment as below,

    [HttpPost]
    [Authorize(Users = admin)]
    public string EditComment(Comment comment)
    {
        //update the comment by calling NHiberante repository methods
    }

From javascript I'm posting only the comment object values like comment id, description to the server, so when binding I see the Post property inside the comment object as null and when I do the ModelState.IsValid i'm getting empty errors. My question is how I can bind the post object to the comment? I can pass the post id to the server along with the other values.

Thanks
Vijaya Anand

Body:
I think your looking for the TryUpdateModel or UpdateModel methods on the Controller. You can bind either by passing Comment as an argument (as your doing in your example) or by calling the UpdateModel-methods.

If you're fetching from a db (as you are doing) you should use those methods to update the existing entity instead of creating a new one.

I't might look something like this:

       [HttpPost]
       [Authorize(Users = admin)]
        public string EditComment(int id, FormCollection form)
        {
               //update the comment by calling NHiberante repository methods

               // Fetch comment from DB
                var comment =  NHibernateHelper.Get<Comment>(id);

                // Update the comment from posted values
                TryUpdateModel(comment);

                // Handle binding errors etc.
                if (!ModelState.IsValid)
                {
                    // On error
                }

            // Commit to DB
            NHibernateHelper.Update<Comment>(comment);

            //Done!

        }

I'm also using NHibernate and it works great with this implementation.


问:
input file Update images inside database
So im trying to change the image thats already inside the database but i cant seem to make it work i kept looking at tutorials and other related questions but couldnt find the exact solution.

this is what i have in php

```<code>// Als de knop van de formulier is ingedrukt update de data dat van de database afkomt

if (isset($_POST['update'])) {

if (isset($_GET['id'])) {
          $chauffeurs_id = $_GET['id'];
        }

if (isset($_POST['Chauffeurs_foto'])) {
            $Chauffeurs_foto = $_POST['Chauffeurs_foto'];
        }

$sql = "SELECT * FROM chauffeurs ORDER BY 'chauffeurs_geboortedatum ASC";
        $sql = "UPDATE `chauffeurs`
        SET `Chauffeurs_foto`=$Chauffeurs_foto
        WHERE `id`='$chauffeurs_id'";

$result = $conn->query($sql);

        if ($result == TRUE){
            echo "Aanpassingen zijn voltooid.";
        }else{
            echo "Error:" . $sql . "<br>" . $conn->error;
        }
    }

if (isset($_GET['id'])) {
      $id = $_GET['id'];

$sql = "SELECT * FROM `chauffeurs` WHERE `id`='$id'";

$result = $conn->query($sql);

if ($result->num_rows > 0) {
        while ($row = $result->fetch_assoc()) {
            $id = $row['id'];
            $chauffeurs_foto = $row['chauffeurs_foto'];
}
$backId = $_SESSION['krijgid'];
</code>```

Here is my html code:

```<code><!-- Formulier waar alles in komt om te veranderen -->
<form action="" method="post" enctype='multipart/form-data' >
          <fieldset>
           <legend>Gegevens chauffeur:</legend>
             <div class="form-group col-md-4">

//I did it like this so i could style the input file

<input type="file" name="file" id="file"  class="inputfile" value="data:image/jpeg;base64, <?php.base64_encode($row['chauffeurs_foto']).?>" />
<label class="btn btn primary"for="file">Choose a file</label>

<input type="submit" value="Chauffeur Aanpassen" name="update">
</fieldset>
</form>
</div>
</code>```

If anyone of you has a solution i would greatly appreciate it cause i need to finish it for my internship if not i'm just going to keep searching.

答:
You have mistakes in your '. Try this code:

```<code>session_start();

include "config.php";

if (isset($_POST['update'])) {

  if (isset($_GET['id'])) {
    $chauffeurs_id = $_GET['id'];
  }

  if (isset($_POST['Chauffeurs_foto'])) {
    $Chauffeurs_foto = $_POST['Chauffeurs_foto'];
  }

  $sql = "UPDATE chauffeurs SET Chauffeurs_foto = '$Chauffeurs_foto' WHERE id = '$chauffeurs_id'";
  $result = $conn->query($sql);

  if ($result == TRUE){
    echo "Aanpassingen zijn voltooid.";
  }else{
    echo "Error:" . $sql . "<br>" . $conn->error;
  }
}

if (isset($_GET['id'])) {

    $id = $_GET['id'];
    $sql = "SELECT * FROM `chauffeurs` WHERE `id`='$id'";
    $result = $conn->query($sql);

    if ($result->num_rows > 0) {
      while ($row = $result->fetch_assoc()) {
        $id = $row['id'];
        $chauffeurs_foto = $row['chauffeurs_foto'];
      }
    $backId = $_SESSION['krijgid'];
    }
}
</code>```

Body:
So im trying to change the image thats already inside the database but i cant seem to make it work i kept looking at tutorials and other related questions but couldnt find the exact solution.

this is what i have in php

// Als de knop van de formulier is ingedrukt update de data dat van de database afkomt

if (isset($_POST['update'])) {

if (isset($_GET['id'])) {
          $chauffeurs_id = $_GET['id'];
        }

if (isset($_POST['Chauffeurs_foto'])) {
            $Chauffeurs_foto = $_POST['Chauffeurs_foto'];
        }

$sql = "SELECT * FROM chauffeurs ORDER BY 'chauffeurs_geboortedatum ASC";
        $sql = "UPDATE `chauffeurs`
        SET `Chauffeurs_foto`=$Chauffeurs_foto
        WHERE `id`='$chauffeurs_id'";

$result = $conn->query($sql);

        if ($result == TRUE){
            echo "Aanpassingen zijn voltooid.";
        }else{
            echo "Error:" . $sql . "
" . $conn->error;
        }
    }

if (isset($_GET['id'])) {
      $id = $_GET['id'];

$sql = "SELECT * FROM `chauffeurs` WHERE `id`='$id'";

$result = $conn->query($sql);

if ($result->num_rows > 0) {
        while ($row = $result->fetch_assoc()) {
            $id = $row['id'];
            $chauffeurs_foto = $row['chauffeurs_foto'];
}
$backId = $_SESSION['krijgid'];

Here is my html code:

<form action="" method="post" enctype='multipart/form-data' >
          <fieldset>
           <legend>Gegevens chauffeur:</legend>

//I did it like this so i could style the input file

<input type="file" name="file" id="file"  class="inputfile" value="data:image/jpeg;base64, <?php.base64_encode($row['chauffeurs_foto']).?>" />
Choose a file

<input type="submit" value="Chauffeur Aanpassen" name="update">
</fieldset>
</form>

If anyone of you has a solution i would greatly appreciate it cause i need to finish it for my internship if not i'm just going to keep searching.

Body:
You have mistakes in your '. Try this code:

session_start();

include "config.php";

if (isset($_POST['update'])) {

  if (isset($_GET['id'])) {
    $chauffeurs_id = $_GET['id'];
  }

  if (isset($_POST['Chauffeurs_foto'])) {
    $Chauffeurs_foto = $_POST['Chauffeurs_foto'];
  }

  $sql = "UPDATE chauffeurs SET Chauffeurs_foto = '$Chauffeurs_foto' WHERE id = '$chauffeurs_id'";
  $result = $conn->query($sql);

  if ($result == TRUE){
    echo "Aanpassingen zijn voltooid.";
  }else{
    echo "Error:" . $sql . "<br>" . $conn->error;
  }
}

if (isset($_GET['id'])) {

    $id = $_GET['id'];
    $sql = "SELECT * FROM `chauffeurs` WHERE `id`='$id'";
    $result = $conn->query($sql);

    if ($result->num_rows > 0) {
      while ($row = $result->fetch_assoc()) {
        $id = $row['id'];
        $chauffeurs_foto = $row['chauffeurs_foto'];
      }
    $backId = $_SESSION['krijgid'];
    }
}


答:
The lazy way?

convert each line to a string. Then check if the int(line[27]) < 5 and line[28] == ".".

Title: Remove data after certain date in python

Body:
I have data with this shape :

date (index)         | x | y
2015-01-01 12:05    | 0 | 10
2015-01-01 12:10    | 0 | 3.6
2015-01-01 12:15    | 1 | 10.2
2015-01-01 12:20    | 0 | 2.8
2015-01-01 12:25    | 1 | 3.6
2015-01-01 12:30    | 5 | 4.8
2015-01-01 12:35    | 2 | 8.9
2015-01-01 12:40    | 7 | 11.9
2015-01-01 12:45    | 1 | 11.8
2015-01-01 12:50    | 0 | 12.0
2015-01-01 12:55    | 2 | 10.9

Goal is to remove all the data when y < 5 (standby) but also remove the data 15mn after standby (range of data when y < 5).
At the end, I will have that :

date (index)        | x | y
2015-01-01 12:05    | 0 | 10
2015-01-01 12:50    | 0 | 12.0
2015-01-01 12:55    | 2 | 10.9

How to do that ?
Thank you.


答:
Please replace your .container class code to below code</p>

```<code>   .container {
    border: 1px solid gray;
    display: flex;
    align-items: center;
    justify-content: space-between;
    padding: 20px;
    border: 1px solid gray;
    }
</code>```

Title: Vertical align the child elements with different height

Body:
I am trying to achieve a vertically aligned child elements which have different heights.

Following is what I want to implement. Currently I set a different negative top margin on both buttons. I feel this can be done in a more cleaner way with a single generic ruling. Please share your thoughts.

Following is the code to illustrate the problem:

.container {
  padding: 35px 2px;
  border: 1px solid gray;
}

.title {
  font-size: 18px;
}

.action-button {
  float: right;
  height: 50px;
  width: 100px;

}

.small-screen {
  width: 160px;
  display: inline-block;
}

HTML:

    Card header

  <button class="action-button">
    Action
  </button>

    Card header title here is longer

  <button class="action-button">
    Action
  </button>

Link to JSFiddle

Body:
Please replace your .container class code to below code

   .container {
    border: 1px solid gray;
    display: flex;
    align-items: center;
    justify-content: space-between;
    padding: 20px;
    border: 1px solid gray;
    }


问:
What's the best way of dealing with AWT Graphics contexts?
Some users of our Swing application have reported weird artefacts appearing on the display. This ranges from components not repainting themselves properly for a second or two, right upto whole portions of the application being repainted like tiled wallpaper over areas of the window.

The app has been worked on by developers of all levels between experienced Java guys to young chaps right out of university over the course of five years or so, and as you'd expect, some of the AWT code is an outright mess. I'm now faced with the task of trying to correct as much of the badness as I can over the next few months or so.

Some of this is easy to deal with. Deal with components only on the event dispatch thread, IO asynchronously, kind of thing, and I'm hopefully getting the message across to the rest of the team.

What I'd like to know is the best way of dealing with Graphics contexts, especially in a paintComponent() context. I see a lot of...

```<code>public void paintComponent( Graphics g ) {
    super.paintComponent( g );
    Graphics2D gfx = (Graphics2D)g;
    // ...Whole lotta drawing code...
}
</code>```

Is it better practice to do this?

```<code>public void paintComponent( Graphics g ) {
    super.paintComponent( g );
    Graphics2D gfx = (Graphics2D)g.create();
    // ...Whole lotta drawing code...
    gfx.dispose();
}
</code>```

If the g parameter is going to be reused in other paints then don't I need to restore it to a good state, undo AffineTransforms, etc.?

答:
According to Filthy Rich Clients, you should not alter the Graphics object passed to you (which sucks as an API, IMO).

The correct way to handle it is slightly more verbose:

```<code>public void paintComponent(Graphics g1) {
    super.paintComponent(g1);
    final Graphics2D g = (Graphics2D)g1.create();
    try {
         // ...Whole lotta drawing code...
    } finally {
         g.dispose();
    }
}
</code>```

IIRC, in the Sun implementation it doesn't matter if you don't dispose of "sub-Graphics" objects. (Don't quote me on that.)

You might want to delegate that comment bit to another object.

OwnerDisplayName: banjollity

ContentLicense: CC BY-SA 2.5

Body:
Some users of our Swing application have reported weird artefacts appearing on the display. This ranges from components not repainting themselves properly for a second or two, right upto whole portions of the application being repainted like tiled wallpaper over areas of the window.

The app has been worked on by developers of all levels between experienced Java guys to young chaps right out of university over the course of five years or so, and as you'd expect, some of the AWT code is an outright mess. I'm now faced with the task of trying to correct as much of the badness as I can over the next few months or so.

Some of this is easy to deal with. Deal with components only on the event dispatch thread, IO asynchronously, kind of thing, and I'm hopefully getting the message across to the rest of the team.

What I'd like to know is the best way of dealing with Graphics contexts, especially in a paintComponent() context. I see a lot of...

public void paintComponent( Graphics g ) {
    super.paintComponent( g );
    Graphics2D gfx = (Graphics2D)g;
    // ...Whole lotta drawing code...
}

Is it better practice to do this?

public void paintComponent( Graphics g ) {
    super.paintComponent( g );
    Graphics2D gfx = (Graphics2D)g.create();
    // ...Whole lotta drawing code...
    gfx.dispose();
}

If the g parameter is going to be reused in other paints then don't I need to restore it to a good state, undo AffineTransforms, etc.?

Body:
According to Filthy Rich Clients, you should not alter the Graphics object passed to you (which sucks as an API, IMO).

The correct way to handle it is slightly more verbose:

public void paintComponent(Graphics g1) {
    super.paintComponent(g1);
    final Graphics2D g = (Graphics2D)g1.create();
    try {
         // ...Whole lotta drawing code...
    } finally {
         g.dispose();
    }
}

IIRC, in the Sun implementation it doesn't matter if you don't dispose of "sub-Graphics" objects. (Don't quote me on that.)

You might want to delegate that comment bit to another object.

OwnerDisplayName: Tom Hawtin - tackline


问:
What is the equivalent code for EndMenu API in c#.net
I need to know the equivalent managed code that does the same as win32api call EndMenu

答:
I assume you want to close a previously shown context menu.

There is no built in way to do this. To close the currently active context menu, you can send the escape key like so:

```<code>SendKeys.Send("{ESC}");
</code>```

UPDATE:

If you want to use EndMenu you need to use P/Invoke. The signature can be found on pinvoke.net:

```<code>[DllImport("user32.dll")]
static extern bool EndMenu();
</code>```

Body:
I assume you want to close a previously shown context menu.

There is no built in way to do this. To close the currently active context menu, you can send the escape key like so:

SendKeys.Send("{ESC}");

UPDATE:

If you want to use EndMenu you need to use P/Invoke. The signature can be found on pinvoke.net:

[DllImport("user32.dll")]
static extern bool EndMenu();


问:
Representing a dictionary<string, string> in .NET Core environment variables
I have a configuration section in my web app for different MIME types represented as a JSON dictionary like so:

```<code>"AllowedMimeTypes": {
    "image/*": "",
    "application/pdf": "pdf",
    "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet": "excel",
    "application/vnd.ms-excel": "excel",
    "application/msword": "word",
    "application/vnd.openxmlformats-officedocument.wordprocessingml.document": "word"
}
</code>```

This is the class it maps to:

```<code>using System.Collections.Generic;

namespace MyApp.Models.Config
{
    public class AllowedMimeTypes : Dictionary<string, string>
    {
    }
}
</code>```

This works perfectly when I run it locally using secrets.json, but when I host it in Azure I have to represent it as environment variables and I cannot seem to find anything that works.

I've tried "AllowedMimeTypes:0:Key" with "AllowedMimeTypes:0:Value" and "AllowedMimeTypes:0:image/*" which both throw an exception and "AllowedMimeTypes:0" which doesn't but doesn't give me the correct configuration values.

Does anyone know how to get this working?

答:
It is not automatically converted to a configuration object but you can store your dictionary as an environment variable in JSON format such as

```<code>AllowedMimeTypes="[{'image/*': '', 'application/pdf': 'pdf', 'application/msword': 'word'}]"
</code>```

and than you can convert it to a dictionary manually

```<code>var values = JsonConvert.DeserializeObject<Dictionary<string, string>>(json);
</code>```

Body:
I have a configuration section in my web app for different MIME types represented as a JSON dictionary like so:

"AllowedMimeTypes": {
    "image/*": "",
    "application/pdf": "pdf",
    "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet": "excel",
    "application/vnd.ms-excel": "excel",
    "application/msword": "word",
    "application/vnd.openxmlformats-officedocument.wordprocessingml.document": "word"
}

This is the class it maps to:

using System.Collections.Generic;

namespace MyApp.Models.Config
{
    public class AllowedMimeTypes : Dictionary<string, string>
    {
    }
}

This works perfectly when I run it locally using secrets.json, but when I host it in Azure I have to represent it as environment variables and I cannot seem to find anything that works.

I've tried "AllowedMimeTypes:0:Key" with "AllowedMimeTypes:0:Value" and "AllowedMimeTypes:0:image/*" which both throw an exception and "AllowedMimeTypes:0" which doesn't but doesn't give me the correct configuration values.

Does anyone know how to get this working?

Body:
It is not automatically converted to a configuration object but you can store your dictionary as an environment variable in JSON format such as

AllowedMimeTypes="[{'image/*': '', 'application/pdf': 'pdf', 'application/msword': 'word'}]"

and than you can convert it to a dictionary manually

var values = JsonConvert.DeserializeObject<Dictionary<string, string>>(json);


问:
How fix the Datetime picker localization problem
I have a problem with the date, for example if I enter the date 18/02/2020, the date is saved in the database is 17/02/2020 22:00:00 !!!
normally is a time zone problem or not? how to correct this problem and thank's.if i want save the date with UTC, how to do that ?

code .html :

<ng-template #datepicker>
  {{cell.label}} *

    <ng-container *ngIf="cell.type === 'date';else select2">
      <mat-form-field class="date-Picker-br-object">
        <input [disabled]="!cell.editable" name="{{cell.id}}" [required]="cell.required" style="width: 100% !important;" matInput [matDatepicker]="i" [(ngModel)]="cell.value" [disabled]="!cell.editable">
        <mat-datepicker-toggle matSuffix [for]="i"></mat-datepicker-toggle>
        <mat-datepicker #i></mat-datepicker>
      </mat-form-field>
    </ng-container>

{{msgRequired(cell.label)}}

{{otherErrorMessages[i]}}

</ng-template>
```

答:
You can use Moment.js with Material Datepicker and set the options accordingly like below

```<code>@NgModule({
imports: [MatDatepickerModule, MatMomentDateModule],
providers: [
  { provide: MAT_MOMENT_DATE_ADAPTER_OPTIONS, useValue: { useUtc: true } }
]
})
</code>```

You can find out more at:
https://material.angular.io/components/datepicker/overview#choosing-a-date-implementation-and-date-format-settings

Body:
You can use Moment.js with Material Datepicker and set the options accordingly like below

@NgModule({
imports: [MatDatepickerModule, MatMomentDateModule],
providers: [
  { provide: MAT_MOMENT_DATE_ADAPTER_OPTIONS, useValue: { useUtc: true } }
]
})

You can find out more at:
https://material.angular.io/components/datepicker/overview#choosing-a-date-implementation-and-date-format-settings


问:
Swift - Objective-C load class method?
In Objective-C, NSObject had a class method called load that gets called when the class is loaded for the first time. What is the equivalent in Swift?

```<code>@implementation MyClass

+ (void)load
{
   [self registerClass];
}

@end
</code>```

答:
What is the equivalent in Swift?

There is none.

Unlike stored instance properties, you must always give stored type properties a default value. This is because the type itself does not have an initializer that can assign a value to a stored type property at initialization time.

Source: "The Swift Programming Language", by Apple

Types simply don't have an initializer in Swift. As several answers here suggest, you may be able to work around that by using the Objective-C bridge and having your Swift class inherit from NSObject or by using a Objective-C loader bootstrap code but if you have a 100% Swift project, you basically only have two options:

Manually initialize your classes somewhere within the code:

```<code>class MyCoolClass {

    static func initClass ( ) {
        // Do your init stuff here...
    }
}

// Somewhere in a method/function that is guaranteed to be called
// on app startup or at some other relevant event:
MyCoolClass.initClass()
</code>```

Use a run once pattern in all methods that require an initialized class:

```<code>class MyCoolClass {

    private static var classInitialized: Bool = {
         // Do your init stuff here...
         // This code will for sure only run once!
         return true
    }()

    private static func ensureClassIsInitialized ( ) {
        _ = self.classInitialized
    }

    func whateverA ( ... ) {
        MyCoolClass.ensureClassIsInitialized()
        // Do something...
    }

    func whateverB ( ... ) {
        MyCoolClass.ensureClassIsInitialized()
        // Do something...
    }

    func whateverC ( ... ) {
        MyCoolClass.ensureClassIsInitialized()
        // Do something...
    }

}
</code>```

This follows a clean pattern that no code in Swift runs "automagically", code only runs if other code instructs it to run, which provides a clear and trackable code flow.

There might be a better solution for special cases yet you have not provided any information as for why you need that feature to begin with.

Title: Swift - Objective-C load class method?

Body:
In Objective-C, NSObject had a class method called load that gets called when the class is loaded for the first time. What is the equivalent in Swift?

@implementation MyClass

+ (void)load
{
   [self registerClass];
}

@end

Body:
What is the equivalent in Swift?

There is none.

Unlike stored instance properties, you must always give stored type properties a default value. This is because the type itself does not have an initializer that can assign a value to a stored type property at initialization time.

Source: "The Swift Programming Language", by Apple

Types simply don't have an initializer in Swift. As several answers here suggest, you may be able to work around that by using the Objective-C bridge and having your Swift class inherit from NSObject or by using a Objective-C loader bootstrap code but if you have a 100% Swift project, you basically only have two options:

Manually initialize your classes somewhere within the code:

class MyCoolClass {

    static func initClass ( ) {
        // Do your init stuff here...
    }
}

// Somewhere in a method/function that is guaranteed to be called
// on app startup or at some other relevant event:
MyCoolClass.initClass()

Use a run once pattern in all methods that require an initialized class:

class MyCoolClass {

    private static var classInitialized: Bool = {
         // Do your init stuff here...
         // This code will for sure only run once!
         return true
    }()

    private static func ensureClassIsInitialized ( ) {
        _ = self.classInitialized
    }

    func whateverA ( ... ) {
        MyCoolClass.ensureClassIsInitialized()
        // Do something...
    }

    func whateverB ( ... ) {
        MyCoolClass.ensureClassIsInitialized()
        // Do something...
    }

    func whateverC ( ... ) {
        MyCoolClass.ensureClassIsInitialized()
        // Do something...
    }

}

This follows a clean pattern that no code in Swift runs "automagically", code only runs if other code instructs it to run, which provides a clear and trackable code flow.

There might be a better solution for special cases yet you have not provided any information as for why you need that feature to begin with.


问:
How set hover for featured image? How change hover?
I would like to set the gif file in the featured image. I would like it to run when I hover over it with the mouse.

I know I should set this in functions.php file

Together with the code:

```<code>add_theme_support ('post-thumbnails');
</code>```

Unfortunately, I have no idea how to do it. I create my blog and I have never done such things. Could someone help me how to do it?
Thank you for your help!

答:
If you’ve ever tried to set an animated gif as a featured image in WordPress, you’ve probably discovered that you can’t.

The reason why is pretty simple. Your theme grabs a resized version of the featured image you upload. And in the case of an animated gif, that means it’s not grabbing the original gif image, and so you end up with a static image.

The way around this is pretty simple, however. You can just install a plugin that automatically sets the featured image from the first image in a post. Of course that means you will need to make the animated image the first image, but at least it’s a workaround.

There are a number of plugins that will let you automatically set your first image as the featured image. I tried two and the both worked: Autoset Featured Image and Automatic Featured Image Posts.

Something else I found was that I didn’t even need to download the gif. I could just insert it with the URL.

Body:
I would like to set the gif file in the featured image. I would like it to run when I hover over it with the mouse.

I know I should set this in functions.php file

Together with the code:

add_theme_support ('post-thumbnails');

Unfortunately, I have no idea how to do it. I create my blog and I have never done such things. Could someone help me how to do it?
Thank you for your help!


问:
Segmentation fault caused by white space not caught in string from cin
I'm working on implementing the Shunting Yard Algorithm to evaluate simple expressions. The code seems to work but crashes if there are spaces. This is surprising because there is a specific check for white space which seems to simply not catch it.

```<code>using namespace std;

mpz_class exprToTokens(string expression);
int precedence(const char op);
mpz_class applyOperation(const mpz_class a, const mpz_class b, const char op);

int main() {

    try {
    while(true)
    {
            cout << "enter an expression: ";
            string expr;
            cin >> expr;
            if( expr == "e")
            {
        break;
            }
            cout << "output: " << exprToTokens(expr) << endl;
    }

    } catch( const std::exception & ex ) {
       cerr << "message: " << ex.what() << endl;
    }

    return 0;
}

mpz_class exprToTokens(string expression)
{

    stack<char> operators;
    stack<mpz_class> output;

    unsigned int i = 0;
    while(i < expression.length())
    {
        if(isspace(static_cast<unsigned char>(expression.at(i))))//skip white space
        {
            cout << "is space" << endl;//never happens
            i++;
            continue;
        }
        else if(isdigit(expression[i]))
        {
            unsigned int j = i;
            while(i < expression.length() && isdigit(expression[j]))
            {
                j++;
            }
            const string number = expression.substr(i, j-i);
            const mpz_class term(number);
            output.push(term);
            i = j;
            continue;
        }
        else//token is an operator
        {
            while(!operators.empty() && precedence(operators.top() >= precedence(expression[i])))
            {
                const mpz_class val1 = output.top();
                output.pop();

                const mpz_class val2 = output.top();
                output.pop();

                const char op = operators.top();
                operators.pop();

                output.push(applyOperation(val1, val2, op));
            }
            operators.push(expression[i]);
        }
        i++;
    }

    /*process remaining operations and values on stacks*/
    while(!operators.empty())
    {
        const mpz_class val2 = output.top();//something bad happens here when spaces are around operator
        output.pop();

        const mpz_class val1 = output.top();
        output.pop();

        const char op = operators.top();
        operators.pop();

        output.push(applyOperation(val1, val2, op));
    }

    return output.top();
}

int precedence(const char op)
{
    if(op == '+' || op == '-')
        return 1;
    if(op == '*' || op == '/')
        return 2;
    return 3;
}

mpz_class applyOperation(const mpz_class a, const mpz_class b, const char op)
{
    switch(op)
    {
        case '+': return a + b;
        case '-': return a - b;
        case '*': return a * b;
        case '/': return a / b;
        default: throw invalid_argument("syntax not recognized");
    }
}
</code>```

For example 3+3 gives 6 result but 3 + 3 causes a segmentation fault. Any ideas?

Aside question: the Shunting Yard Algorithm converts infix to postfix notation. So strictly speaking it's common to modify the algorithm to actually evaluate the expression, but is it still the Shunting Yard Algorithm anymore? For the normal algorithm isn't another algorithm needed to still evaluate the expression in postfix notation?

答:
cin >> expr; splits the input at spaces, so three separate expressions are read: 3, + and 3. To read the entire expression, use std::getline().

Your program probably crashes parsing the first one, because this loop does not check for j:

```<code>while(i < expression.length() && isdigit(expression[j]))
{
    j++;
}
</code>```

Body:
I'm working on implementing the Shunting Yard Algorithm to evaluate simple expressions. The code seems to work but crashes if there are spaces. This is surprising because there is a specific check for white space which seems to simply not catch it.

using namespace std;

mpz_class exprToTokens(string expression);
int precedence(const char op);
mpz_class applyOperation(const mpz_class a, const mpz_class b, const char op);

int main() {

    try {
    while(true)
    {
            cout << "enter an expression: ";
            string expr;
            cin >> expr;
            if( expr == "e")
            {
        break;
            }
            cout << "output: " << exprToTokens(expr) << endl;
    }

    } catch( const std::exception & ex ) {
       cerr << "message: " << ex.what() << endl;
    }

    return 0;
}

mpz_class exprToTokens(string expression)
{

    stack<char> operators;
    stack<mpz_class> output;

    unsigned int i = 0;
    while(i < expression.length())
    {
        if(isspace(static_cast<unsigned char>(expression.at(i))))//skip white space
        {
            cout << "is space" << endl;//never happens
            i++;
            continue;
        }
        else if(isdigit(expression[i]))
        {
            unsigned int j = i;
            while(i < expression.length() && isdigit(expression[j]))
            {
                j++;
            }
            const string number = expression.substr(i, j-i);
            const mpz_class term(number);
            output.push(term);
            i = j;
            continue;
        }
        else//token is an operator
        {
            while(!operators.empty() && precedence(operators.top() >= precedence(expression[i])))
            {
                const mpz_class val1 = output.top();
                output.pop();

                const mpz_class val2 = output.top();
                output.pop();

                const char op = operators.top();
                operators.pop();

                output.push(applyOperation(val1, val2, op));
            }
            operators.push(expression[i]);
        }
        i++;
    }

    /*process remaining operations and values on stacks*/
    while(!operators.empty())
    {
        const mpz_class val2 = output.top();//something bad happens here when spaces are around operator
        output.pop();

        const mpz_class val1 = output.top();
        output.pop();

        const char op = operators.top();
        operators.pop();

        output.push(applyOperation(val1, val2, op));
    }

    return output.top();
}

int precedence(const char op)
{
    if(op == '+' || op == '-')
        return 1;
    if(op == '*' || op == '/')
        return 2;
    return 3;
}

mpz_class applyOperation(const mpz_class a, const mpz_class b, const char op)
{
    switch(op)
    {
        case '+': return a + b;
        case '-': return a - b;
        case '*': return a * b;
        case '/': return a / b;
        default: throw invalid_argument("syntax not recognized");
    }
}

For example 3+3 gives 6 result but 3 + 3 causes a segmentation fault. Any ideas?

Aside question: the Shunting Yard Algorithm converts infix to postfix notation. So strictly speaking it's common to modify the algorithm to actually evaluate the expression, but is it still the Shunting Yard Algorithm anymore? For the normal algorithm isn't another algorithm needed to still evaluate the expression in postfix notation?

Body:
cin >> expr; splits the input at spaces, so three separate expressions are read: 3, + and 3. To read the entire expression, use std::getline().

Your program probably crashes parsing the first one, because this loop does not check for j:

while(i < expression.length() && isdigit(expression[j]))
{
    j++;
}


问:
Error: 419|Page Expired (Laravel 6.0 -Mysql)
I have Added the @csrf token and in form and in the meta tag in header but still getting the same erro. When I register it works and redirects me to the home page. That's fine but it doesn't redirect me to home page when I login although the credentials are okay and fine.

Login.blade.php

```<code>@extends('layouts.app')

@section('content')
<div class="container">
    <div class="row justify-content-center">
        <div class="col-md-8">
            <div class="card">
                <div class="card-header">{{ __('Login') }}</div>

                <div class="card-body">
                    <form method="POST" action="{{ route('login') }}">
                        @csrf

                        <div class="form-group row">
                            <label for="email" class="col-md-4 col-form-label text-md-right">{{ __('E-Mail Address') }}</label>

                            <div class="col-md-6">
                                <input id="email" type="email" class="form-control @error('email') is-invalid @enderror" name="email" value="{{ old('email') }}" required autocomplete="email" autofocus>

                                @error('email')
                                    <span class="invalid-feedback" role="alert">
                                        <strong>{{ $message }}</strong>
                                    </span>
                                @enderror
                            </div>
                        </div>

                        <div class="form-group row">
                            <label for="password" class="col-md-4 col-form-label text-md-right">{{ __('Password') }}</label>

                            <div class="col-md-6">
                                <input id="password" type="password" class="form-control @error('password') is-invalid @enderror" name="password" required autocomplete="current-password">

                                @error('password')
                                    <span class="invalid-feedback" role="alert">
                                        <strong>{{ $message }}</strong>
                                    </span>
                                @enderror
                            </div>
                        </div>

                        <div class="form-group row">
                            <div class="col-md-6 offset-md-4">
                                <div class="form-check">
                                    <input class="form-check-input" type="checkbox" name="remember" id="remember" {{ old('remember') ? 'checked' : '' }}>

                                    <label class="form-check-label" for="remember">
                                        {{ __('Remember Me') }}
                                    </label>
                                </div>
                            </div>
                        </div>

                        <div class="form-group row mb-0">
                            <div class="col-md-8 offset-md-4">
                                <button type="submit" class="btn btn-primary">
                                    {{ __('Login') }}
                                </button>

                                @if (Route::has('password.request'))
                                    <a class="btn btn-link" href="{{ route('password.request') }}">
                                        {{ __('Forgot Your Password?') }}
                                    </a>
                                @endif
                            </div>
                        </div>
                    </form>
                </div>
            </div>
        </div>
    </div>
</div>
@endsection
</code>```

WEB.PHP

```<code>Auth::routes();

Route::get('/home', 'HomeController@index')->name('home');

Route::get('/admin', function(){
    echo "Hello Admin";
})->middleware('auth','admin');

Route::get('/agent', function(){
    echo "Hello Agent";
})->middleware('auth','agent');

Route::get('/customer', function(){
    echo "Hello Customer";
})->middleware('auth','customer');
</code>```

LoginController.php

```<code><?php

namespace App\Http\Controllers\Auth;

use App\Http\Controllers\Controller;
use App\Providers\RouteServiceProvider;
use Illuminate\Foundation\Auth\AuthenticatesUsers;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Redirect;

class LoginController extends Controller
{

    use AuthenticatesUsers;

    protected $redirectTo = RouteServiceProvider::HOME;

    public function __construct()
    {
        $this->middleware('guest')->except('logout');
//        $this->middleware('auth');
//        $this->middleware('admin');
    }

    protected function redirectTo( ) {
        if (Auth::check() && Auth::user()->role == 'customer') {
            return redirect('/customer');
        }
        elseif (Auth::check() && Auth::user()->role == 'agent') {
            return redirect('/agent');
        }
        else {
            return redirect('/admin');
        }
    }
}
</code>```

答: Try clearing your cache with php artisan cache:clear, that normally does the trick for me.

Body:
I have Added the @csrf token and in form and in the meta tag in header but still getting the same erro. When I register it works and redirects me to the home page. That's fine but it doesn't redirect me to home page when I login although the credentials are okay and fine.

Login.blade.php

@extends('layouts.app')

@section('content')

{{ __('Login') }}

                    <form method="POST" action="{{ route('login') }}">
                        @csrf

                            {{ __('E-Mail Address') }}

                                <input id="email" type="email" class="form-control @error('email') is-invalid @enderror" name="email" value="{{ old('email') }}" required autocomplete="email" autofocus>

                                @error('email')

                                        {{ $message }}

                                @enderror

                            {{ __('Password') }}

                                <input id="password" type="password" class="form-control @error('password') is-invalid @enderror" name="password" required autocomplete="current-password">

                                @error('password')

                                        {{ $message }}

                                @enderror

                                    <input class="form-check-input" type="checkbox" name="remember" id="remember" {{ old('remember') ? 'checked' : '' }}>

                                        {{ __('Remember Me') }}

                                <button type="submit" class="btn btn-primary">
                                    {{ __('Login') }}
                                </button>

                                @if (Route::has('password.request'))

                                        {{ __('Forgot Your Password?') }}

                                @endif

                    </form>

@endsection

WEB.PHP

Auth::routes();

Route::get('/home', 'HomeController@index')->name('home');

Route::get('/admin', function(){
    echo "Hello Admin";
})->middleware('auth','admin');

Route::get('/agent', function(){
    echo "Hello Agent";
})->middleware('auth','agent');

Route::get('/customer', function(){
    echo "Hello Customer";
})->middleware('auth','customer');

LoginController.php

<?php

namespace App\Http\Controllers\Auth;

use App\Http\Controllers\Controller;
use App\Providers\RouteServiceProvider;
use Illuminate\Foundation\Auth\AuthenticatesUsers;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Redirect;

class LoginController extends Controller
{

    use AuthenticatesUsers;

    protected $redirectTo = RouteServiceProvider::HOME;

    public function __construct()
    {
        $this->middleware('guest')->except('logout');
//        $this->middleware('auth');
//        $this->middleware('admin');
    }

    protected function redirectTo( ) {
        if (Auth::check() && Auth::user()->role == 'customer') {
            return redirect('/customer');
        }
        elseif (Auth::check() && Auth::user()->role == 'agent') {
            return redirect('/agent');
        }
        else {
            return redirect('/admin');
        }
    }
}