问:
ERR_CONNECTION_REFUSED in POST data to Mysql using NodeJs and ReactJs
I am working on ReactJs and NodeJS in sending data to MySql, in my frontPage.js The problem is I already tested the API to post data using Postman and no error appears. And the problem comes when I tried in ReactJs, I coded this :

```<code>class InputEndUser extends Component {
    constructor(props){
        super(props);

        this.state = {
            project_type: '',
            status : '',
            subject : '',
            enduser_name : '',
            location : '',
            cp_1 : '',
            cp1_hp : '',
            cp1_jpos: '',
            cp_2 : '',
            cp2_hp : '',
            cp2_jpos : '',
            quot_num : '',
            quot_date : '',
            note : ''

        }
        this.handleProject_type = this.handleProject_type.bind(this);
        this.handleStatus = this.handleStatus.bind(this);
        this.handleSubject = this.handleSubject.bind(this);
        this.handleEnduser_name = this.handleEnduser_name.bind(this);
        this.handleLocation = this.handleLocation.bind(this);
        this.handleCP1 = this.handleCP1.bind(this);
        this.handleCP1_hp = this.handleCP1_hp.bind(this);
        this.handleCP1_jpos = this.handleCP1_jpos.bind(this);
        this.handleCP2 = this.handleCP2.bind(this);
        this.handleCP2 = this.handleCP2.bind(this);
        this.handleCP2_hp = this.handleCP2_hp.bind(this);
        this.handleCP2_jpos = this.handleCP2_jpos.bind(this);
        this.handleQuot_num = this.handleQuot_num.bind(this);
        this.handleQuot_date = this.handleQuot_date.bind (this);
        this.handleNotes = this.handleNotes.bind(this);
    }

    handleProject_type(event){
        this.setState ({
            project_type : event.target.value
        })
    }

    handleStatus(event){
        this.setState({
            status: event.target.value
        })
    }

    handleSubject(event){
        this.setState({
            subject: event.target.value
        })
    }

    handleEnduser_name (event) {
        this.setState({
            enduser_name: event.target.value
        })
    }

    handleLocation(event){
        this.setState({
            location: event.target.value
        })
    }

    handleCP1(event){
        this.setState({
            cp_1: event.target.value
        })
    }

    handleCP1_hp(event){
        this.setState ({
            cp1_hp : event.target.value
        })
    }

    handleCP1_jpos(event){
        this.setState ({
            cp1_jpos : event.target.value
        })
    }

    handleCP2(event){
        this.setState({
            cp_2: event.target.value
        })
    }

    handleCP2_hp(event){
        this.setState ({
            cp2_hp : event.target.value
        })
    }

    handleCP2_jpos(event){
        this.setState ({
            cp2_jpos : event.target.value
        })
    }

    handleQuot_num(event) {
        this.setState ({
            quot_num : event.target.value
        })
    }

    handleQuot_date (event) {
        this.setState({
            quot_date : event.target.value
        })
    }

    handleNotes(event) {
        this.setState({
            note : event.target.value
        })
    }

    submitEndUser(event){
        event.preventDefault();
        fetch('http://localhost:4000/enduser', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
                'Accept': 'application/json'
            }
        })
        .then ((response) => {
            return response.json;
        })
        .then ((body) => {
            console.log(body);
        })
        .catch((error) => {
            console.log(error)
        })
    }
</code>```

and My API in server.js :

```<code>app.post('/enduser', (req, res) => {
  let POST_ENDUSER_QUERY =  {
    project_id: req.body.project_id,
    project_type: req.body.project_type,
    status: req.body.status,
    subject: req.body.subject,
    endUser_name: req.body.endUser_name,
    location: req.body.location,
    cp_1: req.body.cp_1,
    cp1_hp: req.body.cp1_hp,
    cp1_jpos: req.body.cp1_jpos,
    cp_2: req.body.cp_1,
    cp2_hp: req.body.cp1_hp,
    cp2_jpos: req.body.cp1_jpos,
    quot_num: req.body.quot_num,
    quot_date: req.body.quot_date,
    note: req.body.note,
    image: req.body.image,
    estimated_value: req.body.estimated_value
  };
  if (!POST_ENDUSER_QUERY) {
    return res.status(400).send({ err: true, message: 'Please project name' });
  }

  let query = `INSERT INTO enduser_tbl (project_id, project_type, status, subject, endUser_name, location, cp_1, cp1_hp, cp1_jpos, cp_2, cp2_hp, cp2_jpos, quot_num,quot_date, note, image, estimated_value) VALUES (
    '${POST_ENDUSER_QUERY.project_id}',
    '${POST_ENDUSER_QUERY.project_type}',
    '${POST_ENDUSER_QUERY.status}',
    '${POST_ENDUSER_QUERY.subject}',
    '${POST_ENDUSER_QUERY.endUser_name}',
    '${POST_ENDUSER_QUERY.location}',
    '${POST_ENDUSER_QUERY.cp_1}',
    '${POST_ENDUSER_QUERY.cp1_hp}',
    '${POST_ENDUSER_QUERY.cp1_jpos}',
    '${POST_ENDUSER_QUERY.cp_2}',
    '${POST_ENDUSER_QUERY.cp2_hp}',
    '${POST_ENDUSER_QUERY.cp2_jpos}',
    '${POST_ENDUSER_QUERY.quot_num}',
    '${POST_ENDUSER_QUERY.quot_date}',
    '${POST_ENDUSER_QUERY.note}',
    '${POST_ENDUSER_QUERY.image}',
    '${POST_ENDUSER_QUERY.estimated_value}'
    )`;
  dbConn.query(query, ( err, results) => {
    if(err) throw err;
    return res.status(200).json({"status": 200, "err" : null, "data": results});
  });
});

</code>```

and the error came :

also in terminal when I test it with some kind of data, appears like this:

答:
Did you set up a bodyparser in your NodeJS API ?  I know that with express and koa you have to install a module to retrieve the contents of the body and store it in req.body or ctx.request.body.

For express

For koa

Body:
I am working on ReactJs and NodeJS in sending data to MySql, in my frontPage.js The problem is I already tested the API to post data using Postman and no error appears. And the problem comes when I tried in ReactJs, I coded this :

class InputEndUser extends Component {
    constructor(props){
        super(props);

        this.state = {
            project_type: '',
            status : '',
            subject : '',
            enduser_name : '',
            location : '',
            cp_1 : '',
            cp1_hp : '',
            cp1_jpos: '',
            cp_2 : '',
            cp2_hp : '',
            cp2_jpos : '',
            quot_num : '',
            quot_date : '',
            note : ''

        }
        this.handleProject_type = this.handleProject_type.bind(this);
        this.handleStatus = this.handleStatus.bind(this);
        this.handleSubject = this.handleSubject.bind(this);
        this.handleEnduser_name = this.handleEnduser_name.bind(this);
        this.handleLocation = this.handleLocation.bind(this);
        this.handleCP1 = this.handleCP1.bind(this);
        this.handleCP1_hp = this.handleCP1_hp.bind(this);
        this.handleCP1_jpos = this.handleCP1_jpos.bind(this);
        this.handleCP2 = this.handleCP2.bind(this);
        this.handleCP2 = this.handleCP2.bind(this);
        this.handleCP2_hp = this.handleCP2_hp.bind(this);
        this.handleCP2_jpos = this.handleCP2_jpos.bind(this);
        this.handleQuot_num = this.handleQuot_num.bind(this);
        this.handleQuot_date = this.handleQuot_date.bind (this);
        this.handleNotes = this.handleNotes.bind(this);
    }

    handleProject_type(event){
        this.setState ({
            project_type : event.target.value
        })
    }

    handleStatus(event){
        this.setState({
            status: event.target.value
        })
    }

    handleSubject(event){
        this.setState({
            subject: event.target.value
        })
    }

    handleEnduser_name (event) {
        this.setState({
            enduser_name: event.target.value
        })
    }

    handleLocation(event){
        this.setState({
            location: event.target.value
        })
    }

    handleCP1(event){
        this.setState({
            cp_1: event.target.value
        })
    }

    handleCP1_hp(event){
        this.setState ({
            cp1_hp : event.target.value
        })
    }

    handleCP1_jpos(event){
        this.setState ({
            cp1_jpos : event.target.value
        })
    }

    handleCP2(event){
        this.setState({
            cp_2: event.target.value
        })
    }

    handleCP2_hp(event){
        this.setState ({
            cp2_hp : event.target.value
        })
    }

    handleCP2_jpos(event){
        this.setState ({
            cp2_jpos : event.target.value
        })
    }

    handleQuot_num(event) {
        this.setState ({
            quot_num : event.target.value
        })
    }

    handleQuot_date (event) {
        this.setState({
            quot_date : event.target.value
        })
    }

    handleNotes(event) {
        this.setState({
            note : event.target.value
        })
    }

    submitEndUser(event){
        event.preventDefault();
        fetch('http://localhost:4000/enduser', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
                'Accept': 'application/json'
            }
        })
        .then ((response) => {
            return response.json;
        })
        .then ((body) => {
            console.log(body);
        })
        .catch((error) => {
            console.log(error)
        })
    }

and My API in server.js :

app.post('/enduser', (req, res) => {
  let POST_ENDUSER_QUERY =  {
    project_id: req.body.project_id,
    project_type: req.body.project_type,
    status: req.body.status,
    subject: req.body.subject,
    endUser_name: req.body.endUser_name,
    location: req.body.location,
    cp_1: req.body.cp_1,
    cp1_hp: req.body.cp1_hp,
    cp1_jpos: req.body.cp1_jpos,
    cp_2: req.body.cp_1,
    cp2_hp: req.body.cp1_hp,
    cp2_jpos: req.body.cp1_jpos,
    quot_num: req.body.quot_num,
    quot_date: req.body.quot_date,
    note: req.body.note,
    image: req.body.image,
    estimated_value: req.body.estimated_value
  };
  if (!POST_ENDUSER_QUERY) {
    return res.status(400).send({ err: true, message: 'Please project name' });
  }

  let query = `INSERT INTO enduser_tbl (project_id, project_type, status, subject, endUser_name, location, cp_1, cp1_hp, cp1_jpos, cp_2, cp2_hp, cp2_jpos, quot_num,quot_date, note, image, estimated_value) VALUES (
    '${POST_ENDUSER_QUERY.project_id}',
    '${POST_ENDUSER_QUERY.project_type}',
    '${POST_ENDUSER_QUERY.status}',
    '${POST_ENDUSER_QUERY.subject}',
    '${POST_ENDUSER_QUERY.endUser_name}',
    '${POST_ENDUSER_QUERY.location}',
    '${POST_ENDUSER_QUERY.cp_1}',
    '${POST_ENDUSER_QUERY.cp1_hp}',
    '${POST_ENDUSER_QUERY.cp1_jpos}',
    '${POST_ENDUSER_QUERY.cp_2}',
    '${POST_ENDUSER_QUERY.cp2_hp}',
    '${POST_ENDUSER_QUERY.cp2_jpos}',
    '${POST_ENDUSER_QUERY.quot_num}',
    '${POST_ENDUSER_QUERY.quot_date}',
    '${POST_ENDUSER_QUERY.note}',
    '${POST_ENDUSER_QUERY.image}',
    '${POST_ENDUSER_QUERY.estimated_value}'
    )`;
  dbConn.query(query, ( err, results) => {
    if(err) throw err;
    return res.status(200).json({"status": 200, "err" : null, "data": results});
  });
});

and the error came :

also in terminal when I test it with some kind of data, appears like this:


来源: stackexchange

问:
Combine multiple array with one array key
I have a situation in PHP where I need to combine multiple array values and bind with the first array key, Let say I have following array,

```<code>[services] => Array
        (
            [0] => 1
            [1] => 2
            [2] => 1
        )

    [package_type] => Array
        (
            [0] => 1
            [1] => 2
            [2] => 1
        )

    [service_desc] => Array
        (
            [0] => Full HD
            [1] => Full HD
            [2] => Full HD
        )

    [service_price] => Array
        (
            [0] => 500
            [1] => 600
            [2] => 500
        )
</code>```

Now , I want to bind all array with service type keys like services[0] will have the value of package_type[0],  service_desc[0] and service_price[0]. The purpose is that I can easily identify all service related values with its Id. Can anyone suggest ?

答:
array_map is key here.  Leave the first argument as null and it will group as you want:

```<code><?php

$data =
[
    'services' =>
    [
        'programming',
        'debugging'
    ],
    'description' =>
    [
        'the process of writing computer programs.',
        'the process of identifying and removing errors from software/hardware'
    ]
];

$result = array_map(null, $data['services'], $data['description']);
var_export($result);
</code>```

Output:

```<code>array (
  0 =>
  array (
    0 => 'programming',
    1 => 'the process of writing computer programs.',
  ),
  1 =>
  array (
    0 => 'debugging',
    1 => 'the process of identifying and removing errors from software/hardware',
  ),
)
</code>```

Instead of writing out all your keys as arguments you could unpack like this:

```<code>array_map(null, ...array_values($data));
</code>```

For something more elaborate, pass array_map a callable:

```<code>$keys   = array_keys($data);
$result = array_map(function(...$args) use ($keys) {
    return array_combine($keys, $args);
}, ...array_values($data));

var_export($result);
</code>```

Output:

```<code>array (
  0 =>
  array (
    'services' => 'programming',
    'description' => 'the process of writing computer programs.',
  ),
  1 =>
  array (
    'services' => 'debugging',
    'description' => 'the process of identifying and removing errors from software/hardware',
  ),
)
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I have a situation in PHP where I need to combine multiple array values and bind with the first array key, Let say I have following array,

[services] => Array
        (
            [0] => 1
            [1] => 2
            [2] => 1
        )

    [package_type] => Array
        (
            [0] => 1
            [1] => 2
            [2] => 1
        )

    [service_desc] => Array
        (
            [0] => Full HD
            [1] => Full HD
            [2] => Full HD
        )

    [service_price] => Array
        (
            [0] => 500
            [1] => 600
            [2] => 500
        )

Now , I want to bind all array with service type keys like services[0] will have the value of package_type[0],  service_desc[0] and service_price[0]. The purpose is that I can easily identify all service related values with its Id. Can anyone suggest ?

Body:
array_map is key here.  Leave the first argument as null and it will group as you want:

<?php

$data =
[
    'services' =>
    [
        'programming',
        'debugging'
    ],
    'description' =>
    [
        'the process of writing computer programs.',
        'the process of identifying and removing errors from software/hardware'
    ]
];

$result = array_map(null, $data['services'], $data['description']);
var_export($result);

Output:

array (
  0 =>
  array (
    0 => 'programming',
    1 => 'the process of writing computer programs.',
  ),
  1 =>
  array (
    0 => 'debugging',
    1 => 'the process of identifying and removing errors from software/hardware',
  ),
)

Instead of writing out all your keys as arguments you could unpack like this:

array_map(null, ...array_values($data));

For something more elaborate, pass array_map a callable:

$keys   = array_keys($data);
$result = array_map(function(...$args) use ($keys) {
    return array_combine($keys, $args);
}, ...array_values($data));

var_export($result);

Output:

array (
  0 =>
  array (
    'services' => 'programming',
    'description' => 'the process of writing computer programs.',
  ),
  1 =>
  array (
    'services' => 'debugging',
    'description' => 'the process of identifying and removing errors from software/hardware',
  ),
)


问:
How to remove default certificate (need to change to different certificate)
I can't remove the current cert because it's the default.
So uh..how do I make the other one the default so I can remove the current default?

Note in the screenshot it says:

Select the certificates to remove from this listener

Note that you
  cannot remove the default certificate

please help

答:
So it might help other people as it was hard for me to find the correct option,

So here is the steps to change SSL for LoadBalancer.

Click on view and edit link and add one more certificate

Add the New SSL you want to use with LB

Then select listener i.e (443) and click on edit

Set the new certificate as default added in step 2

Now you are good to remove the old certificate from the Load balancer under step 2.


问:
WPF form opacity fade animation not finishing if less then 1 second
I have a form that I would like to have fade to 70% opacity unless the mouse if over the form the code I have only works properly if I set the animation time to 1 second. Anything less then that and the animation seems to stop before getting back to 100% opacity.

<Window.Resources>

    </Style>
</Window.Resources>
```

答:
Storyboard.TargetProperty and Duration must be set on the animations, not on the Storyboard.

If you set the Duration on the Storyboard, the animations run for their default Duration of 1 second.

```<code><Trigger Property="IsMouseOver" Value="True">
    <Trigger.EnterActions>
        <BeginStoryboard>
            <Storyboard>
                <DoubleAnimation
                    Storyboard.TargetProperty="Opacity"
                    To="1" Duration="0:0:0.3"/>
            </Storyboard>
        </BeginStoryboard>
    </Trigger.EnterActions>
    <Trigger.ExitActions>
        <BeginStoryboard>
            <Storyboard>
                <DoubleAnimation
                    Storyboard.TargetProperty="Opacity"
                    To=".7" Duration="0:0:0.3" />
            </Storyboard>
        </BeginStoryboard>
    </Trigger.ExitActions>
</Trigger>
</code>```

Body:
Storyboard.TargetProperty and Duration must be set on the animations, not on the Storyboard.

If you set the Duration on the Storyboard, the animations run for their default Duration of 1 second.

<Trigger Property="IsMouseOver" Value="True">
    <Trigger.EnterActions>
        <BeginStoryboard>
            <Storyboard>
                <DoubleAnimation
                    Storyboard.TargetProperty="Opacity"
                    To="1" Duration="0:0:0.3"/>
            </Storyboard>
        </BeginStoryboard>
    </Trigger.EnterActions>
    <Trigger.ExitActions>
        <BeginStoryboard>
            <Storyboard>
                <DoubleAnimation
                    Storyboard.TargetProperty="Opacity"
                    To=".7" Duration="0:0:0.3" />
            </Storyboard>
        </BeginStoryboard>
    </Trigger.ExitActions>
</Trigger>


问:
Calculating tardies using google script
I am trying to create an attendance system that calculates tardies based on certain criteria. First off, each student member has a row dedicated to them in the spreadsheet. (Ie, student1's attendance is found on row 3, student2's attendance is found on row 4, etc.). Each student has personal information in the first few columns. Then each student has an attendance record for the meeting. All attendance information comes in pairs with a sign in time and a sign out time.

A student receives a tardy if they show up after 6:30 PM. They also receive a tardy if they are present for less than 2 hours. So I wrote a code to calculate the number of tardies.

```<code>/**
each student has one row dedicated to their attendance. Sign in and sign out are always in pairs. I will ensure that the range
begins with range[0][0] being the first sign in time.
@param range the row for the student's attendance
@return the total tardies for each student
**/
function calculateTardies(range){
  var search = range[0].length;
  var tardies = 0;//initially set to 0
  for(k = 0; k<search; k+2){ //go through the entire row of the student's sign in and sign out times (k+2 because they always come in pairs)
      var timeIn = new Date(range[0][k]); //sign in time will always be at a K value
      var date = Utilities.formatDate(timeIn, "EST", "EEE"); //get the day of week that time stamp is
      var timeOut = new Date(range[0][k+1]); //sign out time is to the right of the sign in time
          if(date == "Tue" || date == "Wed"  || date == "Thu"){ //they only need to be there for 2 hours Tues-Thurs
            var checkHour = Number(Utilities.formatDate(timeIn, "EST", "HH")); //The hour student arrived
            var checkMin = Number(Utilities.formatDate(timeIn, "EST", "mm")); //The minute student arrived
            var outHour = Number(Utilities.formatDate(timeOut, "EST", "HH")); //hour student left
            var outHour = Number(Utilities.formatDate(timeOut, "EST", "HH")); // min student left
            //If the student wasn't present for at least 2 hours, add a tardy
            if((checkHour+2)*60+checkMin < (outHour*60)+outMin){
                 tardies = tardies+1;
                 }
            //if the student left before 6:30 PM, add a tardy
            if((checkHour*60)+checkMin > 1830){ //11100 is 6:30 PM in minutes 6PM=> 18 hours * 60 min = 1080 minutes + 30 additional minutes
              tardies = tardies+1;
            }
       }
    }
  return tardies;
}
</code>```

To check if they are there for two hours I had to change the time stamps to minutes. I found that I couldn't simply compare the times as is. The same applies for why I changed the arrival time to minutes before comparing it to 6:30 PM.

I am running into an error that states exceeded maximum execution time (line 0). Any advice on how I can change the code or fix this error would be greatly appreciated.

答:
I am running into an error that states exceeded maximum execution time

You have an endless loop that makes your code run until it exceeds maximum execution time

This endless loop is created by the definition

for(k = 0; k<search; k+2)

depending on what you want to do, the correct syntax is either

for(k = 0; k<search; k=k+2)

(if you want to increase k by 2 after each iteration) or

for(k = 0; k<search; k=k++)

if you want to increase k by 1 after each iteration.

I found that I couldn't simply compare the times as is.

Dates are proceeded in Apps Script the same way like in Javascript.

The documentation provides many useful methods and examples of how to wokr with dates.

In a nutshell:

If you want to calculate the difference between two timestamps - the easiest way might be to convert both dates to ms with getTime(), substract them and convert the difference back to hours (1 h = 1000*60*60 ms)

If you want to know the weekday of a date, you need to use getDay()

For working with dates it is recommendable that they are formatted as such in your spreadsheet, rather than manually converting them from numbers inside your script.

Title: Calculating tardies using google script

Body:
I am trying to create an attendance system that calculates tardies based on certain criteria. First off, each student member has a row dedicated to them in the spreadsheet. (Ie, student1's attendance is found on row 3, student2's attendance is found on row 4, etc.). Each student has personal information in the first few columns. Then each student has an attendance record for the meeting. All attendance information comes in pairs with a sign in time and a sign out time.

A student receives a tardy if they show up after 6:30 PM. They also receive a tardy if they are present for less than 2 hours. So I wrote a code to calculate the number of tardies.

/**
each student has one row dedicated to their attendance. Sign in and sign out are always in pairs. I will ensure that the range
begins with range[0][0] being the first sign in time.
@param range the row for the student's attendance
@return the total tardies for each student
**/
function calculateTardies(range){
  var search = range[0].length;
  var tardies = 0;//initially set to 0
  for(k = 0; k<search; k+2){ //go through the entire row of the student's sign in and sign out times (k+2 because they always come in pairs)
      var timeIn = new Date(range[0][k]); //sign in time will always be at a K value
      var date = Utilities.formatDate(timeIn, "EST", "EEE"); //get the day of week that time stamp is
      var timeOut = new Date(range[0][k+1]); //sign out time is to the right of the sign in time
          if(date == "Tue" || date == "Wed"  || date == "Thu"){ //they only need to be there for 2 hours Tues-Thurs
            var checkHour = Number(Utilities.formatDate(timeIn, "EST", "HH")); //The hour student arrived
            var checkMin = Number(Utilities.formatDate(timeIn, "EST", "mm")); //The minute student arrived
            var outHour = Number(Utilities.formatDate(timeOut, "EST", "HH")); //hour student left
            var outHour = Number(Utilities.formatDate(timeOut, "EST", "HH")); // min student left
            //If the student wasn't present for at least 2 hours, add a tardy
            if((checkHour+2)*60+checkMin < (outHour*60)+outMin){
                 tardies = tardies+1;
                 }
            //if the student left before 6:30 PM, add a tardy
            if((checkHour*60)+checkMin > 1830){ //11100 is 6:30 PM in minutes 6PM=> 18 hours * 60 min = 1080 minutes + 30 additional minutes
              tardies = tardies+1;
            }
       }
    }
  return tardies;
}

To check if they are there for two hours I had to change the time stamps to minutes. I found that I couldn't simply compare the times as is. The same applies for why I changed the arrival time to minutes before comparing it to 6:30 PM.

I am running into an error that states exceeded maximum execution time (line 0). Any advice on how I can change the code or fix this error would be greatly appreciated.


问:
Fastest, most efficient way to aggregate a large dataset in python
Let's say I'm measuring the speed over time of a car moving forward on a single axis, with a new measure every 10 minutes.

I have a column in my DataFrame called delta_x, which contains how much the car moved on my axis in the last 10 minutes, values are integers only.

Now let's say that I want to aggregate my data, and have only the amount of movement over each hour, but I want to optimize my code as much as possible because my dataset is extremely large, what's the most efficient way to achieve that ?

```<code>df.head(9)

    date        time    delta_x
0   01/01/2018  00:00   9
1   01/01/2018  00:10   9
2   01/01/2018  00:20   9
3   01/01/2018  00:30   9
4   01/01/2018  00:40   11
5   01/01/2018  00:50   12
6   01/01/2018  01:00   10
7   01/01/2018  01:10   10
8   01/01/2018  01:20   10
</code>```

Currently my solution is to do the following

```<code>for file in os.listdir('temp'):
    if(file.endswith('.txt'):
        df = pd.read_csv(''.join(["./temp/",file]), header=None, delim_whitespace=True)
        df.columns = ['date', 'time', 'delta_x']
        df['hour'] = [(datetime.strptime(x, "%H:%M")).hour for x in df['time'].values]
        df = df.groupby(['date','hour']).agg({'delta_x': 'sum'})
</code>```

Which outputs the correct:

```<code>
date        hour   delta_x
01/01/2018  0      59
</code>```

But I was wondering, is there a better, faster and more efficient way, perhaps using NumPy ?

答:
You can try with following packages which are used for speeding up pandas operation

https://github.com/jmcarpenter2/swifter

https://github.com/modin-project/modin

Body:
Let's say I'm measuring the speed over time of a car moving forward on a single axis, with a new measure every 10 minutes.

I have a column in my DataFrame called delta_x, which contains how much the car moved on my axis in the last 10 minutes, values are integers only.

Now let's say that I want to aggregate my data, and have only the amount of movement over each hour, but I want to optimize my code as much as possible because my dataset is extremely large, what's the most efficient way to achieve that ?

df.head(9)

    date        time    delta_x
0   01/01/2018  00:00   9
1   01/01/2018  00:10   9
2   01/01/2018  00:20   9
3   01/01/2018  00:30   9
4   01/01/2018  00:40   11
5   01/01/2018  00:50   12
6   01/01/2018  01:00   10
7   01/01/2018  01:10   10
8   01/01/2018  01:20   10

Currently my solution is to do the following

for file in os.listdir('temp'):
    if(file.endswith('.txt'):
        df = pd.read_csv(''.join(["./temp/",file]), header=None, delim_whitespace=True)
        df.columns = ['date', 'time', 'delta_x']
        df['hour'] = [(datetime.strptime(x, "%H:%M")).hour for x in df['time'].values]
        df = df.groupby(['date','hour']).agg({'delta_x': 'sum'})

Which outputs the correct:

date        hour   delta_x
01/01/2018  0      59

But I was wondering, is there a better, faster and more efficient way, perhaps using NumPy ?


问:
Spacy - making smaller size of library
Is it possible to make smaller size of this lib?
Currently in python.36/site-packages/spacy lang is 380MiB folder, where I see a lot of unused languages by me. I use only en, and is it possible to install with pip somehow spacy and load to this folder only needed language?</p>

答: This is improved in v2.2+, where the language-specific data has been moved out of the main library into a separate package. The size depends a bit on your OS, but should be closer to ~50 MB.</p>

Title: Spacy - making smaller size of library


问:
liquibase and orai18n.jar
I can't run this

liquibase --driver=oracle.jdbc.OracleDriver --classpath=ojdbc8.jar --url="jdbc:oracle:thin:@host:port:sid" --changeLogFile=db.xml --username=name --password=psw generateChangeLog
```

I get an error

"Unexpected error running Liquibase:
  liquibase.exception.DatabaseException: java.sql.SQLException:
  Unsupported code table (add orai18n.jar to the class route):
  CL8MSWIN1251"

Full stack error

Liquibase Community 3.8.0 by Datical
  Unexpected error running Liquibase: liquibase.exception.DatabaseException: java.sql.SQLException: Неподдерживаемая кодовая таблица (добавьте orai18n.jar в маршрут классов): CL8MSWIN1251
  liquibase.exception.LiquibaseException: liquibase.command.CommandExecutionException: liquibase.exception.DatabaseException: java.sql.SQLException: Неподдерживаемая кодовая таблица (добавьте orai18n.jar в маршрут классов): CL8MSWIN1251
          at liquibase.integration.commandline.CommandLineUtils.doGenerateChangeLog(CommandLineUtils.java:282) ~[liquibase.jar:na]
          at liquibase.integration.commandline.Main.doMigration(Main.java:1060) [liquibase.jar:na]
          at liquibase.integration.commandline.Main.run(Main.java:209) [liquibase.jar:na]
          at liquibase.integration.commandline.Main.main(Main.java:132) [liquibase.jar:na]
  Caused by: liquibase.command.CommandExecutionException: liquibase.exception.DatabaseException: java.sql.SQLException: Неподдерживаемая кодовая таблица (добавьте orai18n.jar в маршрут классов): CL8MSWIN1251
          at liquibase.command.AbstractCommand.execute(AbstractCommand.java:24) ~[liquibase.jar:na]
          at liquibase.integration.commandline.CommandLineUtils.doGenerateChangeLog(CommandLineUtils.java:280) ~[liquibase.jar:na]
          ... 3 common frames omitted
  Caused by: liquibase.exception.DatabaseException: java.sql.SQLException: Неподдерживаемая кодовая таблица (добавьте orai18n.jar в маршрут классов): CL8MSWIN1251
          at liquibase.snapshot.jvm.CatalogSnapshotGenerator.snapshotObject(CatalogSnapshotGenerator.java:47) ~[liquibase.jar:na]
          at liquibase.snapshot.jvm.JdbcSnapshotGenerator.snapshot(JdbcSnapshotGenerator.java:66) ~[liquibase.jar:na]
          at liquibase.snapshot.SnapshotGeneratorChain.snapshot(SnapshotGeneratorChain.java:49) ~[liquibase.jar:na]
          at liquibase.snapshot.jvm.JdbcSnapshotGenerator.snapshot(JdbcSnapshotGenerator.java:69) ~[liquibase.jar:na]
          at liquibase.snapshot.SnapshotGeneratorChain.snapshot(SnapshotGeneratorChain.java:49) ~[liquibase.jar:na]
          at liquibase.snapshot.DatabaseSnapshot.include(DatabaseSnapshot.java:315) ~[liquibase.jar:na]
          at liquibase.snapshot.DatabaseSnapshot.init(DatabaseSnapshot.java:100) ~[liquibase.jar:na]
          at liquibase.snapshot.DatabaseSnapshot.(DatabaseSnapshot.java:59) ~[liquibase.jar:na]
          at liquibase.snapshot.JdbcDatabaseSnapshot.(JdbcDatabaseSnapshot.java:39) ~[liquibase.jar:na]
          at liquibase.snapshot.SnapshotGeneratorFactory.createSnapshot(SnapshotGeneratorFactory.java:217) ~[liquibase.jar:na]
          at liquibase.snapshot.SnapshotGeneratorFactory.createSnapshot(SnapshotGeneratorFactory.java:190) ~[liquibase.jar:na]
          at liquibase.command.core.DiffCommand.createReferenceSnapshot(DiffCommand.java:221) ~[liquibase.jar:na]
          at liquibase.command.core.DiffCommand.createDiffResult(DiffCommand.java:143) ~[liquibase.jar:na]
          at liquibase.command.core.GenerateChangeLogCommand.run(GenerateChangeLogCommand.java:46) ~[liquibase.jar:na]
          at liquibase.command.AbstractCommand.execute(AbstractCommand.java:19) ~[liquibase.jar:na]
          ... 4 common frames omitted
  Caused by: java.sql.SQLException: Неподдерживаемая кодовая таблица (добавьте orai18n.jar в маршрут классов): CL8MSWIN1251
          at oracle.sql.CharacterSetUnknown.failCharsetUnknown(CharacterSetFactoryThin.java:233) ~[ojdbc8.jar:19.3.0.0.0]
          at oracle.sql.CharacterSetUnknown.convert(CharacterSetFactoryThin.java:194) ~[ojdbc8.jar:19.3.0.0.0]
          at oracle.jdbc.driver.PhysicalConnection.throughDbCharset(PhysicalConnection.java:10365) ~[ojdbc8.jar:19.3.0.0.0]
          at oracle.jdbc.driver.PhysicalConnection.enquoteIdentifier(PhysicalConnection.java:10442) ~[ojdbc8.jar:19.3.0.0.0]
          at oracle.jdbc.driver.OracleStatement.enquoteIdentifier(OracleStatement.java:6452) ~[ojdbc8.jar:19.3.0.0.0]
          at oracle.jdbc.driver.OracleStatement.getColumnIndex(OracleStatement.java:3853) ~[ojdbc8.jar:19.3.0.0.0]
          at oracle.jdbc.driver.InsensitiveScrollableResultSet.findColumn(InsensitiveScrollableResultSet.java:270) ~[ojdbc8.jar:19.3.0.0.0]
          at oracle.jdbc.driver.GeneratedResultSet.getString(GeneratedResultSet.java:596) ~[ojdbc8.jar:19.3.0.0.0]
          at liquibase.snapshot.jvm.JdbcSnapshotGenerator.getDatabaseCatalogNames(JdbcSnapshotGenerator.java:149) ~[liquibase.jar:na]
          at liquibase.snapshot.jvm.CatalogSnapshotGenerator.snapshotObject(CatalogSnapshotGenerator.java:35) ~[liquibase.jar:na]
          ... 18 common frames omitte

How to fix this?

答: i fix this problem. I changed NLS LANG in DB server.</p>

Title: liquibase and orai18n.jar

Body:
I can't run this

liquibase --driver=oracle.jdbc.OracleDriver --classpath=ojdbc8.jar --url="jdbc:oracle:thin:@host:port:sid" --changeLogFile=db.xml --username=name --password=psw generateChangeLog

I get an error

"Unexpected error running Liquibase:
  liquibase.exception.DatabaseException: java.sql.SQLException:
  Unsupported code table (add orai18n.jar to the class route):
  CL8MSWIN1251"

Full stack error

Liquibase Community 3.8.0 by Datical
  Unexpected error running Liquibase: liquibase.exception.DatabaseException: java.sql.SQLException: Неподдерживаемая кодовая таблица (добавьте orai18n.jar в маршрут классов): CL8MSWIN1251
  liquibase.exception.LiquibaseException: liquibase.command.CommandExecutionException: liquibase.exception.DatabaseException: java.sql.SQLException: Неподдерживаемая кодовая таблица (добавьте orai18n.jar в маршрут классов): CL8MSWIN1251
          at liquibase.integration.commandline.CommandLineUtils.doGenerateChangeLog(CommandLineUtils.java:282) ~[liquibase.jar:na]
          at liquibase.integration.commandline.Main.doMigration(Main.java:1060) [liquibase.jar:na]
          at liquibase.integration.commandline.Main.run(Main.java:209) [liquibase.jar:na]
          at liquibase.integration.commandline.Main.main(Main.java:132) [liquibase.jar:na]
  Caused by: liquibase.command.CommandExecutionException: liquibase.exception.DatabaseException: java.sql.SQLException: Неподдерживаемая кодовая таблица (добавьте orai18n.jar в маршрут классов): CL8MSWIN1251
          at liquibase.command.AbstractCommand.execute(AbstractCommand.java:24) ~[liquibase.jar:na]
          at liquibase.integration.commandline.CommandLineUtils.doGenerateChangeLog(CommandLineUtils.java:280) ~[liquibase.jar:na]
          ... 3 common frames omitted
  Caused by: liquibase.exception.DatabaseException: java.sql.SQLException: Неподдерживаемая кодовая таблица (добавьте orai18n.jar в маршрут классов): CL8MSWIN1251
          at liquibase.snapshot.jvm.CatalogSnapshotGenerator.snapshotObject(CatalogSnapshotGenerator.java:47) ~[liquibase.jar:na]
          at liquibase.snapshot.jvm.JdbcSnapshotGenerator.snapshot(JdbcSnapshotGenerator.java:66) ~[liquibase.jar:na]
          at liquibase.snapshot.SnapshotGeneratorChain.snapshot(SnapshotGeneratorChain.java:49) ~[liquibase.jar:na]
          at liquibase.snapshot.jvm.JdbcSnapshotGenerator.snapshot(JdbcSnapshotGenerator.java:69) ~[liquibase.jar:na]
          at liquibase.snapshot.SnapshotGeneratorChain.snapshot(SnapshotGeneratorChain.java:49) ~[liquibase.jar:na]
          at liquibase.snapshot.DatabaseSnapshot.include(DatabaseSnapshot.java:315) ~[liquibase.jar:na]
          at liquibase.snapshot.DatabaseSnapshot.init(DatabaseSnapshot.java:100) ~[liquibase.jar:na]
          at liquibase.snapshot.DatabaseSnapshot.(DatabaseSnapshot.java:59) ~[liquibase.jar:na]
          at liquibase.snapshot.JdbcDatabaseSnapshot.(JdbcDatabaseSnapshot.java:39) ~[liquibase.jar:na]
          at liquibase.snapshot.SnapshotGeneratorFactory.createSnapshot(SnapshotGeneratorFactory.java:217) ~[liquibase.jar:na]
          at liquibase.snapshot.SnapshotGeneratorFactory.createSnapshot(SnapshotGeneratorFactory.java:190) ~[liquibase.jar:na]
          at liquibase.command.core.DiffCommand.createReferenceSnapshot(DiffCommand.java:221) ~[liquibase.jar:na]
          at liquibase.command.core.DiffCommand.createDiffResult(DiffCommand.java:143) ~[liquibase.jar:na]
          at liquibase.command.core.GenerateChangeLogCommand.run(GenerateChangeLogCommand.java:46) ~[liquibase.jar:na]
          at liquibase.command.AbstractCommand.execute(AbstractCommand.java:19) ~[liquibase.jar:na]
          ... 4 common frames omitted
  Caused by: java.sql.SQLException: Неподдерживаемая кодовая таблица (добавьте orai18n.jar в маршрут классов): CL8MSWIN1251
          at oracle.sql.CharacterSetUnknown.failCharsetUnknown(CharacterSetFactoryThin.java:233) ~[ojdbc8.jar:19.3.0.0.0]
          at oracle.sql.CharacterSetUnknown.convert(CharacterSetFactoryThin.java:194) ~[ojdbc8.jar:19.3.0.0.0]
          at oracle.jdbc.driver.PhysicalConnection.throughDbCharset(PhysicalConnection.java:10365) ~[ojdbc8.jar:19.3.0.0.0]
          at oracle.jdbc.driver.PhysicalConnection.enquoteIdentifier(PhysicalConnection.java:10442) ~[ojdbc8.jar:19.3.0.0.0]
          at oracle.jdbc.driver.OracleStatement.enquoteIdentifier(OracleStatement.java:6452) ~[ojdbc8.jar:19.3.0.0.0]
          at oracle.jdbc.driver.OracleStatement.getColumnIndex(OracleStatement.java:3853) ~[ojdbc8.jar:19.3.0.0.0]
          at oracle.jdbc.driver.InsensitiveScrollableResultSet.findColumn(InsensitiveScrollableResultSet.java:270) ~[ojdbc8.jar:19.3.0.0.0]
          at oracle.jdbc.driver.GeneratedResultSet.getString(GeneratedResultSet.java:596) ~[ojdbc8.jar:19.3.0.0.0]
          at liquibase.snapshot.jvm.JdbcSnapshotGenerator.getDatabaseCatalogNames(JdbcSnapshotGenerator.java:149) ~[liquibase.jar:na]
          at liquibase.snapshot.jvm.CatalogSnapshotGenerator.snapshotObject(CatalogSnapshotGenerator.java:35) ~[liquibase.jar:na]
          ... 18 common frames omitte

How to fix this?


问:
How to avoid blink when updating a ContentControl?
I have a DataTemplate defined as below.

```<code>        <DataTemplate x:Key="singleUnit">
            <RelativePanel >
                <Button Padding="0,0,0,0" BorderThickness="0" Background="Transparent" Width="180" Height="210" Margin="0,0,70,20"
                        Style="{StaticResource textButtonStyle1}"
                        Command="{Binding ClickCommand}" CommandParameter="{Binding itemIndex}">
                    <StackPanel Orientation="Vertical">
                        <Image Source="{Binding icon_url, Converter={StaticResource _path2Image}}" Width="150" Height="150" Stretch="Uniform" Margin="0,0,0,0"/>
                        <Image Source="ms-appx:///Assets/SettingPage/Selected.png" Width="30" Height="30" Margin="130,-250,0,0"
                               Opacity="{Binding isSelected, Converter={StaticResource _selectedToOpacity}}"/>
                    </StackPanel>
                </Button>
            </RelativePanel>
        </DataTemplate>
</code>```

And I will assign the DataTemplate to a ContentControl's ContentTemplate. In the DataTemplate, it contains two Images(inside of a Button), one is main Image, another one is the corner icon(the Marker). And each time I need to update the corner icon only: to change its Opacity for 0 to 1 or ortherwise.

But when I use below code to get this function, I find sometimes the main Image will blink. I find some post from StackOverflow. Someone said it is caused by the Button's trigger setting. But by Edit Button's Copy, I do not find any key word of trigger now.

```<code>    private void SetMarker(int index)
    {
        ContentControl ccUnit = InitCCUnit(previousSelectedIndex, false);
        wrapGrid.Children[previousSelectedIndex] = ccUnit;

        ccUnit = InitCCUnit(index, true);
        wrapGrid.Children[index] = ccUnit;

        previousSelectedIndex = index;
    }

    private ContentControl InitCCUnit(int index, bool setMarked)
    {
        ContentControl ccUnit = new ContentControl();
        ccUnit.ContentTemplate = this.Resources["singleUnit"] as DataTemplate;

        if (setMarked)
            dms[index].isSelected = true;
        else
            dms[index].isSelected = false;

        ccUnit.Content = dms[index];
        return ccUnit;
    }
</code>```

Code of DataModel: variable dms is the array which contains instance if DataModel

```<code>    public class DataModel
    {
        public string icon_url { get; set; }
        public int itemIndex { get; set; }
        public bool isSelected { get; set; }
        public ICommand ClickCommand { get; set; }
    }

    DataModel[] dms;
</code>```

For example, there are total 6 Images. And I click two of them, named A and B.
When I click A, then the icon of A(a small tick icon) is shown(while Image of A is kept shown); at the same time the icon of B is hiden (while Image of B is kept shown). Or vice versa.

Problem:
Here when icon of B is hiden (means I click item A), then sometimes the Image of B will blink once. Not always. Why and how to solve it?

More:
I make a demo project to show this issue, pelase check this link to get the code:
https://github.com/tomxue/BlinkIssueInUWP.git

Richard mentioned using INotifyPropertyChanged, but I do not know how to combind it together with DataTemplate.

答:
I analyzed your code and found the cause of the blink.

The main reason is that you re-created the ContentControl and replaced the old one with a new one, which is not necessary.

Please try this:

Implement the INotifyPropertyChanged interface for the DataModel:

public class DataModel:INotifyPropertyChanged
{
    public string icon_url { get; set; }
    public bool ssml_support { get; set; }
    public string data_name { get; set; }
    public string data_type { get; set; }
    public int itemIndex { get; set; }
    private bool _isSelected;
    public bool isSelected
    {
        get => _isSelected;
        set
        {
            _isSelected = value;
            OnPropertyChanged();
        }
    }
    public ICommand ClickCommand { get; set; }

    public event PropertyChangedEventHandler PropertyChanged;
    public void OnPropertyChanged([CallerMemberName]string propertyName = "")
    {
        PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
    }
}
```

<ol start="2">
<li>Rewrite <code>SetMarker</code> method:</li>
</ol>

<pre class="lang-cs prettyprint-override"><code>private void SetMarker(int index)
{
    ContentControl ccUnit = wrapGrid.Children[previousSelectedIndex] as ContentControl;
    var previousContent = ccUnit.Content as DataModel;
    previousContent.isSelected = false;

    ContentControl currentUnit= wrapGrid.Children[index] as ContentControl;
    var currentContent = currentUnit.Content as DataModel;
    currentContent.isSelected = true;

    previousSelectedIndex = index;
}
</code>```

This way, we don't need to create a new control, we just need to modify the state of the old control. This will not cause the so-called blink problem.

Body:
I have a DataTemplate defined as below.

        <DataTemplate x:Key="singleUnit">
            <RelativePanel >
                <Button Padding="0,0,0,0" BorderThickness="0" Background="Transparent" Width="180" Height="210" Margin="0,0,70,20"
                        Style="{StaticResource textButtonStyle1}"
                        Command="{Binding ClickCommand}" CommandParameter="{Binding itemIndex}">
                    <StackPanel Orientation="Vertical">
                        <Image Source="{Binding icon_url, Converter={StaticResource _path2Image}}" Width="150" Height="150" Stretch="Uniform" Margin="0,0,0,0"/>
                        <Image Source="ms-appx:///Assets/SettingPage/Selected.png" Width="30" Height="30" Margin="130,-250,0,0"
                               Opacity="{Binding isSelected, Converter={StaticResource _selectedToOpacity}}"/>
                    </StackPanel>
                </Button>
            </RelativePanel>
        </DataTemplate>

And I will assign the DataTemplate to a ContentControl's ContentTemplate. In the DataTemplate, it contains two Images(inside of a Button), one is main Image, another one is the corner icon(the Marker). And each time I need to update the corner icon only: to change its Opacity for 0 to 1 or ortherwise.

But when I use below code to get this function, I find sometimes the main Image will blink. I find some post from StackOverflow. Someone said it is caused by the Button's trigger setting. But by Edit Button's Copy, I do not find any key word of trigger now.

    private void SetMarker(int index)
    {
        ContentControl ccUnit = InitCCUnit(previousSelectedIndex, false);
        wrapGrid.Children[previousSelectedIndex] = ccUnit;

        ccUnit = InitCCUnit(index, true);
        wrapGrid.Children[index] = ccUnit;

        previousSelectedIndex = index;
    }

    private ContentControl InitCCUnit(int index, bool setMarked)
    {
        ContentControl ccUnit = new ContentControl();
        ccUnit.ContentTemplate = this.Resources["singleUnit"] as DataTemplate;

        if (setMarked)
            dms[index].isSelected = true;
        else
            dms[index].isSelected = false;

        ccUnit.Content = dms[index];
        return ccUnit;
    }

Code of DataModel: variable dms is the array which contains instance if DataModel

    public class DataModel
    {
        public string icon_url { get; set; }
        public int itemIndex { get; set; }
        public bool isSelected { get; set; }
        public ICommand ClickCommand { get; set; }
    }

    DataModel[] dms;

For example, there are total 6 Images. And I click two of them, named A and B.
When I click A, then the icon of A(a small tick icon) is shown(while Image of A is kept shown); at the same time the icon of B is hiden (while Image of B is kept shown). Or vice versa.

Problem:
Here when icon of B is hiden (means I click item A), then sometimes the Image of B will blink once. Not always. Why and how to solve it?

More:
I make a demo project to show this issue, pelase check this link to get the code:
https://github.com/tomxue/BlinkIssueInUWP.git

Richard mentioned using INotifyPropertyChanged, but I do not know how to combind it together with DataTemplate.

Body:
I analyzed your code and found the cause of the blink.

The main reason is that you re-created the ContentControl and replaced the old one with a new one, which is not necessary.

Please try this:

Implement the INotifyPropertyChanged interface for the DataModel:

public class DataModel:INotifyPropertyChanged
{
    public string icon_url { get; set; }
    public bool ssml_support { get; set; }
    public string data_name { get; set; }
    public string data_type { get; set; }
    public int itemIndex { get; set; }
    private bool _isSelected;
    public bool isSelected
    {
        get => _isSelected;
        set
        {
            _isSelected = value;
            OnPropertyChanged();
        }
    }
    public ICommand ClickCommand { get; set; }

    public event PropertyChangedEventHandler PropertyChanged;
    public void OnPropertyChanged([CallerMemberName]string propertyName = "")
    {
        PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
    }
}

Rewrite SetMarker method:

private void SetMarker(int index)
{
    ContentControl ccUnit = wrapGrid.Children[previousSelectedIndex] as ContentControl;
    var previousContent = ccUnit.Content as DataModel;
    previousContent.isSelected = false;

    ContentControl currentUnit= wrapGrid.Children[index] as ContentControl;
    var currentContent = currentUnit.Content as DataModel;
    currentContent.isSelected = true;

    previousSelectedIndex = index;
}

This way, we don't need to create a new control, we just need to modify the state of the old control. This will not cause the so-called blink problem.


问:
SelectMany doesn't work on cosmosDb for child properties?
When I try to use selectMany on queryable that I build against cosmosdb I always get exception:

The LINQ expression 'DbSet
      .Where(t => t.Id == __timelineId_0)
      .SelectMany(
          source: t => EF.Property>(t, "GraduationEvents")
              .AsQueryable(),
          collectionSelector: (t, c) => new TransparentIdentifier(
              Outer = t,
              Inner = c
          ))' could not be translated. Either rewrite the query in a form that can be translated, or switch to client evaluation explicitly by inserting a call to either AsEnumerable(), AsAsyncEnumerable(), ToList(), or ToListAsync(). See https://go.microsoft.com/fwlink/?linkid=2101038 for more information.

The query doesn't matter, always when I use selectMany I get this error.

Example query:

```<code> await _dbContext.Timelines.Where(x => x.Id == timelineId).Select(x => x.GraduationEvents).SelectMany(x => x).ToListAsync();
</code>```

My entity configuration:

```<code>        public void Configure(EntityTypeBuilder<Timeline> builder)
    {
        builder.HasKey(x => x.Id);
        builder.HasAlternateKey(x => x.Id);
        builder.OwnsMany(x => x.GraduationEvents, x => x.OwnsMany(graduationEvent => graduationEvent.Subjects));
    }
</code>```

I also tried to use native cosmosClient but when I query the base with plain sql I get empty objects (all nulls). Any thoughts what am I doing wrong?

Sajid - I tried your soulution but the exception remains the same

答:
Try calling directly .SelectMany() over the List property (GraduationEvents).

I usually then call AsDocumentQuery() to generate the query to CosmosDB and then execute that query to retrieve the results.

Some pseudo c# to clarify this a bit:

var query = this.documentClient.CreateDocumentQuery(uri, options)
    .SelectMany(x => x.GraduationEvents).AsDocumentQuery();

List<T> results = new List<T>();
while (query.HasMoreResults)
{
    results.AddRange(await query.ExecuteNextAsync());
}
```

Edit: This approach uses the native Azure DocumentClient library.

Body:
When I try to use selectMany on queryable that I build against cosmosdb I always get exception:

The LINQ expression 'DbSet
      .Where(t => t.Id == __timelineId_0)
      .SelectMany(
          source: t => EF.Property>(t, "GraduationEvents")
              .AsQueryable(),
          collectionSelector: (t, c) => new TransparentIdentifier(
              Outer = t,
              Inner = c
          ))' could not be translated. Either rewrite the query in a form that can be translated, or switch to client evaluation explicitly by inserting a call to either AsEnumerable(), AsAsyncEnumerable(), ToList(), or ToListAsync(). See https://go.microsoft.com/fwlink/?linkid=2101038 for more information.

The query doesn't matter, always when I use selectMany I get this error.

Example query:

 await _dbContext.Timelines.Where(x => x.Id == timelineId).Select(x => x.GraduationEvents).SelectMany(x => x).ToListAsync();

My entity configuration:

        public void Configure(EntityTypeBuilder<Timeline> builder)
    {
        builder.HasKey(x => x.Id);
        builder.HasAlternateKey(x => x.Id);
        builder.OwnsMany(x => x.GraduationEvents, x => x.OwnsMany(graduationEvent => graduationEvent.Subjects));
    }

I also tried to use native cosmosClient but when I query the base with plain sql I get empty objects (all nulls). Any thoughts what am I doing wrong?

Sajid - I tried your soulution but the exception remains the same

Body:
Try calling directly .SelectMany() over the List property (GraduationEvents).

I usually then call AsDocumentQuery() to generate the query to CosmosDB and then execute that query to retrieve the results.

Some pseudo c# to clarify this a bit:

var query = this.documentClient.CreateDocumentQuery(uri, options)
    .SelectMany(x => x.GraduationEvents).AsDocumentQuery();

List<T> results = new List<T>();
while (query.HasMoreResults)
{
    results.AddRange(await query.ExecuteNextAsync());
}

Edit: This approach uses the native Azure DocumentClient library.


问:
Migrating Paperclip database to Active Storage Amazon S3
We are in the process of migrating paperclip to active storage.But we want to move Paperclip storage from database to Active Storage Amazon S3. Can anyone point me to a documentation for this? I can't seem to find one.</p>

答:
Maybe this article can help you. Code is missing due to Github username update but the main idea is there. </p>

<p>Or simply the documentation of Paperclip. As you wish. </p>

Body:
Maybe this article can help you. Code is missing due to Github username update but the main idea is there.

Or simply the documentation of Paperclip. As you wish.


问:
pointer not updating the value it is pointing to inside void function
I've made a simple function that simple does the addition and absolute difference between the parameters using pointers, but when I try to update the pointer, the pointer still has the old value. why is this so, or what am I doing wrong:

```<code>#include <stdio.h>
#include <cstdlib>

void update(int *a,int *b) {
int temp = *a;
int temp2 = *b;
int temp3 =0;
temp3 = temp + temp2;
printf("%d",temp3);
*b = abs(*a - *b);
 a = &temp3; // it is not updating
}

int main() {
    int a, b;
    int *pa = &a, *pb = &b;

    scanf("%d %d", &a, &b);
    update(pa, pb);
    printf("%d\n%d", a, b);

    return 0;
}
</code>```

the pointer a is not updating and still retains its old value inside the function update

答:
a is a copy of the pointer that was passed. At the end of update, a is lost. When you do this:

```<code>a = &temp3;
</code>```

You change the value of a, but that doesn't matter, because a is gone after that anyway. Instead, assign the value to where it's pointing at, much like you did with b:

```<code>*a = temp3;
</code>```

You could also use references instead of pointers:

```<code>void update(int &a, int &b) {
    int temp = a;
    int temp2 = b;
    int temp3 = temp + temp2;
    printf("%d ", temp3);
    b = abs(a - b);
    a = temp3;
}

int main() {
    int a, b;
    scanf("%d %d", &a, &b);
    update(a, b);
    printf("%d\n%d", a, b);
    return 0;
}
</code>```

Body:
I've made a simple function that simple does the addition and absolute difference between the parameters using pointers, but when I try to update the pointer, the pointer still has the old value. why is this so, or what am I doing wrong:

#include <stdio.h>
#include <cstdlib>

void update(int *a,int *b) {
int temp = *a;
int temp2 = *b;
int temp3 =0;
temp3 = temp + temp2;
printf("%d",temp3);
*b = abs(*a - *b);
 a = &temp3; // it is not updating
}

int main() {
    int a, b;
    int *pa = &a, *pb = &b;

    scanf("%d %d", &a, &b);
    update(pa, pb);
    printf("%d\n%d", a, b);

    return 0;
}

the pointer a is not updating and still retains its old value inside the function update

Body:
a is a copy of the pointer that was passed. At the end of update, a is lost. When you do this:

a = &temp3;

You change the value of a, but that doesn't matter, because a is gone after that anyway. Instead, assign the value to where it's pointing at, much like you did with b:

*a = temp3;

You could also use references instead of pointers:

void update(int &a, int &b) {
    int temp = a;
    int temp2 = b;
    int temp3 = temp + temp2;
    printf("%d ", temp3);
    b = abs(a - b);
    a = temp3;
}

int main() {
    int a, b;
    scanf("%d %d", &a, &b);
    update(a, b);
    printf("%d\n%d", a, b);
    return 0;
}


问:
different behavior with method onCreateOptionsMenu
I found something confused for me in this article
http://developer.android.com/guide/topics/ui/menus.html

Below is simple piece of code and output
When I start application on android 3.0

and 2. line system executed as soon as the activity is created

The 3. and 4. lines were printed when menu was pressed and menu item was chosen

Probem is line 5 and buttonHandler method, that method calls invalidateOptionsMenu();
and result of that calls is line 6 and 7

Why system calls onCreateOptionsMenu before onPrepareOptionsMenu even they have written

On Android 3.0 and higher, you must call invalidateOptionsMenu() when you want to update the menu, because the menu is always open. The system will then call onPrepareOptionsMenu() so you can update the menu items.

In this case onCreateOptionsMenu is called every time after invalidateOptionsMenu(),
but when I start application on android 2.3 onCreateOptionsMenu was called only once.

1 INFO/System.out(382): onCreateOptionsMenu

2 INFO/System.out(382): onPrepareOptionsMenu

3 INFO/System.out(382): onPrepareOptionsMenu

4 INFO/System.out(382): onOptionsItemSelected

5 INFO/System.out(382): buttonHandler

6 INFO/System.out(382): onCreateOptionsMenu

7 INFO/System.out(382): onPrepareOptionsMenu

```<code>public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);
}

public boolean onCreateOptionsMenu(Menu menu) {
    System.out.println("onCreateOptionsMenu");
    MenuInflater inflater = getMenuInflater();
    inflater.inflate(R.menu.game_menu, menu);
    return true;
}

public boolean onPrepareOptionsMenu(Menu menu) {
    System.out.println("onPrepareOptionsMenu");
    return super.onPrepareOptionsMenu(menu);
}

public boolean onOptionsItemSelected(MenuItem item) {
    System.out.println("onOptionsItemSelected");
    return super.onOptionsItemSelected(item);
}

public void buttonHandler(View v){
    System.out.println("buttonHandler");
    invalidateOptionsMenu();
}
</code>```

答: That is probably a documentation bug. I would expect onCreateOptionsMenu() to be called after invalidateOptionsMenu().

ContentLicense: CC BY-SA 3.0

Body:
I found something confused for me in this article
http://developer.android.com/guide/topics/ui/menus.html

Below is simple piece of code and output
When I start application on android 3.0

and 2. line system executed as soon as the activity is created

The 3. and 4. lines were printed when menu was pressed and menu item was chosen

Probem is line 5 and buttonHandler method, that method calls invalidateOptionsMenu();
and result of that calls is line 6 and 7

Why system calls onCreateOptionsMenu before onPrepareOptionsMenu even they have written

On Android 3.0 and higher, you must call invalidateOptionsMenu() when you want to update the menu, because the menu is always open. The system will then call onPrepareOptionsMenu() so you can update the menu items.

In this case onCreateOptionsMenu is called every time after invalidateOptionsMenu(),
but when I start application on android 2.3 onCreateOptionsMenu was called only once.

1 INFO/System.out(382): onCreateOptionsMenu

2 INFO/System.out(382): onPrepareOptionsMenu

3 INFO/System.out(382): onPrepareOptionsMenu

4 INFO/System.out(382): onOptionsItemSelected

5 INFO/System.out(382): buttonHandler

6 INFO/System.out(382): onCreateOptionsMenu

7 INFO/System.out(382): onPrepareOptionsMenu

public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);
}

public boolean onCreateOptionsMenu(Menu menu) {
    System.out.println("onCreateOptionsMenu");
    MenuInflater inflater = getMenuInflater();
    inflater.inflate(R.menu.game_menu, menu);
    return true;
}

public boolean onPrepareOptionsMenu(Menu menu) {
    System.out.println("onPrepareOptionsMenu");
    return super.onPrepareOptionsMenu(menu);
}

public boolean onOptionsItemSelected(MenuItem item) {
    System.out.println("onOptionsItemSelected");
    return super.onOptionsItemSelected(item);
}

public void buttonHandler(View v){
    System.out.println("buttonHandler");
    invalidateOptionsMenu();
}


问:
Retrieving a Provider from TestingModule when using an interface
I am trying to retrieve a provider from a testing module in NestJS, but cannot resolve that module when providing it out of a module using an interface.

This is what I have so far:

```<code>const moduleFixture: TestingModule = await Test.createTestingModule({
  imports: [AppModule],
}).compile()

...

const fooService = moduleFixture.get<FooService>(FooService) // Nest could not find FooService element
</code>```

When the module exporting the FooService is doing something like this...

```<code>@Global()
@Module({
  providers: [{ provide: 'IFooService', useClass: FooService }],
  exports: [{ provide: 'IFooService', useClass: FooService }],
})
export class FooModule {}
</code>```

How can I get the FooService instance to be able to call methods directly?

答:
You'll need to tell the get method to done the same injection token as provided in your code. In this case

const fooService = moduleFixture.get<FooService>('IFooService');
```

Body:
I am trying to retrieve a provider from a testing module in NestJS, but cannot resolve that module when providing it out of a module using an interface.

This is what I have so far:

const moduleFixture: TestingModule = await Test.createTestingModule({
  imports: [AppModule],
}).compile()

...

const fooService = moduleFixture.get<FooService>(FooService) // Nest could not find FooService element

When the module exporting the FooService is doing something like this...

@Global()
@Module({
  providers: [{ provide: 'IFooService', useClass: FooService }],
  exports: [{ provide: 'IFooService', useClass: FooService }],
})
export class FooModule {}

How can I get the FooService instance to be able to call methods directly?


问:
(Swift) How to show Cancel button on searchBar even if there is no text?
I have a searchBar with a Cancel button. Cancel button appears only when I start typing a text in searchBar.

What I want is to show cancel button in the moment user taps the searchBar (when cursor and keyboard appears).

Code:

```<code>let searchController = UISearchController(searchResultsController: nil)
    var isSearchBarEmpty: Bool {
        return searchController.searchBar.text?.isEmpty ?? true
    }
    var searching = false
</code>```

searchBar methods:

```<code>func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String) {
        let cancelButtonAttributes = [NSAttributedString.Key.foregroundColor: UIColor.systemGreen]
        UIBarButtonItem.appearance().setTitleTextAttributes(cancelButtonAttributes , for: .normal)

        searching = true
        searchBar.showsCancelButton = true
        tableView.reloadData()
    }

    func searchBarSearchButtonClicked(_ searchBar: UISearchBar)
    {
        searching = false
        self.searchBar.endEditing(true)
    }

    func searchBarCancelButtonClicked(_ searchBar: UISearchBar) {
        searching = false
        searchBar.text = nil
        searchBar.showsCancelButton = false
        searchBar.endEditing(true)
        tableView.reloadData()
    }
</code>```

答:
You can try delegate method

```<code>func searchBarTextDidBeginEditing(_ searchBar: UISearchBar) {

   searchBar.setShowsCancelButton(true, animated: true)

}
</code>```

And

```<code>func searchBarTextDidEndEditing(_ searchBar: UISearchBar) {

    searchBar.setShowsCancelButton(false, animated: true)
}
</code>```

Body:
I have a searchBar with a Cancel button. Cancel button appears only when I start typing a text in searchBar.

What I want is to show cancel button in the moment user taps the searchBar (when cursor and keyboard appears).

Code:

let searchController = UISearchController(searchResultsController: nil)
    var isSearchBarEmpty: Bool {
        return searchController.searchBar.text?.isEmpty ?? true
    }
    var searching = false

searchBar methods:

func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String) {
        let cancelButtonAttributes = [NSAttributedString.Key.foregroundColor: UIColor.systemGreen]
        UIBarButtonItem.appearance().setTitleTextAttributes(cancelButtonAttributes , for: .normal)

        searching = true
        searchBar.showsCancelButton = true
        tableView.reloadData()
    }

    func searchBarSearchButtonClicked(_ searchBar: UISearchBar)
    {
        searching = false
        self.searchBar.endEditing(true)
    }

    func searchBarCancelButtonClicked(_ searchBar: UISearchBar) {
        searching = false
        searchBar.text = nil
        searchBar.showsCancelButton = false
        searchBar.endEditing(true)
        tableView.reloadData()
    }

Body:
You can try delegate method

func searchBarTextDidBeginEditing(_ searchBar: UISearchBar) {

   searchBar.setShowsCancelButton(true, animated: true)

}

And

func searchBarTextDidEndEditing(_ searchBar: UISearchBar) {

    searchBar.setShowsCancelButton(false, animated: true)
}


问:
How to get params from response API Google via PHP
I use PHP call API from Google, but the API response is a function. someone know how can I get params "results" in response. Thanks

答:
I found the solution is API response is jsonp, so I use:</p>

```<code>function jsonp_decode($jsonp, $assoc = false) { // PHP 5.3 adds depth as third parameter to json_decode
    if($jsonp[0] !== '[' && $jsonp[0] !== '{') { // we have JSONP
       $jsonp = substr($jsonp, strpos($jsonp, '('));
    }
    return json_decode(trim($jsonp,'();'), $assoc);
}
</code>```

Body:
I found the solution is API response is jsonp, so I use:

function jsonp_decode($jsonp, $assoc = false) { // PHP 5.3 adds depth as third parameter to json_decode
    if($jsonp[0] !== '[' && $jsonp[0] !== '{') { // we have JSONP
       $jsonp = substr($jsonp, strpos($jsonp, '('));
    }
    return json_decode(trim($jsonp,'();'), $assoc);
}


问:
.bin object executable in command prompt but not in visual studio code
I have the following Practica1.cpp file:

```<code>// Ejemplo de la ordenacion por burbuja sobre un vector de enteros

#include <cstdlib> // Para usar srand y rand
#include <chrono>
#include <iostream>
#include <fstream> // Para usar ficheros
using namespace std;

void OrdenaBurbuja(int *v, int n);

int main(int argc, char *argv[]) {

    int *v;
    int n, i, argumento;
    chrono::time_point<std::chrono::high_resolution_clock> t0, tf; // Para medir el tiempo de ejecución
    double tejecucion; // tiempo de ejecucion del algoritmo en ms
    unsigned long int semilla;
    ofstream fsalida;

    if (argc <= 3) {
        cerr<<"\nError: El programa se debe ejecutar de la siguiente forma.\n\n";
        cerr<<argv[0]<<" NombreFicheroSalida Semilla tamCaso1 tamCaso2 ... tamCasoN\n\n";
        return 0;
    }

    // Abrimos fichero de salida
    fsalida.open(argv[1]);
    if (!fsalida.is_open()) {
        cerr<<"Error: No se pudo abrir fichero para escritura "<<argv[1]<<"\n\n";
        return 0;
    }

    // Inicializamos generador de no. aleatorios
    semilla= atoi(argv[2]);
    srand(semilla);

    // Pasamos por cada tamaÒo de caso
    for (argumento= 3; argumento<argc; argumento++) {

        // Cogemos el tamanio del caso
        n= atoi(argv[argumento]);

        // Reservamos memoria para el vector
        v= new int[n];

        // Generamos vector aleatorio de prueba, con componentes entre 0 y n-1
        for (i= 0; i<n; i++)
            v[i]= rand()%n;

        cerr << "Ejecutando Burbuja para tam. caso: " << n << endl;

        t0= std::chrono::high_resolution_clock::now(); // Cogemos el tiempo en que comienza la ejecuciÛn del algoritmo
        OrdenaBurbuja(v, n); // Ejecutamos el algoritmo para tamaÒo de caso tam
        tf= std::chrono::high_resolution_clock::now(); // Cogemos el tiempo en que finaliza la ejecuciÛn del algoritmo

        unsigned long tejecucion= std::chrono::duration_cast<std::chrono::microseconds>(tf - t0).count();

        cerr << "\tTiempo de ejec. (us): " << tejecucion << " para tam. caso "<< n<<endl;

        // Guardamos tam. de caso y t_ejecucion a fichero de salida
        fsalida<<n<<" "<<tejecucion<<"\n";

        // Liberamos memoria del vector
        delete [] v;
    }

    // Cerramos fichero de salida
    fsalida.close();

    return 0;
}

void OrdenaBurbuja(int *v, int n) {

    int i, j, aux;
    bool haycambios= true;

    i= 0;
    while (haycambios) {

     haycambios=false; // Suponemos vector ya ordenado
     for (j= n-1; j>i; j--) { // Recorremos vector de final a i

         if (v[j-1]>v[j]) { // Dos elementos consecutivos mal ordenados
          aux= v[j]; // Los intercambiamos
          v[j]= v[j-1];
          v[j-1]= aux;
          haycambios= true; // Al intercambiar, hay cambio
         }
     }
    }
}
</code>```

so I compile it like this:
g++ -o Practica1.bin Practica1.cpp -std=c++11
Then I get my Practica1.bin
However when I try
.\Practica1.bin 12345 1000 2000 3000
It just opens a corrupt written file

If I compile it like a .exe:
g++ -o Practica1.exe Practica1.cpp -std=c++11
I get the desired output:
.\Practica1.exe 12345 1000 2000 3000:

```<code>Ejecutando Burbuja para tam. caso: 2000
        Tiempo de ejec. (us): 11853 para tam. caso 2000
Ejecutando Burbuja para tam. caso: 3000
        Tiempo de ejec. (us): 27954 para tam. caso 3000
</code>```

On the other hand, on the cmd I can create the same .exe or .bin as before, and both will compile with:

Practica1.bin salida.txt 12345 1000 2000 3000
or Practica1.exe salida.txt 12345 1000 2000 3000

but without the ./

Of course I tried to compile from Visual Studio Code the .bin without the ./ and it doesn't work

I get better results with the .bin logically, so I think this is important

So I want to know if it is possible to execute .bin files from Visual Studio Code

Thanks in advance

答:
I will assume you are using Windows because you are compiling an exe, maybe unix systems behave likewise.

.\xyz will try to open file xyz, not neccessarily execute it. So Windows will treat the file according to it's extension.

In .\Practica1.exe 12345 1000 2000 3000 Windows recognizes the file as executable, because of the extension .exe, so it will run the program.

However when opening .\Practica1.bin 12345 1000 2000 3000 Windows thinks it's a binary data file because of the extension .bin and tries to open it in the according program, which happens to be a text-editor on your system.

That should explain the first confusion. Now, the extension of a file does not matter when executing. Simply compile as .exe and be happy with it.

Body:
I have the following Practica1.cpp file:

// Ejemplo de la ordenacion por burbuja sobre un vector de enteros

#include <cstdlib> // Para usar srand y rand
#include <chrono>
#include <iostream>
#include <fstream> // Para usar ficheros
using namespace std;

void OrdenaBurbuja(int *v, int n);

int main(int argc, char *argv[]) {

    int *v;
    int n, i, argumento;
    chrono::time_point<std::chrono::high_resolution_clock> t0, tf; // Para medir el tiempo de ejecución
    double tejecucion; // tiempo de ejecucion del algoritmo en ms
    unsigned long int semilla;
    ofstream fsalida;

    if (argc <= 3) {
        cerr<<"\nError: El programa se debe ejecutar de la siguiente forma.\n\n";
        cerr<<argv[0]<<" NombreFicheroSalida Semilla tamCaso1 tamCaso2 ... tamCasoN\n\n";
        return 0;
    }

    // Abrimos fichero de salida
    fsalida.open(argv[1]);
    if (!fsalida.is_open()) {
        cerr<<"Error: No se pudo abrir fichero para escritura "<<argv[1]<<"\n\n";
        return 0;
    }

    // Inicializamos generador de no. aleatorios
    semilla= atoi(argv[2]);
    srand(semilla);

    // Pasamos por cada tamaÒo de caso
    for (argumento= 3; argumento<argc; argumento++) {

        // Cogemos el tamanio del caso
        n= atoi(argv[argumento]);

        // Reservamos memoria para el vector
        v= new int[n];

        // Generamos vector aleatorio de prueba, con componentes entre 0 y n-1
        for (i= 0; i<n; i++)
            v[i]= rand()%n;

        cerr << "Ejecutando Burbuja para tam. caso: " << n << endl;

        t0= std::chrono::high_resolution_clock::now(); // Cogemos el tiempo en que comienza la ejecuciÛn del algoritmo
        OrdenaBurbuja(v, n); // Ejecutamos el algoritmo para tamaÒo de caso tam
        tf= std::chrono::high_resolution_clock::now(); // Cogemos el tiempo en que finaliza la ejecuciÛn del algoritmo

        unsigned long tejecucion= std::chrono::duration_cast<std::chrono::microseconds>(tf - t0).count();

        cerr << "\tTiempo de ejec. (us): " << tejecucion << " para tam. caso "<< n<<endl;

        // Guardamos tam. de caso y t_ejecucion a fichero de salida
        fsalida<<n<<" "<<tejecucion<<"\n";

        // Liberamos memoria del vector
        delete [] v;
    }

    // Cerramos fichero de salida
    fsalida.close();

    return 0;
}

void OrdenaBurbuja(int *v, int n) {

    int i, j, aux;
    bool haycambios= true;

    i= 0;
    while (haycambios) {

     haycambios=false; // Suponemos vector ya ordenado
     for (j= n-1; j>i; j--) { // Recorremos vector de final a i

         if (v[j-1]>v[j]) { // Dos elementos consecutivos mal ordenados
          aux= v[j]; // Los intercambiamos
          v[j]= v[j-1];
          v[j-1]= aux;
          haycambios= true; // Al intercambiar, hay cambio
         }
     }
    }
}

so I compile it like this:
g++ -o Practica1.bin Practica1.cpp -std=c++11
Then I get my Practica1.bin
However when I try
.\Practica1.bin 12345 1000 2000 3000
It just opens a corrupt written file

If I compile it like a .exe:
g++ -o Practica1.exe Practica1.cpp -std=c++11
I get the desired output:
.\Practica1.exe 12345 1000 2000 3000:

Ejecutando Burbuja para tam. caso: 2000
        Tiempo de ejec. (us): 11853 para tam. caso 2000
Ejecutando Burbuja para tam. caso: 3000
        Tiempo de ejec. (us): 27954 para tam. caso 3000

On the other hand, on the cmd I can create the same .exe or .bin as before, and both will compile with:

Practica1.bin salida.txt 12345 1000 2000 3000
or Practica1.exe salida.txt 12345 1000 2000 3000

but without the ./

Of course I tried to compile from Visual Studio Code the .bin without the ./ and it doesn't work

I get better results with the .bin logically, so I think this is important

So I want to know if it is possible to execute .bin files from Visual Studio Code

Thanks in advance


问:
Binding input from Azure blob in function app using python
I have a csv file in azure blob storage that I would like to open and get certain data based on user input. I have two problems:

1) Empty AzureWebJobsStorage value in local.settings.json

I tried to input binding using AzureWebJobsStorage but the value seems empty. I'm not sure how I can what value I should edit in local.settings.json. Hence, getting this error:

Executed 'Functions.HttpExample' (Failed, Id=3a9309d6-7019-4de6-a8d2-43c89921b0f6)
  [18-Feb-20 9:40:36 AM] System.Private.CoreLib: Exception while executing function: Functions.HttpExample. Microsoft.Azure.WebJobs.Host: Value cannot be null.
  [18-Feb-20 9:40:36 AM] Parameter name: connectionString.

I updated the value with connection string of my storage account. It still did not work.

function.json :

```<code>{
  "type": "blob",
  "direction": "in",
  "name": "container_name",
  "path": "blob_name/file_name.csv",
  "connection": "AzureWebJobsStorage"
}
</code>```

Am I using the correct variable names above? As I also received another error :

The specified blob does not exist.

But the blob exist in the storage.

2) How do I display all data inside csv from this (assuming the above issue has resolved)

This is my current code in __init__.py :

```<code>def main(req: func.HttpRequest, inputblob: func.InputStream) -> func.HttpResponse:
    logging.info('Python HTTP trigger function processed a request.')

    section = req.params.get('section')
    bound = req.params.get('bound')
    km_location = req.params.get('km_location')
    location = req.params.get('location')
    if not section:
        try:
            req_body = req.get_json()
        except ValueError:
            pass
        else:
            section = req_body.get('section')

    if section and bound and km_location:
        #pass the following user input to the following function and use them to retrieve remaining info
        #from csv (stored in blob) to user.
        result(section, km_location, bound, location).getResult()

        return func.HttpResponse(f"Hello {section}, {bound}!")
</code>```

答:
About the definition about property in function.json you could refer to this doc: configuration.

name is the variable that represents the blob in function code. It should be same in the function code, and could be any variable you want.

The below is my test function.json, you could also refer to the sample in the link I provide.

```<code>{
      "name": "inputBlob",
      "type": "blob",
      "path": "test/test.csv",
      "connection": "AzureWebJobsStorage",
      "direction": "in"
    }
</code>```

And about how to read csv file, you could refer to my function code.

```<code>import logging
import azure.functions as func
import csv
import codecs

def main(req: func.HttpRequest,inputBlob: func.InputStream) -> func.HttpResponse:
    logging.info('Python HTTP trigger function processed a request.')
    reader=csv.reader(codecs.iterdecode(inputBlob,'utf-8'))
    for line in reader:
        logging.info(line)

    name = req.params.get('name')
    if not name:
        try:
            req_body = req.get_json()
        except ValueError:
            pass
        else:
            name = req_body.get('name')

    if name:
        return func.HttpResponse(f"Hello {name}!")
    else:
        return func.HttpResponse(
             "Please pass a name on the query string or in the request body",
             status_code=400
        )
</code>```

Here is my test result, hope this could help you, if you still have other problem please feel free to let me know.

Body:
I have a csv file in azure blob storage that I would like to open and get certain data based on user input. I have two problems:

1) Empty AzureWebJobsStorage value in local.settings.json

I tried to input binding using AzureWebJobsStorage but the value seems empty. I'm not sure how I can what value I should edit in local.settings.json. Hence, getting this error:

Executed 'Functions.HttpExample' (Failed, Id=3a9309d6-7019-4de6-a8d2-43c89921b0f6)
  [18-Feb-20 9:40:36 AM] System.Private.CoreLib: Exception while executing function: Functions.HttpExample. Microsoft.Azure.WebJobs.Host: Value cannot be null.
  [18-Feb-20 9:40:36 AM] Parameter name: connectionString.

I updated the value with connection string of my storage account. It still did not work.

function.json :

{
  "type": "blob",
  "direction": "in",
  "name": "container_name",
  "path": "blob_name/file_name.csv",
  "connection": "AzureWebJobsStorage"
}

Am I using the correct variable names above? As I also received another error :

The specified blob does not exist.

But the blob exist in the storage.

2) How do I display all data inside csv from this (assuming the above issue has resolved)

This is my current code in __init__.py :

def main(req: func.HttpRequest, inputblob: func.InputStream) -> func.HttpResponse:
    logging.info('Python HTTP trigger function processed a request.')

    section = req.params.get('section')
    bound = req.params.get('bound')
    km_location = req.params.get('km_location')
    location = req.params.get('location')
    if not section:
        try:
            req_body = req.get_json()
        except ValueError:
            pass
        else:
            section = req_body.get('section')

    if section and bound and km_location:
        #pass the following user input to the following function and use them to retrieve remaining info
        #from csv (stored in blob) to user.
        result(section, km_location, bound, location).getResult()

        return func.HttpResponse(f"Hello {section}, {bound}!")

Body:
About the definition about property in function.json you could refer to this doc: configuration.

name is the variable that represents the blob in function code. It should be same in the function code, and could be any variable you want.

The below is my test function.json, you could also refer to the sample in the link I provide.

{
      "name": "inputBlob",
      "type": "blob",
      "path": "test/test.csv",
      "connection": "AzureWebJobsStorage",
      "direction": "in"
    }

And about how to read csv file, you could refer to my function code.

import logging
import azure.functions as func
import csv
import codecs

def main(req: func.HttpRequest,inputBlob: func.InputStream) -> func.HttpResponse:
    logging.info('Python HTTP trigger function processed a request.')
    reader=csv.reader(codecs.iterdecode(inputBlob,'utf-8'))
    for line in reader:
        logging.info(line)

    name = req.params.get('name')
    if not name:
        try:
            req_body = req.get_json()
        except ValueError:
            pass
        else:
            name = req_body.get('name')

    if name:
        return func.HttpResponse(f"Hello {name}!")
    else:
        return func.HttpResponse(
             "Please pass a name on the query string or in the request body",
             status_code=400
        )

Here is my test result, hope this could help you, if you still have other problem please feel free to let me know.