问:
Can't parse request data in Flask when running over SSL
I have a Flask based app running which had a path responding to a POST command.  The incoming data was json so I used the get_json() method to parse the data.

I have now changed the server to run nginx and uwsgi as I now use SSL.  All paths in the app work (GET) but the POST based path no longer sees the incoming data as python and fails. The data is visible in request.data but the get_json method fails.

```<code>@school_app.route('/school/queries', methods=['POST'])
def school_queries():
    req = request.get_json(silent=True, force=True)
    command_name = req["result"]["parameters"]["command-name"]
</code>```

I have also tried to push the request.data through json.loads but this fails as well.

```<code>req = json.loads(request.data)
</code>```

I'm assuming that the server changes have impacted the data but I can't see why it can no longer be parsed as json.

答:
So, the following code works...

```<code>data = request.data
req = json.loads(data)
command_name = req["result"]["parameters"]["command-name"]
</code>```

Still not sure why the get_json method stopped working after the switch to SSL/nginx/uwsgi but at least it works.

Body:
I have a Flask based app running which had a path responding to a POST command.  The incoming data was json so I used the get_json() method to parse the data.

I have now changed the server to run nginx and uwsgi as I now use SSL.  All paths in the app work (GET) but the POST based path no longer sees the incoming data as python and fails. The data is visible in request.data but the get_json method fails.

@school_app.route('/school/queries', methods=['POST'])
def school_queries():
    req = request.get_json(silent=True, force=True)
    command_name = req["result"]["parameters"]["command-name"]

I have also tried to push the request.data through json.loads but this fails as well.

req = json.loads(request.data)

I'm assuming that the server changes have impacted the data but I can't see why it can no longer be parsed as json.

Body:
So, the following code works...

data = request.data
req = json.loads(data)
command_name = req["result"]["parameters"]["command-name"]

Still not sure why the get_json method stopped working after the switch to SSL/nginx/uwsgi but at least it works.


来源: stackexchange

问:
PHP variable in href in PHP
I'm struggling with the syntax of this:

```<code>echo '<strong><a href="<?php echo get_post_meta( get_the_ID(), 'data_sheet', true );?>" target="_blank">Datasheet</a></strong>';
</code>```

The central PHP element gets a URL from a WooCommerce custom field (I know this works ok on its own). That needs to be turned into a viable link opening a new page, and the whole sits in a PHP wrapper on the page.

Where am I going wrong?

答:
Try this hopefully, it will work.</p>

```<code>echo '<strong><a href="' . get_post_meta( get_the_ID(), 'data_sheet', true ) . '" target="_blank">Datasheet</a></strong>';
</code>```

ContentLicense: CC BY-SA 3.0

Title: PHP variable in href in PHP

Body:
I'm struggling with the syntax of this:

echo '<a href="<?php echo get_post_meta( get_the_ID(), 'data_sheet', true );?>" target="_blank">Datasheet';

The central PHP element gets a URL from a WooCommerce custom field (I know this works ok on its own). That needs to be turned into a viable link opening a new page, and the whole sits in a PHP wrapper on the page.

Where am I going wrong?

Body:
Try this hopefully, it will work.

echo '<strong><a href="' . get_post_meta( get_the_ID(), 'data_sheet', true ) . '" target="_blank">Datasheet</a></strong>';


问:
How to assign a webaddress to each item fetch from the database, like www.example.com/datafromdatabase
I want to fetch data from the database and assign it to a web address base on it id. For example if I fetch 5 data from database I want to assign those data to a web address without using Get method.

Just like this www.example.com/datafromdatabase instead of this www.example.com?id=datafromdatabase. I have seen many forum site using the "/" but I only know the get "?" method.

答:
You're looking for rewrites in this situation, for Apache you will want to use rewrite rules:

```<code>RewriteEngine on
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^(.*)$ index.php?id=$1 [L,QSA]
</code>```

For nginx you also want to use try_files:

```<code>try_files $uri $uri/ /index.php?id=$uri;
</code>```

Both of these will convert the /directory to index.php?id=directory if the file doesn't exist which will allow images and such to still be served as normal and only rewrite things which aren't files or directories.

Body:
You're looking for rewrites in this situation, for Apache you will want to use rewrite rules:

RewriteEngine on
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^(.*)$ index.php?id=$1 [L,QSA]

For nginx you also want to use try_files:

try_files $uri $uri/ /index.php?id=$uri;

Both of these will convert the /directory to index.php?id=directory if the file doesn't exist which will allow images and such to still be served as normal and only rewrite things which aren't files or directories.


问:
How to add an external javascript library to ionic 3 typescript project
for an assignment we need to make a thermostat app. I would like to do this in ionic but am struggling with using the provided API right now. We have been provided an API.js file with a set of function that communicate the the server we have to get our data from. I tried to make these functions myself via a provider but because the server is returning xml data I have not been successful so far. So I wanted to use the given API.js by including it in my project but am now struggling to do that as well. So I would like to get some insight on either how to include this external API into my ionic project and use the functions that is has, or on how to use the returned xml data (show it in the app and send altered data back).

Since both files are quite large I've provided some snippets below and full files in pastebin links.

The get and put commands we can use are day, time, currentTemperature, targetTemperature, dayTemperature, nightTemperature, weekProgramState and weekProgram.

Thanks a lot in advance!!

The API.js

```<code>var ServerUrl = '';

Type = {
    Day : 'day',
    Night : 'night'
};

Days = {
    Monday : 'Monday',
    Tuesday : 'Tuesday',
    Wednesday : 'Wednesday',
    Thursday : 'Thursday',
    Friday : 'Friday',
    Saturday : 'Saturday',
    Sunday : 'Sunday'
};

var MinTemperature = parseFloat(5.0);
var MaxTemperature = parseFloat(30.0);
var MaxSwitches = 5;

var Time;
var CurrentDay;
var DayTemperature;
var NightTemperature;
var CurrentTemperature;
var TargetTemperature;
var ProgramState;

var Program = {};
Program[Days.Monday]    = [];
Program[Days.Tuesday]   = [];
Program[Days.Wednesday] = [];
Program[Days.Thursday]  = [];
Program[Days.Friday]    = [];
Program[Days.Saturday]  = [];
Program[Days.Sunday]    = [];

/* Retrive day program
*/
function getProgram(day) {
    return Program[day];
}

/* Sorts the heating periods (the periods when the heating is on) and merges overlapping ones
*/
function sortMergeProgram(day) {
    var program = getProgram(day);
    program.sort(function(a, b){return parseTime(a[0])-parseTime(b[0])});
    for (var i = 0; i < program.length - 1; i++) {
        if (parseTime(program[i][1]) >= parseTime(program[i+1][0])) {
            var start = (program[i][0]);
            var end = (parseTime(program[i][1]) > parseTime(program[i+1][1])) ? program[i][1] : program[i+1][1];
            program.splice(i, 2);
            program.push([start, end]);
            sortMergeProgram(day);
            break;
        }
    }
}

/* Retrieves all data from the server except for weekProgram
*/
function get(attribute_name, xml_tag) {
    return requestData(
        "/"+attribute_name,
        function(data) {
            return $(data).find(xml_tag).text();
        }
    );
}

/* Retrieves the week program
*/
function getWeekProgram() {
    return requestData(
        '/weekProgram',
        function(data) {
            $(data).find('day').each(function() {
                var day = $(this).attr('name');
                Program[day] = [];
                $(this).find('switch').each(function() {
                    if ($(this).attr('state') == 'on') {
                        if ($(this).attr('type') == Type.Day) {
                            getProgram(day).push([$(this).text(), '00:00']);
                        } else {
                            getProgram(day)[getProgram(day).length - 1][1] = $(this).text();
                        }
                    }
                })
            });
            return Program;
        }
    );
}
</code>```

The returned XML data

```<code><thermostat><current_day>Thursday</current_day>
<time>23:32</time>
<current_temperature>16.0</current_temperature>
<target_temperature>16.0</target_temperature>
<day_temperature>22.0</day_temperature>
<night_temperature>19.0</night_temperature>
<week_program_state>off</week_program_state>
<week_program state="off">
  <day name="Monday">
    <switch type="day" state="off">00:00</switch>
    <switch type="day" state="off">00:00</switch>
    <switch type="day" state="off">00:00</switch>
    <switch type="night" state="off">00:00</switch>
    <switch type="night" state="off">00:00</switch>
    <switch type="night" state="off">00:00</switch>
    <switch type="day" state="on">05:00</switch>
    <switch type="night" state="on">08:00</switch>
    <switch type="day" state="on">12:00</switch>
    <switch type="night" state="on">14:00</switch>
  </day>
  <day name="Tuesday">
    <switch type="day" state="off">00:00</switch>
    <switch type="day" state="off">00:00</switch>
    <switch type="day" state="off">00:00</switch>
    <switch type="day" state="off">00:00</switch>
    <switch type="day" state="off">00:00</switch>
    <switch type="night" state="off">00:00</switch>
    <switch type="night" state="off">00:00</switch>
    <switch type="night" state="off">00:00</switch>
    <switch type="night" state="off">00:00</switch>
    <switch type="night" state="off">00:00</switch>
  </day>
</code>```

答:
What I would do is create a file named API.ts. Inside it I would create an API class containing the properties and functions of API.js, correcting for Typesctipt syntax.

It also looks like whoever wrote this file wanted to also use jquery but it isn't imported, so I imported that too. I suppose you are given this file so make sure you place it inside src/assets and correct the import path in my code in order to have the matching filename.

So here's what I have for you:

import * as $ from '.assets/jquery.js';

export class API {
  ServerUrl = '';

  Type = {
    Day: 'day',
    Night: 'night'
  };

  Days = {
    Monday: 'Monday',
    Tuesday: 'Tuesday',
    Wednesday: 'Wednesday',
    Thursday: 'Thursday',
    Friday: 'Friday',
    Saturday: 'Saturday',
    Sunday: 'Sunday'
  };

  MinTemperature = parseFloat('5.0');
  MaxTemperature = parseFloat('30.0');
  MaxSwitches = 5;

  Time;
  CurrentDay;
  DayTemperature;
  NightTemperature;
  CurrentTemperature;
  TargetTemperature;
  ProgramState;

  Program:any = {};

  constructor() {
    this.Program[this.Days.Monday]    = [];
    this.Program[this.Days.Tuesday]   = [];
    this.Program[this.Days.Wednesday] = [];
    this.Program[this.Days.Thursday]  = [];
    this.Program[this.Days.Friday]    = [];
    this.Program[this.Days.Saturday]  = [];
    this.Program[this.Days.Sunday]    = [];
  }

  /* Retrive day program
   */
  getProgram(day) {
    return this.Program[day];
  }

  /* Sorts the heating periods (the periods when the heating is on) and merges overlapping ones
   */
  sortMergeProgram(day) {
    let program = this.getProgram(day);
    program.sort(function(a, b) {
      return this.parseTime(a[0]) - this.parseTime(b[0])
    });
    for (let i = 0; i < program.length - 1; i++) {
      if (this.parseTime(program[i][1]) >= this.parseTime(program[i + 1][0])) {
        let start = (program[i][0]);
        let end = (this.parseTime(program[i][1]) > this.parseTime(program[i + 1][1])) ? program[i][1] : program[i + 1][1];
        program.splice(i, 2);
        program.push([start, end]);
        this.sortMergeProgram(day);
        break;
      }
    }
  }

  /* Retrieves all data from the server except for weekProgram
   */
  get(attribute_name, xml_tag) {
    return this.requestData(
      "/" + attribute_name,
      function(data) {
        return $(data).find(xml_tag).text();
      }
    );
  }

  /* Retrieves the week program
   */
  getWeekProgram() {
    return this.requestData(
      '/weekProgram',
      function(data) {
        $(data).find('day').each(function() {
          let day = (<any>$(this)).attr('name');
          this.Program[day] = [];
          $(this).find('switch').each(function() {
            if ((<any>$(this)).attr('state') == 'on') {
              if ((<any>$(this)).attr('type') == this.Type.Day) {
                this.getProgram(day).push([$(this).text(), '00:00']);
              } else {
                this.getProgram(day)[this.getProgram(day).length - 1][1] = $(this).text();
              }
            }
          })
        });
        return this.Program;
      }
    );
  }

  /* Uploads all data to the server except for currentTemperature and weekProgram
   */
  put(attribute_name, xml_tag, value) {
    this.uploadData("/" + attribute_name, "<" + xml_tag + ">" + value + "</" + xml_tag + ">");
  }

  requestData(address, func) {
    let result;
    (<any>$).ajax({
      type: "get",
      url: this.ServerUrl + address,
      dataType: "xml",
      async: false,
      success: function(data) {
        result = func(data);
      }
    });
    return result;
  }

  /* Uploads the week program
   */
  setWeekProgram() {
    let doc = document.implementation.createDocument(null, null, null);
    let program = doc.createElement('week_program');
    program.setAttribute('state', this.ProgramState ? 'on' : 'off');
    for (let key in this.Program) {
      let day = doc.createElement('day');
      day.setAttribute('name', key);

      let daySwitches = [];
      let nightSwitches = [];

      let i, text, sw;
      let periods = this.getProgram(key);
      for (i = 0; i < periods.length; i++) {
        daySwitches.push(periods[i][0]);
        nightSwitches.push(periods[i][1]);
      }

      for (i = 0; i < this.MaxSwitches; i++) {
        sw = doc.createElement('switch');
        sw.setAttribute('type', this.Type.Day);

        if (i < daySwitches.length) {
          sw.setAttribute('state', 'on');
          text = doc.createTextNode(daySwitches[i]);
        } else {
          sw.setAttribute('state', 'off');
          text = doc.createTextNode('00:00');
        }
        sw.appendChild(text);
        day.appendChild(sw);
      }

      for (i = 0; i < this.MaxSwitches; i++) {
        sw = doc.createElement('switch');
        sw.setAttribute('type', this.Type.Night);

        if (i < nightSwitches.length) {
          sw.setAttribute('state', 'on');
          text = doc.createTextNode(nightSwitches[i]);
        } else {
          sw.setAttribute('state', 'off');
          text = doc.createTextNode('00:00');
        }
        sw.appendChild(text);
        day.appendChild(sw);
      }
      program.appendChild(day);
    }
    doc.appendChild(program);
    this.uploadData('/weekProgram', (new XMLSerializer()).serializeToString(doc));
  }

  /* Creates the default week program
   */
  setDefault() {
    let doc = document.implementation.createDocument(null, null, null);
    let program = doc.createElement('week_program');
    program.setAttribute('state', this.ProgramState ? 'on' : 'off');
    for (let key in this.Program) {
      let day = doc.createElement('day');
      day.setAttribute('name', key);

      let daySwitches = [];
      let nightSwitches = [];

      let i, text, sw;

      for (i = 0; i < this.MaxSwitches; i++) {
        sw = doc.createElement('switch');
        sw.setAttribute('type', this.Type.Night);
        sw.setAttribute('state', 'off');
        text = doc.createTextNode('00:00');
        sw.appendChild(text);
        day.appendChild(sw);
      }

      for (i = 0; i < this.MaxSwitches; i++) {
        sw = doc.createElement('switch');
        sw.setAttribute('type', this.Type.Day);
        sw.setAttribute('state', 'off');
        text = doc.createTextNode('00:00');
        sw.appendChild(text);
        day.appendChild(sw);
      }

      program.appendChild(day);
    }
    doc.appendChild(program);
    this.uploadData('/weekProgram', (new XMLSerializer()).serializeToString(doc));
  }

  uploadData(address, xml) {
    (<any>$).ajax({
      type: "put",
      url: this.ServerUrl + address,
      contentType: 'application/xml',
      data: xml,
      async: false
    });
  }

  parseTime(t) {
    return parseFloat(t.substr(0, 2)) + parseFloat(t.substr(3, 2)) / 60;
  }

  /* Adds a heating period for a specific day
   */
  addPeriod(day, start, end) {
    let program = this.getWeekProgram()[day];
    program.push([start, end]);
    this.sortMergeProgram(day);
    this.setWeekProgram();
  }

  /* Removes a heating period from a specific day.
     idx is the idex of the period with values from 0 to 4
  */
  removePeriod(day, idx) {
    let program = this.getWeekProgram()[day];
    let start = program[idx][0];
    let end = program[idx][1];
    program.splice(idx, 1);
    this.setWeekProgram();
  }

  /* Checks whether the temperature is within the range [5.0,30.0]
   */
  inTemperatureBoundaries(temp) {
    temp = parseFloat(temp);
    return (temp >= this.MinTemperature && temp <= this.MaxTemperature);
  }
}
```

<p>Now in any ionic component you want to consume the API, you just import it like so:</p>

<pre class="lang-js prettyprint-override"><code>import { API } from './API'
</code>```

and then in your code use it like so:

export class yourPage {
  constructor(public api: API){}

  yourFunction() {
    this.api.setDefault();
  }
}
```

Body:
for an assignment we need to make a thermostat app. I would like to do this in ionic but am struggling with using the provided API right now. We have been provided an API.js file with a set of function that communicate the the server we have to get our data from. I tried to make these functions myself via a provider but because the server is returning xml data I have not been successful so far. So I wanted to use the given API.js by including it in my project but am now struggling to do that as well. So I would like to get some insight on either how to include this external API into my ionic project and use the functions that is has, or on how to use the returned xml data (show it in the app and send altered data back).

Since both files are quite large I've provided some snippets below and full files in pastebin links.

The get and put commands we can use are day, time, currentTemperature, targetTemperature, dayTemperature, nightTemperature, weekProgramState and weekProgram.

Thanks a lot in advance!!

The API.js

var ServerUrl = '';

Type = {
    Day : 'day',
    Night : 'night'
};

Days = {
    Monday : 'Monday',
    Tuesday : 'Tuesday',
    Wednesday : 'Wednesday',
    Thursday : 'Thursday',
    Friday : 'Friday',
    Saturday : 'Saturday',
    Sunday : 'Sunday'
};

var MinTemperature = parseFloat(5.0);
var MaxTemperature = parseFloat(30.0);
var MaxSwitches = 5;

var Time;
var CurrentDay;
var DayTemperature;
var NightTemperature;
var CurrentTemperature;
var TargetTemperature;
var ProgramState;

var Program = {};
Program[Days.Monday]    = [];
Program[Days.Tuesday]   = [];
Program[Days.Wednesday] = [];
Program[Days.Thursday]  = [];
Program[Days.Friday]    = [];
Program[Days.Saturday]  = [];
Program[Days.Sunday]    = [];

/* Retrive day program
*/
function getProgram(day) {
    return Program[day];
}

/* Sorts the heating periods (the periods when the heating is on) and merges overlapping ones
*/
function sortMergeProgram(day) {
    var program = getProgram(day);
    program.sort(function(a, b){return parseTime(a[0])-parseTime(b[0])});
    for (var i = 0; i < program.length - 1; i++) {
        if (parseTime(program[i][1]) >= parseTime(program[i+1][0])) {
            var start = (program[i][0]);
            var end = (parseTime(program[i][1]) > parseTime(program[i+1][1])) ? program[i][1] : program[i+1][1];
            program.splice(i, 2);
            program.push([start, end]);
            sortMergeProgram(day);
            break;
        }
    }
}

/* Retrieves all data from the server except for weekProgram
*/
function get(attribute_name, xml_tag) {
    return requestData(
        "/"+attribute_name,
        function(data) {
            return $(data).find(xml_tag).text();
        }
    );
}

/* Retrieves the week program
*/
function getWeekProgram() {
    return requestData(
        '/weekProgram',
        function(data) {
            $(data).find('day').each(function() {
                var day = $(this).attr('name');
                Program[day] = [];
                $(this).find('switch').each(function() {
                    if ($(this).attr('state') == 'on') {
                        if ($(this).attr('type') == Type.Day) {
                            getProgram(day).push([$(this).text(), '00:00']);
                        } else {
                            getProgram(day)[getProgram(day).length - 1][1] = $(this).text();
                        }
                    }
                })
            });
            return Program;
        }
    );
}

The returned XML data

<thermostat><current_day>Thursday</current_day>
<time>23:32</time>
<current_temperature>16.0</current_temperature>
<target_temperature>16.0</target_temperature>
<day_temperature>22.0</day_temperature>
<night_temperature>19.0</night_temperature>
<week_program_state>off</week_program_state>
<week_program state="off">
  <day name="Monday">
    <switch type="day" state="off">00:00</switch>
    <switch type="day" state="off">00:00</switch>
    <switch type="day" state="off">00:00</switch>
    <switch type="night" state="off">00:00</switch>
    <switch type="night" state="off">00:00</switch>
    <switch type="night" state="off">00:00</switch>
    <switch type="day" state="on">05:00</switch>
    <switch type="night" state="on">08:00</switch>
    <switch type="day" state="on">12:00</switch>
    <switch type="night" state="on">14:00</switch>
  </day>
  <day name="Tuesday">
    <switch type="day" state="off">00:00</switch>
    <switch type="day" state="off">00:00</switch>
    <switch type="day" state="off">00:00</switch>
    <switch type="day" state="off">00:00</switch>
    <switch type="day" state="off">00:00</switch>
    <switch type="night" state="off">00:00</switch>
    <switch type="night" state="off">00:00</switch>
    <switch type="night" state="off">00:00</switch>
    <switch type="night" state="off">00:00</switch>
    <switch type="night" state="off">00:00</switch>
  </day>

Body:
What I would do is create a file named API.ts. Inside it I would create an API class containing the properties and functions of API.js, correcting for Typesctipt syntax.

It also looks like whoever wrote this file wanted to also use jquery but it isn't imported, so I imported that too. I suppose you are given this file so make sure you place it inside src/assets and correct the import path in my code in order to have the matching filename.

So here's what I have for you:

import * as $ from '.assets/jquery.js';

export class API {
  ServerUrl = '';

  Type = {
    Day: 'day',
    Night: 'night'
  };

  Days = {
    Monday: 'Monday',
    Tuesday: 'Tuesday',
    Wednesday: 'Wednesday',
    Thursday: 'Thursday',
    Friday: 'Friday',
    Saturday: 'Saturday',
    Sunday: 'Sunday'
  };

  MinTemperature = parseFloat('5.0');
  MaxTemperature = parseFloat('30.0');
  MaxSwitches = 5;

  Time;
  CurrentDay;
  DayTemperature;
  NightTemperature;
  CurrentTemperature;
  TargetTemperature;
  ProgramState;

  Program:any = {};

  constructor() {
    this.Program[this.Days.Monday]    = [];
    this.Program[this.Days.Tuesday]   = [];
    this.Program[this.Days.Wednesday] = [];
    this.Program[this.Days.Thursday]  = [];
    this.Program[this.Days.Friday]    = [];
    this.Program[this.Days.Saturday]  = [];
    this.Program[this.Days.Sunday]    = [];
  }

  /* Retrive day program
   */
  getProgram(day) {
    return this.Program[day];
  }

  /* Sorts the heating periods (the periods when the heating is on) and merges overlapping ones
   */
  sortMergeProgram(day) {
    let program = this.getProgram(day);
    program.sort(function(a, b) {
      return this.parseTime(a[0]) - this.parseTime(b[0])
    });
    for (let i = 0; i < program.length - 1; i++) {
      if (this.parseTime(program[i][1]) >= this.parseTime(program[i + 1][0])) {
        let start = (program[i][0]);
        let end = (this.parseTime(program[i][1]) > this.parseTime(program[i + 1][1])) ? program[i][1] : program[i + 1][1];
        program.splice(i, 2);
        program.push([start, end]);
        this.sortMergeProgram(day);
        break;
      }
    }
  }

  /* Retrieves all data from the server except for weekProgram
   */
  get(attribute_name, xml_tag) {
    return this.requestData(
      "/" + attribute_name,
      function(data) {
        return $(data).find(xml_tag).text();
      }
    );
  }

  /* Retrieves the week program
   */
  getWeekProgram() {
    return this.requestData(
      '/weekProgram',
      function(data) {
        $(data).find('day').each(function() {
          let day = (<any>$(this)).attr('name');
          this.Program[day] = [];
          $(this).find('switch').each(function() {
            if ((<any>$(this)).attr('state') == 'on') {
              if ((<any>$(this)).attr('type') == this.Type.Day) {
                this.getProgram(day).push([$(this).text(), '00:00']);
              } else {
                this.getProgram(day)[this.getProgram(day).length - 1][1] = $(this).text();
              }
            }
          })
        });
        return this.Program;
      }
    );
  }

  /* Uploads all data to the server except for currentTemperature and weekProgram
   */
  put(attribute_name, xml_tag, value) {
    this.uploadData("/" + attribute_name, "<" + xml_tag + ">" + value + "</" + xml_tag + ">");
  }

  requestData(address, func) {
    let result;
    (<any>$).ajax({
      type: "get",
      url: this.ServerUrl + address,
      dataType: "xml",
      async: false,
      success: function(data) {
        result = func(data);
      }
    });
    return result;
  }

  /* Uploads the week program
   */
  setWeekProgram() {
    let doc = document.implementation.createDocument(null, null, null);
    let program = doc.createElement('week_program');
    program.setAttribute('state', this.ProgramState ? 'on' : 'off');
    for (let key in this.Program) {
      let day = doc.createElement('day');
      day.setAttribute('name', key);

      let daySwitches = [];
      let nightSwitches = [];

      let i, text, sw;
      let periods = this.getProgram(key);
      for (i = 0; i < periods.length; i++) {
        daySwitches.push(periods[i][0]);
        nightSwitches.push(periods[i][1]);
      }

      for (i = 0; i < this.MaxSwitches; i++) {
        sw = doc.createElement('switch');
        sw.setAttribute('type', this.Type.Day);

        if (i < daySwitches.length) {
          sw.setAttribute('state', 'on');
          text = doc.createTextNode(daySwitches[i]);
        } else {
          sw.setAttribute('state', 'off');
          text = doc.createTextNode('00:00');
        }
        sw.appendChild(text);
        day.appendChild(sw);
      }

      for (i = 0; i < this.MaxSwitches; i++) {
        sw = doc.createElement('switch');
        sw.setAttribute('type', this.Type.Night);

        if (i < nightSwitches.length) {
          sw.setAttribute('state', 'on');
          text = doc.createTextNode(nightSwitches[i]);
        } else {
          sw.setAttribute('state', 'off');
          text = doc.createTextNode('00:00');
        }
        sw.appendChild(text);
        day.appendChild(sw);
      }
      program.appendChild(day);
    }
    doc.appendChild(program);
    this.uploadData('/weekProgram', (new XMLSerializer()).serializeToString(doc));
  }

  /* Creates the default week program
   */
  setDefault() {
    let doc = document.implementation.createDocument(null, null, null);
    let program = doc.createElement('week_program');
    program.setAttribute('state', this.ProgramState ? 'on' : 'off');
    for (let key in this.Program) {
      let day = doc.createElement('day');
      day.setAttribute('name', key);

      let daySwitches = [];
      let nightSwitches = [];

      let i, text, sw;

      for (i = 0; i < this.MaxSwitches; i++) {
        sw = doc.createElement('switch');
        sw.setAttribute('type', this.Type.Night);
        sw.setAttribute('state', 'off');
        text = doc.createTextNode('00:00');
        sw.appendChild(text);
        day.appendChild(sw);
      }

      for (i = 0; i < this.MaxSwitches; i++) {
        sw = doc.createElement('switch');
        sw.setAttribute('type', this.Type.Day);
        sw.setAttribute('state', 'off');
        text = doc.createTextNode('00:00');
        sw.appendChild(text);
        day.appendChild(sw);
      }

      program.appendChild(day);
    }
    doc.appendChild(program);
    this.uploadData('/weekProgram', (new XMLSerializer()).serializeToString(doc));
  }

  uploadData(address, xml) {
    (<any>$).ajax({
      type: "put",
      url: this.ServerUrl + address,
      contentType: 'application/xml',
      data: xml,
      async: false
    });
  }

  parseTime(t) {
    return parseFloat(t.substr(0, 2)) + parseFloat(t.substr(3, 2)) / 60;
  }

  /* Adds a heating period for a specific day
   */
  addPeriod(day, start, end) {
    let program = this.getWeekProgram()[day];
    program.push([start, end]);
    this.sortMergeProgram(day);
    this.setWeekProgram();
  }

  /* Removes a heating period from a specific day.
     idx is the idex of the period with values from 0 to 4
  */
  removePeriod(day, idx) {
    let program = this.getWeekProgram()[day];
    let start = program[idx][0];
    let end = program[idx][1];
    program.splice(idx, 1);
    this.setWeekProgram();
  }

  /* Checks whether the temperature is within the range [5.0,30.0]
   */
  inTemperatureBoundaries(temp) {
    temp = parseFloat(temp);
    return (temp >= this.MinTemperature && temp <= this.MaxTemperature);
  }
}

Now in any ionic component you want to consume the API, you just import it like so:

import { API } from './API'

and then in your code use it like so:

export class yourPage {
  constructor(public api: API){}

  yourFunction() {
    this.api.setDefault();
  }
}


问:
Too many types conversions in a Z80 emulator in Ada
I am doing a Z80 emulator in Ada.
I am implementing the JR (Jump relative) family, But I am not satisfied with my code:

```<code>with Ada.Text_IO;

procedure main is
    type UInt16 is mod 2 ** 16;
    type UInt8  is mod 2 **  8;
    type Int8   is range -128 .. 127;

    package UInt16_IO is new Ada.Text_IO.Modular_IO (UInt16);

    function Two_Complement(N : UInt8) return Int8 is
    begin
        if N <= 127 then
            return Int8 (N);
        end if;
        return Int8 (Integer (N) - 256);
    end Two_Complement;

    -- Relative jump
    function Jr (Address : UInt16; D: UInt8) return UInt16 is
    begin
        return UInt16 (Integer (Address) + Integer (Two_Complement (D) + 2));
    end Jr;

    Address : UInt16;
begin
    Address := 16#683#;
    UInt16_IO.Put (Item => Jr (Address, 16#F1#), Base => 16); -- Get    16#676# which is good !
end main;
</code>```

It seems to work, but I find that there are too many types conversions.
Do you have some advice ?

Thanks,

Olivier.

答:
I suspect that a little alteration in naming might help things out here.

You could use this:

```<code>Subtype Address is UInt16;

Function "+"( Location : Address; Offset: Int8 ) return Address is
  (if Offset < 0 then Location - UInt16(ABS Offset)
   else Location + UInt16(Offset) );
</code>```

Which would allow you to reformulate Jr to this:

```<code>-- Relative jump
function Jr (Location : Address; D: UInt8) return UInt16 is
    Offset : Constant Int8 := Two_Complement(D) + 2;
begin
    return Location + Offset;
end Jr;
</code>```

Body:
I am doing a Z80 emulator in Ada.
I am implementing the JR (Jump relative) family, But I am not satisfied with my code:

with Ada.Text_IO;

procedure main is
    type UInt16 is mod 2 ** 16;
    type UInt8  is mod 2 **  8;
    type Int8   is range -128 .. 127;

    package UInt16_IO is new Ada.Text_IO.Modular_IO (UInt16);

    function Two_Complement(N : UInt8) return Int8 is
    begin
        if N <= 127 then
            return Int8 (N);
        end if;
        return Int8 (Integer (N) - 256);
    end Two_Complement;

    -- Relative jump
    function Jr (Address : UInt16; D: UInt8) return UInt16 is
    begin
        return UInt16 (Integer (Address) + Integer (Two_Complement (D) + 2));
    end Jr;

    Address : UInt16;
begin
    Address := 16#683#;
    UInt16_IO.Put (Item => Jr (Address, 16#F1#), Base => 16); -- Get    16#676# which is good !
end main;

It seems to work, but I find that there are too many types conversions.
Do you have some advice ?

Thanks,

Olivier.

Body:
I suspect that a little alteration in naming might help things out here.

You could use this:

Subtype Address is UInt16;

Function "+"( Location : Address; Offset: Int8 ) return Address is
  (if Offset < 0 then Location - UInt16(ABS Offset)
   else Location + UInt16(Offset) );

Which would allow you to reformulate Jr to this:

-- Relative jump
function Jr (Location : Address; D: UInt8) return UInt16 is
    Offset : Constant Int8 := Two_Complement(D) + 2;
begin
    return Location + Offset;
end Jr;


问:
How to use getch() in a loop (nCurses)
This is my first time using ncurses library. So, I wanted to use getch() to get a character as it is typed by the user (without pressing return every time). However, when I run this code:

```<code>#include <pthread.h>
#include <stdio.h>
#include <curses.h>

void *userInput() {
char c;

while((c = getch()) != '~') {
    printf("%c\n",c);
}

pthread_exit(NULL);

}

int main() {
    cbreak();

    pthread_t threads[4];

    pthread_create(&threads[0], NULL, userInput, NULL);

    pthread_exit(NULL);
}
</code>```

It printf lots of '?'s without getting any input. Could anyone please help me understand whats wrong?
Thank you.

EDIT: removed dead code.

答:
There are at least three problems with the program:

getch will always return an error because you did not initialize the screen with initscr or newterm.  Likewise, the cbreak call does nothing except return an error.

even if you initialized the screen, calling getch with multiple threads will not work predictably because it is not thread-safe. It's an FAQ: Why does (fill in the blank) happen when I use two threads?

the printf does something, but mixing stdio (printf) and curses does not work as you'd like.  Use printw for curses applications.

As for printing ?, those -1's sent to a terminal which expects UTF-8 would likely decide they're not valid UTF-8 and display the replacement character.

Title: How to use getch() in a loop (nCurses)

Body:
This is my first time using ncurses library. So, I wanted to use getch() to get a character as it is typed by the user (without pressing return every time). However, when I run this code:

#include <pthread.h>
#include <stdio.h>
#include <curses.h>

void *userInput() {
char c;

while((c = getch()) != '~') {
    printf("%c\n",c);
}

pthread_exit(NULL);

}

int main() {
    cbreak();

    pthread_t threads[4];

    pthread_create(&threads[0], NULL, userInput, NULL);

    pthread_exit(NULL);
}

It printf lots of '?'s without getting any input. Could anyone please help me understand whats wrong?
Thank you.

EDIT: removed dead code.


问:
How do you embedded your sql queries in php scripts (coding-style)?
how do you embed your sql scripts in php? Do you just write them in a string or a heredoc or do you outsource them to a sql file? Are there any best practices when to outsource them ? Is there an elegant way to organize this?</p>

答:
Once you get to a certain level, you realise that 99% of the SQL you write could be automated. If you write so much queries that you think of a properties file, you're probably doing something that could be simpler:

Most of the stuff we programmers do is CRUD: Create Read Update Delete

As a tool for myself, I built Pork.dbObject. Object Relation Mapper + Active Record in 2 simple classes (Database Abstraction + dbObject class)

A couple of examples from my site:

Create a weblog:

```<code>    $weblog = new Weblog(); // create an empty object to work with.
    $weblog->Author = 'SchizoDuckie'; // mapped internally to strAuthor.
    $weblog->Title = 'A test weblog';
    $weblog->Story = 'This is a test weblog!';
    $weblog->Posted = date("Y-m-d H:i:s");
    $weblog->Save(); // Checks for any changed values and inserts or updates into DB.
    echo ($weblog->ID) // outputs: 1
</code>```

And one reply to it:

```<code>    $reply = new Reply();
    $reply->Author = 'Some random guy';
    $reply->Reply = 'w000t';
    $reply->Posted = date("Y-m-d H:i:s");
    $reply->IP = '127.0.0.1';
    $reply->Connect($weblog); // auto-saves $reply and connects it to $weblog->ID
</code>```

And, fetch and display the weblog + all replies:

```<code>    $weblog = new Weblog(1); //Fetches the row with primary key 1 from table weblogs and hooks it's values into $weblog;

    echo("<h1>{$weblog->Title}</h1>
    <h3>Posted by {$weblog->Author} @ {$weblog->Posted}</h3>
    <div class='weblogpost'>{$weblog->Story}</div>");

    // now fetch the connected posts. this is the real magic:
    $replies = $weblog->Find("Reply"); // fetches a pre-filled array of Reply objects.
    if ($replies != false)
    {
        foreach($replies as $reply)
        {
            echo("<div class='weblogreply'><h4>By {$reply->Author} @ {$reply->Posted}</h4> {$reply->Reply}</div>");
        }
    }
</code>```

The weblog object would look like this:

```<code>class Weblog extends dbObject
{
    function __construct($ID=false)
    {
        $this->__setupDatabase('blogs', // database table
        array('ID_Blog' => 'ID',    // database field => mapped object property
            'strPost' => 'Story',    // as you can see, database field strPost is mapped to $this->Story
            'datPosted' => 'Posted',
            'strPoster' => 'Author',
            'strTitle'  => 'Title',
            'ipAddress'  => 'IpAddress',
            'ID_Blog',    // primary table key
            $ID);    // value of primary key to init with (can be false for new empty object / row)
        $this->addRelation('Reaction'); // define a 1:many relation to Reaction

    }
}
</code>```

See, no manual SQL writing :)
Link + more examples: Pork.dbObject

Oh yeah i also created a rudimentary GUI for my scaffolding tool: Pork.Generator

Body:
Once you get to a certain level, you realise that 99% of the SQL you write could be automated. If you write so much queries that you think of a properties file, you're probably doing something that could be simpler:

Most of the stuff we programmers do is CRUD: Create Read Update Delete

As a tool for myself, I built Pork.dbObject. Object Relation Mapper + Active Record in 2 simple classes (Database Abstraction + dbObject class)

A couple of examples from my site:

Create a weblog:

    $weblog = new Weblog(); // create an empty object to work with.
    $weblog->Author = 'SchizoDuckie'; // mapped internally to strAuthor.
    $weblog->Title = 'A test weblog';
    $weblog->Story = 'This is a test weblog!';
    $weblog->Posted = date("Y-m-d H:i:s");
    $weblog->Save(); // Checks for any changed values and inserts or updates into DB.
    echo ($weblog->ID) // outputs: 1

And one reply to it:

    $reply = new Reply();
    $reply->Author = 'Some random guy';
    $reply->Reply = 'w000t';
    $reply->Posted = date("Y-m-d H:i:s");
    $reply->IP = '127.0.0.1';
    $reply->Connect($weblog); // auto-saves $reply and connects it to $weblog->ID

And, fetch and display the weblog + all replies:

    $weblog = new Weblog(1); //Fetches the row with primary key 1 from table weblogs and hooks it's values into $weblog;

    echo("<h1>{$weblog->Title}</h1>
    <h3>Posted by {$weblog->Author} @ {$weblog->Posted}</h3>
    <div class='weblogpost'>{$weblog->Story}</div>");

    // now fetch the connected posts. this is the real magic:
    $replies = $weblog->Find("Reply"); // fetches a pre-filled array of Reply objects.
    if ($replies != false)
    {
        foreach($replies as $reply)
        {
            echo("<div class='weblogreply'><h4>By {$reply->Author} @ {$reply->Posted}</h4> {$reply->Reply}</div>");
        }
    }

The weblog object would look like this:

class Weblog extends dbObject
{
    function __construct($ID=false)
    {
        $this->__setupDatabase('blogs', // database table
        array('ID_Blog' => 'ID',    // database field => mapped object property
            'strPost' => 'Story',    // as you can see, database field strPost is mapped to $this->Story
            'datPosted' => 'Posted',
            'strPoster' => 'Author',
            'strTitle'  => 'Title',
            'ipAddress'  => 'IpAddress',
            'ID_Blog',    // primary table key
            $ID);    // value of primary key to init with (can be false for new empty object / row)
        $this->addRelation('Reaction'); // define a 1:many relation to Reaction

    }
}

See, no manual SQL writing :)
Link + more examples: Pork.dbObject

Oh yeah i also created a rudimentary GUI for my scaffolding tool: Pork.Generator

OwnerDisplayName: SchizoDuckie

ContentLicense: CC BY-SA 2.5

LastEditorDisplayName: SchizoDuckie


问:
How to repeat a query in postgreSQL, and add the results to a table
I need to run a query 1000 times, and add the results to a table. I have the following code which is what I would like to be repeated:

```<code>Select max_gridco, count(max_gridco) as TaxLots, sum(population) as pop_sum
from
(
    Select tlid, max_gridco, population
    from (
        select tlid, max_gridco, population, st_intersects(tle.geom, acres025.geom)
        from tle, acres025
        where max_gridco not in (0, 1)
        order by RANDOM()
        limit 1000
    ) as count
    where st_intersects = 't'
    order by max_gridco
) as gridcode_count
group by max_gridco;
</code>```

Is there a way that I can run this 1000 times automatically, and in the output table have a column that includes the run number? So my table would look like the following:

Run number | max_gridco | TaxLots | pop_sum

I am trying to do a Loop command in PgAdmin3, but cannot seem to get the syntax correct.

答:
If you need to insert values from a specific select you can do it by using:

```<code>INSERT INTO table2 (column1, column2, column3, ...)
SELECT column1, column2, column3, ...
FROM table1
WHERE condition;
</code>```

(https://www.w3schools.com/sql/sql_insert_into_select.asp)

Is that what you're looking for?

Body:
I need to run a query 1000 times, and add the results to a table. I have the following code which is what I would like to be repeated:

Select max_gridco, count(max_gridco) as TaxLots, sum(population) as pop_sum
from
(
    Select tlid, max_gridco, population
    from (
        select tlid, max_gridco, population, st_intersects(tle.geom, acres025.geom)
        from tle, acres025
        where max_gridco not in (0, 1)
        order by RANDOM()
        limit 1000
    ) as count
    where st_intersects = 't'
    order by max_gridco
) as gridcode_count
group by max_gridco;

Is there a way that I can run this 1000 times automatically, and in the output table have a column that includes the run number? So my table would look like the following:

Run number | max_gridco | TaxLots | pop_sum

I am trying to do a Loop command in PgAdmin3, but cannot seem to get the syntax correct.

Body:
If you need to insert values from a specific select you can do it by using:

INSERT INTO table2 (column1, column2, column3, ...)
SELECT column1, column2, column3, ...
FROM table1
WHERE condition;

(https://www.w3schools.com/sql/sql_insert_into_select.asp)

Is that what you're looking for?


问:
maxWidth uncenters dialog box (modal) for material-ui
I am trying to set the max-width on material-ui's Dialog component. When I set the max width, the modal becomes uncentered. I have created a minimal example here:

```<code>//npm install material-ui
import React from 'react'
import Dialog from 'material-ui/Dialog';
import MuiThemeProvider from 'material-ui/styles/MuiThemeProvider';

function App() {
  return(
    <MuiThemeProvider>
      <div>
        <Dialog open={true} style={{maxWidth: '300px'}}>
          <h2>nice box</h2>
        </Dialog>
        <h1>React App</h1>
      </div>
    </MuiThemeProvider>
  );
}

export default App
</code>```

The result looks like this:

If I remove the style={{maxWidth: '300px'}}, the the Dialog component and its children are centered as expected.

How can I put a maxWidth on the Dialog component and have it still be centered properly? I've tried playing around with it quite a bit without much luck.

答:
Figured it out. I should have been using the contentStyle prop on the Dialog component. Fixed example looks like this:

```<code>//npm install material-ui
import React from 'react'
import Dialog from 'material-ui/Dialog';
import MuiThemeProvider from 'material-ui/styles/MuiThemeProvider';

function App() {
  return(
    <MuiThemeProvider>
      <div>
        <Dialog open={true} contentStyle={{maxWidth: 300}}>
          <h2>nice box</h2>
        </Dialog>
        <h1>React App</h1>
      </div>
    </MuiThemeProvider>
  );
}

export default App
</code>```

Thanks

Body:
I am trying to set the max-width on material-ui's Dialog component. When I set the max width, the modal becomes uncentered. I have created a minimal example here:

//npm install material-ui
import React from 'react'
import Dialog from 'material-ui/Dialog';
import MuiThemeProvider from 'material-ui/styles/MuiThemeProvider';

function App() {
  return(
    <MuiThemeProvider>

        <Dialog open={true} style={{maxWidth: '300px'}}>

nice box

        </Dialog>

React App

    </MuiThemeProvider>
  );
}

export default App

The result looks like this:

If I remove the style={{maxWidth: '300px'}}, the the Dialog component and its children are centered as expected.

How can I put a maxWidth on the Dialog component and have it still be centered properly? I've tried playing around with it quite a bit without much luck.

Body:
Figured it out. I should have been using the contentStyle prop on the Dialog component. Fixed example looks like this:

//npm install material-ui
import React from 'react'
import Dialog from 'material-ui/Dialog';
import MuiThemeProvider from 'material-ui/styles/MuiThemeProvider';

function App() {
  return(
    <MuiThemeProvider>
      <div>
        <Dialog open={true} contentStyle={{maxWidth: 300}}>
          <h2>nice box</h2>
        </Dialog>
        <h1>React App</h1>
      </div>
    </MuiThemeProvider>
  );
}

export default App

Thanks


问:
Why is my v-for statement not reacting to Vue properly?
I have the following code

```<code><marker-popup v-for="point in pointsArray" :position="point.latlng" :title="point.name" > </marker-popup>
</code>```

with marker-popup defined here:

```<code><template>

    <l-marker :position="position" :title="title" :draggable="false">
      <l-popup :content="text"></l-popup>
    </l-marker>
</template>

<script>
    export default {

        name: 'MarkerPopup',
        props: ['position','title'],

        computed: {
            text: function(){
                return "<b>" + this.title + "</b><br>"
                    + this.position[0] + ", " + this.position[1];
            }
        }
    }
</script>

<style lang="scss">

</style>
</code>```

pointsArray is updated here:

```<code>addPoint: function(data) {

                let alreadyExists = false;
                if(this.pointsDictionary[data.uid]!=undefined){
                    alreadyExists = true;
                }
                this.pointsDictionary[data.uid] = {};

                this.$set(this.pointsDictionary,data.uid,{
                    'name': data.name,
                    'latlng': data.latlng,
                    'uid': data.uid
                });
            //    this.pointsDictionary[data.uid]['name'] = data.name;
              //  this.pointsDictionary[data.uid]['latlng'] = data.latlng;

                //  this.points[data.uid]["marker"] = null;
                if(alreadyExists){
                    console.log("exists");
                    var index = this.pointsArray.find(function(point){
                        return point.uid == data.uid;
                    });
                    //this.$set(this.pointsArray,index,this.pointsDictionary[data.uid]);
                    this.pointsArray.splice(index,1,this.pointsDictionary[data.uid]);
                }
                else {
                      this.pointsArray.push(this.pointsDictionary[data.uid]);
                }

                console.log(JSON.stringify(this.pointsDictionary));
                console.log(JSON.stringify(this.pointsArray2()));

            }
</code>```

However, it does nothing to affect the v-for statement. Whenever the addPoint() method runs, it alters pointsArray in one of two ways

It pushes to the array - this works fine, v-for is perfect

It changes an element in the array according to what the Vue.js docs recommend here. This does not work at all. My console.log statements tell me that the change occurs in pointsArray - Vue does not react to that change despite me trying their recommended approach for changing arrays.

I could, I suppose, remove the element and then just push it but that approach seems clumsy and this should work according to their docs.

答: Turns out that I was doing everything right but the vue-leaflet package doesn't play nicely with Vue 2.0 and refuses to properly react. Switching over to this one solved all the problems.</p>

ContentLicense: CC BY-SA 4.0

Body:
I have the following code

<marker-popup v-for="point in pointsArray" :position="point.latlng" :title="point.name" > </marker-popup>

with marker-popup defined here:

<template>

    <l-marker :position="position" :title="title" :draggable="false">
      <l-popup :content="text"></l-popup>
    </l-marker>
</template>

pointsArray is updated here:

addPoint: function(data) {

                let alreadyExists = false;
                if(this.pointsDictionary[data.uid]!=undefined){
                    alreadyExists = true;
                }
                this.pointsDictionary[data.uid] = {};

                this.$set(this.pointsDictionary,data.uid,{
                    'name': data.name,
                    'latlng': data.latlng,
                    'uid': data.uid
                });
            //    this.pointsDictionary[data.uid]['name'] = data.name;
              //  this.pointsDictionary[data.uid]['latlng'] = data.latlng;

                //  this.points[data.uid]["marker"] = null;
                if(alreadyExists){
                    console.log("exists");
                    var index = this.pointsArray.find(function(point){
                        return point.uid == data.uid;
                    });
                    //this.$set(this.pointsArray,index,this.pointsDictionary[data.uid]);
                    this.pointsArray.splice(index,1,this.pointsDictionary[data.uid]);
                }
                else {
                      this.pointsArray.push(this.pointsDictionary[data.uid]);
                }

                console.log(JSON.stringify(this.pointsDictionary));
                console.log(JSON.stringify(this.pointsArray2()));

            }

However, it does nothing to affect the v-for statement. Whenever the addPoint() method runs, it alters pointsArray in one of two ways

It pushes to the array - this works fine, v-for is perfect

It changes an element in the array according to what the Vue.js docs recommend here. This does not work at all. My console.log statements tell me that the change occurs in pointsArray - Vue does not react to that change despite me trying their recommended approach for changing arrays.

I could, I suppose, remove the element and then just push it but that approach seems clumsy and this should work according to their docs.


问:
How to use variables created multiple times by a loop in Activiti
I am quite new to the activiti-bpm and allready having a problem I cant find any solution on the Internet. So our workflow looks like this:

now the "Untersuchung dokumentieren" task creates two variables each time it is performed.

My first question is now: Does this mechanism create unique variables every time the task "Untersuchung dokumentieren" is performed or does it overried the exisiting variables.

My second question is: How do I access the so created variables (if it does create multiple variables)

Thanks in advance and have a greate day

答:
My first question is now: Does this mechanism create unique variables every time the task "Untersuchung dokumentieren" is performed or does it overried the exisiting variables.

You can use the task local variable.
(ex)TaskService.setVariableLocal method.
https://www.activiti.org/javadocs/org/activiti/engine/TaskService.html#setVariableLocal-java.lang.String-java.lang.String-java.lang.Object-

Because a new task is generated for each loop, the variables of the task are independent for each loop.

My second question is: How do I access the so created variables (if it does create multiple variables)

You can access the task local variable by TaskService.getVariableLocal.
https://www.activiti.org/javadocs/org/activiti/engine/TaskService.html#getVariableLocal-java.lang.String-java.lang.String-


问:
How to use cmd.run in salt-api
```<code>curl -skS "https://xx.xxx.xxx.xxx:8080/run"     -H 'Accept: application/x-yaml'     -H 'Content-type: application/json'     -d '[{
        "client": "local",
        "tgt": "*",
        "fun": "cmd.run",
        "name": "df -h",
        "username": "ravi",
        "password": "teledna",
        "eauth": "pam" }]'
</code>```

I want to run a command through the salt-api. But I am getting an error. Where test.ping is working fine. I think I am missing the params in the body. Can anybody point out the documentation or adjust the curl command above here. Thanks.

答:
You will want to use cmd

```<code>curl -skS https://xxx.xxx.xxx.xxx:8080/run \
    -H 'Accept: application/x-yaml' \
    -H 'Content-type: application/json' \
    -d '[{
        "client": "local",
        "tgt": "*",
        "fun": "cmd.run",
        "kwarg": {
           "cmd": "df -h"
        },
        "username": "ravi",
        "password": "teledna",
        "eauth": "auto"
     }]'
</code>```

You need to use the name from the function in the modules, not the state.

https://docs.saltstack.com/en/latest/ref/modules/all/salt.modules.cmdmod.html#salt.modules.cmdmod.run

Title: How to use cmd.run in salt-api

Body:
curl -skS "https://xx.xxx.xxx.xxx:8080/run"     -H 'Accept: application/x-yaml'     -H 'Content-type: application/json'     -d '[{
        "client": "local",
        "tgt": "*",
        "fun": "cmd.run",
        "name": "df -h",
        "username": "ravi",
        "password": "teledna",
        "eauth": "pam" }]'

I want to run a command through the salt-api. But I am getting an error. Where test.ping is working fine. I think I am missing the params in the body. Can anybody point out the documentation or adjust the curl command above here. Thanks.

Body:
You will want to use cmd

curl -skS https://xxx.xxx.xxx.xxx:8080/run \
    -H 'Accept: application/x-yaml' \
    -H 'Content-type: application/json' \
    -d '[{
        "client": "local",
        "tgt": "*",
        "fun": "cmd.run",
        "kwarg": {
           "cmd": "df -h"
        },
        "username": "ravi",
        "password": "teledna",
        "eauth": "auto"
     }]'

You need to use the name from the function in the modules, not the state.

https://docs.saltstack.com/en/latest/ref/modules/all/salt.modules.cmdmod.html#salt.modules.cmdmod.run


问:
Cordova UWP Desktop - hide back arrow
Using Cordova I'm targeting Windows Desktop (specifically Windows 10). In my deviceready event, I have the following code:

```<code>document.addEventListener( "backbutton", function() {
  window.history.back();
}, false );
</code>```

This hooks up the back arrow in the top left hand corner of the window and works a treat. However, I would like to hide the arrow for the first screen. Is there a way to conditionally hide the back arrow based on the page I'm currently on?

答:
However, I would like to hide the arrow for the first screen. Is there a way to conditionally hide the back arrow based on the page I'm currently on?

On any page of your application, you can call the following API to hide the back button again:

```<code>var Core = Windows.UI.Core;
Core.SystemNavigationManager.getForCurrentView().appViewBackButtonVisibility = Core.AppViewBackButtonVisibility.collapsed;
</code>```

Title: Cordova UWP Desktop - hide back arrow

Body:
Using Cordova I'm targeting Windows Desktop (specifically Windows 10). In my deviceready event, I have the following code:

document.addEventListener( "backbutton", function() {
  window.history.back();
}, false );

This hooks up the back arrow in the top left hand corner of the window and works a treat. However, I would like to hide the arrow for the first screen. Is there a way to conditionally hide the back arrow based on the page I'm currently on?

Body:
However, I would like to hide the arrow for the first screen. Is there a way to conditionally hide the back arrow based on the page I'm currently on?

On any page of your application, you can call the following API to hide the back button again:

var Core = Windows.UI.Core;
Core.SystemNavigationManager.getForCurrentView().appViewBackButtonVisibility = Core.AppViewBackButtonVisibility.collapsed;


问:
What's the difference between the "line" and "path" series types in Plots.jl?
The plots generated using the options seriestype = :line and seriestype = :path look completely identical to me.

答: :line is sorted in x, and :path takes your input and does not do any sorting.


问:
What's the point of throwing an exception?
I'm writing a login class in c#, and I'm trying to be diligent about throwing exceptions for null passwords, insufficiant password characters, etc. The thing that suddenly occured to me was - What do I do with these exception? What/who are they for? Whether I handle the exception or not, the app will still fail at that point. Is the exception for other developers, the customer!? </p>

答: Exceptions usually indicate that the contract of the method has been violated. The client of the method cares about the exception and should handle them appropriately. When the contract is violated, the method itself usually cannot recover and cannot produce meaningful results. The exception indicates that no meaningful results is forthcoming.</p>


问:
AWS AutoScaling Simple Scaling policy
I have one scale in simple policy in my autoscaling group which is based on CPU Utilization.
The policy looks like:

```<code>Execute :
When CPUUtilization < 50 for 5 consecutive periods of 60 seconds
Action :
Remove 10 percent of group
Cooldown time:
600 seconds before allowing another scaling activity
</code>```

Now I would like to add a more aggressive simple policy, saying if CPUUtilization is less than 35 for 5 minutes, remove 20% of the group.

The goal is

When 35 < CPU Utilization < 50 for 5 minutes, remove 10% of the group

When CPU Utilization < 35 for 5 minutes, remove 20% of the group

The problem is I cannot use scaling policy with steps since the cooldown time is not supported which could make my asg scaling in until the min instances.

And if I have both simple policies, they are obviously conflict. I don't really know which policy will be triggered first if it reachs CPUUtilization < 35.

Does anyone have a workaround of this one?
Thanks.

答:
You would certainly need to use Scaling Policy with Steps to be able to specify multiple rules for the scaling policy. While it doesn't allow the specification of a Cooldown period, it should work fine. I recommend you try it and monitor/test the system.

By the way, you have a very aggressive policy. It is not typically a good idea to scale-in based upon only 5 minutes of data. Amazon EC2 is charged in hourly increments, so you might be thrashing (adding and removing instances very quickly), which is not economical. It is typically recommended to scale-out quickly (to respond to user demand) but scale-in slowly (since there's really no rush).

Title: AWS AutoScaling Simple Scaling policy

Body:
I have one scale in simple policy in my autoscaling group which is based on CPU Utilization.
The policy looks like:

Execute :
When CPUUtilization < 50 for 5 consecutive periods of 60 seconds
Action :
Remove 10 percent of group
Cooldown time:
600 seconds before allowing another scaling activity

Now I would like to add a more aggressive simple policy, saying if CPUUtilization is less than 35 for 5 minutes, remove 20% of the group.

The goal is

When 35 < CPU Utilization < 50 for 5 minutes, remove 10% of the group

When CPU Utilization < 35 for 5 minutes, remove 20% of the group

The problem is I cannot use scaling policy with steps since the cooldown time is not supported which could make my asg scaling in until the min instances.

And if I have both simple policies, they are obviously conflict. I don't really know which policy will be triggered first if it reachs CPUUtilization < 35.

Does anyone have a workaround of this one?
Thanks.


问:
Not sure How to fix this issues about FILTER_VALIDATE_EMAIL
Please check my code. I have to 2 fields for validate email

one is

```<code>if ($email == NULL) {
            $error['email'] = "email is missing";
        }
</code>```

another is

```<code>if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
            $error['emailfilter'] = "email is Invalid";
    }
</code>```

But my Problem is when email field is blank/empty. I found those 2 warring is show. "email is missing" &  "email is Invalid"; I want only one warring will show. Such as if email filed is blank/empty. It will show only "email is missing" not show me "email is Invalid" and when email is not valid It will show "email is Invalid". Below is my full code.

```<code><?php
    if (isset($_POST['contact'])) {

        $warning = array();
        $firstname = $_POST['firstname'];
        $lastname = $_POST['lastname'];
        $email = $_POST['email'];
        $msg = $_POST['message'];
        $to = "asifurrahaman124@gmail.com";
        $sub = "you got a msg";
        $headers = "from: $email";

        if ($firstname == NULL) {
            $error['fname'] = "firstname is missing";
        }
        if($lastname == NULL){
            $error['lname'] = "Last name is missing";
        }
        if ($email == NULL) {
            $error['email'] = "email is missing";
        }

        if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
            $error['emailfilter'] = "email is Invalid";
        }

        if ($msg == NULL) {
            $error['msg'] = "message is required";
        }
        if (count( $error ) == 0) {
            mail($to, $sub, $msg, $headers);

            $success = "Message Submited";
        }
    }

?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>conatact</title>
    <link rel="stylesheet" href="style.css">
</head>
<body>
    <form action="" method="POST">
        <input type="text" name="firstname" Placeholder="First Name"><br />
        <p class="error"><?php if (isset($error['fname'])) {
            echo $error['fname'];
        }?></p>
        <input type="text" name="lastname" Placeholder="Last Name"><br />
        <p class="error"><?php if (isset($error['lname'])) {
            echo $error['lname'];
        }?></p>
        <input type="email" name="email" Placeholder="Email"><br />
        <p class="error"><?php if (isset($error['email'])) {
            echo $error['email'];
        }?></p>
        <p class="error"><?php if (isset($error['emailfilter'])) {
            echo $error['emailfilter'];
        }?></p>
        <textarea name="message"  cols="30" rows="10"></textarea><br />
        <p class="error"><?php if (isset($error['msg'])) {
            echo $error['msg'];
        }?></p>

        <input type="password" name="password" Placeholder="Password"><br />
        <input type="submit" value="send" name="contact">

    </form>
    <h2 class="error"><?php if (isset($success)) {
            echo $success;
        }?></h2>
</body>
</html>
</code>```

答:
You want to use elseif for this, it will only trigger if the first condition isn't matched.

```<code>if ($email == NULL) {
    $error['email'] = "email is missing";
} elseif (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
    $error['emailfilter'] = "email is Invalid";
}
</code>```

This will check the first condition, do they have an email, if not it'll populate $error['email'], if the email has a value then it'll perform the filter_var on the email to check it's validity.

Body:
Please check my code. I have to 2 fields for validate email

one is

if ($email == NULL) {
            $error['email'] = "email is missing";
        }

another is

if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
            $error['emailfilter'] = "email is Invalid";
    }

But my Problem is when email field is blank/empty. I found those 2 warring is show. "email is missing" &  "email is Invalid"; I want only one warring will show. Such as if email filed is blank/empty. It will show only "email is missing" not show me "email is Invalid" and when email is not valid It will show "email is Invalid". Below is my full code.

<?php
    if (isset($_POST['contact'])) {

        $warning = array();
        $firstname = $_POST['firstname'];
        $lastname = $_POST['lastname'];
        $email = $_POST['email'];
        $msg = $_POST['message'];
        $to = "asifurrahaman124@gmail.com";
        $sub = "you got a msg";
        $headers = "from: $email";

        if ($firstname == NULL) {
            $error['fname'] = "firstname is missing";
        }
        if($lastname == NULL){
            $error['lname'] = "Last name is missing";
        }
        if ($email == NULL) {
            $error['email'] = "email is missing";
        }

        if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
            $error['emailfilter'] = "email is Invalid";
        }

        if ($msg == NULL) {
            $error['msg'] = "message is required";
        }
        if (count( $error ) == 0) {
            mail($to, $sub, $msg, $headers);

            $success = "Message Submited";
        }
    }

?>

<!DOCTYPE html>

    <meta charset="UTF-8">
    <title>conatact</title>
    <link rel="stylesheet" href="style.css">

    <form action="" method="POST">
        <input type="text" name="firstname" Placeholder="First Name">

<?php if (isset($error['fname'])) {
            echo $error['fname'];
        }?>

        <input type="text" name="lastname" Placeholder="Last Name">

<?php if (isset($error['lname'])) {
            echo $error['lname'];
        }?>

        <input type="email" name="email" Placeholder="Email">

<?php if (isset($error['email'])) {
            echo $error['email'];
        }?>

<?php if (isset($error['emailfilter'])) {
            echo $error['emailfilter'];
        }?>

        <textarea name="message"  cols="30" rows="10"></textarea>

<?php if (isset($error['msg'])) {
            echo $error['msg'];
        }?>

        <input type="password" name="password" Placeholder="Password">

        <input type="submit" value="send" name="contact">

    </form>

<?php if (isset($success)) {
            echo $success;
        }?>

Body:
You want to use elseif for this, it will only trigger if the first condition isn't matched.

if ($email == NULL) {
    $error['email'] = "email is missing";
} elseif (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
    $error['emailfilter'] = "email is Invalid";
}

This will check the first condition, do they have an email, if not it'll populate $error['email'], if the email has a value then it'll perform the filter_var on the email to check it's validity.


问:
What's the Swift equivalent of Objective-C's "#ifdef __IPHONE_11_0"?
I want to use Xcode 9 to add iOS 11 code to my project while keeping the option to compile the project with Xcode 8 which only supports iOS 10.

In Objective-C I can do this by using a preprocessor directive to check if __IPHONE_11_0 is defined. Which will hide the code if I'm compiling with a Base SDK earlier than iOS 11. Like this:

```<code>#ifdef __IPHONE_11_0
    if (@available(iOS 11.0, *)) {
        self.navigationController.navigationBar.prefersLargeTitles = YES;
    }
#endif
</code>```

Is there a way to do that in Swift?

if #available(iOS 11.0, *) doesn't work because that's a runtime check.

答:
The iOS 11 SDK comes with Swift 3.2 (or Swift 4), so you can use a Swift version check to accomplish the same thing:</p>

```<code>#if swift(>=3.2)
    if #available(iOS 11.0, *) {
        …
    }
#endif
</code>```

Body:
I want to use Xcode 9 to add iOS 11 code to my project while keeping the option to compile the project with Xcode 8 which only supports iOS 10.

In Objective-C I can do this by using a preprocessor directive to check if __IPHONE_11_0 is defined. Which will hide the code if I'm compiling with a Base SDK earlier than iOS 11. Like this:

#ifdef __IPHONE_11_0
    if (@available(iOS 11.0, *)) {
        self.navigationController.navigationBar.prefersLargeTitles = YES;
    }
#endif

Is there a way to do that in Swift?

if #available(iOS 11.0, *) doesn't work because that's a runtime check.

Body:
The iOS 11 SDK comes with Swift 3.2 (or Swift 4), so you can use a Swift version check to accomplish the same thing:

#if swift(>=3.2)
    if #available(iOS 11.0, *) {
        …
    }
#endif


问:
Streaming mode vs block mode
I can't figure out what exactly is the streaming mode offered by modern compression/decompression algorithms (eg ZStandard or LZ4) and how I can exploit it.

As an example, suppose I have 4x16KB file. I can (individually) compress each file and obtain 4xDifferentCompressedLength files. However I could compress all 4 files together (sending them sequentially, right?) using streaming mode and obtain 1xCompressedLength and expect the compression ratio to be better.

Can I decompress (say) only the 3rd file without decompressing all the previous files? Do streaming mode introduce dependency between the files I appended?

答:
Yes, streaming introduce dependency between files.
In your example, decoding file3 would require to decode first file1 then file2.

Note also that data will appear as appended, with no specific marker between files. So one would need a way to know where each file starts and ends if it's important. Sometimes it's implicit (ex : fixed 16KB size), sometimes it can be deducted from data itself (specific end-of-mark), sometimes it needs additional metadata. It all depends on the application.

You are correct that the compression ratio of C(4xFiles) is expected to be better than 4xC(File), especially if the 4 files are somewhat related (for example if they all are text files).

Title: Streaming mode vs block mode


问:
How to run gulp tasks with different parameters depending on the argument on terminal
I have a shared SCSS source files which must be compiled and copied into different project folders.

I have a build task which calls 2 tasks, clean and styles(to compile/minify and copy to build folder).

My source SCSS files are shared between all websites however the destination folders are different.

I would like to be able to run: build websiteA and then clean build folder inside websiteA and compile files from a shared folder and copied to build folder inside Website A.

```<code>var assetsDir = '_Assets';

var buildStyleWebsiteA = 'WebsiteA/Assets/build';
var buildStyleWebsiteB = 'WebsiteB/Assets/build';

gulp.task('clean-websiteA', function (cb) {
    return del([buildStyleWebsiteA ], cb);
});

gulp.task('styles-websiteA', ['clean-websiteA'], function () {
    return gulp.src(assetsDir + '/**/*.scss')
        .pipe(sourcemaps.init())
        .pipe(sass().on('error', sass.logError))
        .pipe(autoprefixer())
        .pipe(gulp.dest(buildStyleWebsiteA + '/css'))
        .pipe(concat('styles.css'))
        .pipe(cleanCss())
        .pipe(sourcemaps.write())
        .pipe(rename({ suffix: '.min' }))
        .pipe(gulp.dest(buildStyleWebsiteA + '/min/'))
        .pipe(liveReload());
});

gulp.task('build-websiteA', ['styles']);
</code>```

PS: I also have same tasks for websiteB (build-websiteB, clean-websiteB, and style-websiteB).
So I ended up with repetitive code and I know there must be a better way.

What I would like to have is provide website name as a parameter for gulp command and then it runs clean and style using correct folder related to that website.

How can I refactor my code to achieve that?

Thanks

答:
I would use environment variables to accomplish this rather than arguments.

```<code>var buildDir = process.env.BUILD_DIR + '/Assets/build';
</code>```

Then you would call it as:

```<code>BUILD_DIR=websiteA gulp build
</code>```

Body:
I have a shared SCSS source files which must be compiled and copied into different project folders.

I have a build task which calls 2 tasks, clean and styles(to compile/minify and copy to build folder).

My source SCSS files are shared between all websites however the destination folders are different.

I would like to be able to run: build websiteA and then clean build folder inside websiteA and compile files from a shared folder and copied to build folder inside Website A.

var assetsDir = '_Assets';

var buildStyleWebsiteA = 'WebsiteA/Assets/build';
var buildStyleWebsiteB = 'WebsiteB/Assets/build';

gulp.task('clean-websiteA', function (cb) {
    return del([buildStyleWebsiteA ], cb);
});

gulp.task('styles-websiteA', ['clean-websiteA'], function () {
    return gulp.src(assetsDir + '/**/*.scss')
        .pipe(sourcemaps.init())
        .pipe(sass().on('error', sass.logError))
        .pipe(autoprefixer())
        .pipe(gulp.dest(buildStyleWebsiteA + '/css'))
        .pipe(concat('styles.css'))
        .pipe(cleanCss())
        .pipe(sourcemaps.write())
        .pipe(rename({ suffix: '.min' }))
        .pipe(gulp.dest(buildStyleWebsiteA + '/min/'))
        .pipe(liveReload());
});

gulp.task('build-websiteA', ['styles']);

PS: I also have same tasks for websiteB (build-websiteB, clean-websiteB, and style-websiteB).
So I ended up with repetitive code and I know there must be a better way.

What I would like to have is provide website name as a parameter for gulp command and then it runs clean and style using correct folder related to that website.

How can I refactor my code to achieve that?

Thanks

Body:
I would use environment variables to accomplish this rather than arguments.

var buildDir = process.env.BUILD_DIR + '/Assets/build';

Then you would call it as:

BUILD_DIR=websiteA gulp build


问:
Why is it possible to modify a returned value when the return type is const?
I was under the impression that by declaring a return type const, you could prevent the data structure from being modified.  However, I tested this and I can modify the data structures.  Why is that?

For example, the following code prints 1 2 3 4 5 6 when compiled with --std=c++11:

```<code>#include <iostream>
#include <set>

using namespace std;
const set<int> f(void) {
    set<int> s = {1, 2, 3, 4, 5};
    return s;
}
int main(void) {
    set<int> s = f();
    s.insert(6);

    for (auto elem: s) {
        cout << elem << " ";
    }
    return 0;
}
</code>```

答:
Because s is a different object which constructed from the returned value. It has nothing to do with the returned object, and it's a non-const object itself.

The const qualifier for the return value means you can't modify on it directly, like

```<code>f().insert(6); // fail
</code>```

Body:
I was under the impression that by declaring a return type const, you could prevent the data structure from being modified.  However, I tested this and I can modify the data structures.  Why is that?

For example, the following code prints 1 2 3 4 5 6 when compiled with --std=c++11:

#include <iostream>
#include <set>

using namespace std;
const set<int> f(void) {
    set<int> s = {1, 2, 3, 4, 5};
    return s;
}
int main(void) {
    set<int> s = f();
    s.insert(6);

    for (auto elem: s) {
        cout << elem << " ";
    }
    return 0;
}

Body:
Because s is a different object which constructed from the returned value. It has nothing to do with the returned object, and it's a non-const object itself.

The const qualifier for the return value means you can't modify on it directly, like

f().insert(6); // fail


问:
Winform TabControl style
I'm once again turning to you since I can't find an answer anywhere else. I have a TabControl, but I want to get rid of the ugly orange bar on top of the selected tabs. I would also like to make the tab text BOLD when selected and NORMAL when not.

Is there any easy way to achieve that goal ? I don't want to use the Appearance Buttons or Flat Buttons.

Thanks for your help !

答: This appearance is controlled by the Visual Styles theme selected in your operating system.  In general, users do not appreciate any program that ignores their theme settings, especially when they paid money for a custom one.  But you can get what you want, you'll have to set the DrawMode property to OwnerDrawFixed and implement a handler for the DrawItem event.  There's a good example to get you started in the MSDN Library article for this event.  Just change the font assignment in that sample code.

Title: Winform TabControl style


问:
Serverless is failing when trying to initialize google cloud apis in node js
I am using google datastore for nodejs6.10 and it is working fine with serverless offline. But when i deployed and tried to use the functions urls.

I am getting following error:

```<code>module initialization error: Error
at Error (native)
at Object.Module._extensions..node (module.js:597:18)
at Module.load (module.js:487:32)
at tryModuleLoad (module.js:446:12)
at Function.Module._load (module.js:438:3)
at Module.require (module.js:497:17)
at require (internal/module.js:20:19)
at Object.<anonymous>
(/var/task/node_modules/grpc/src/node/src/grpc_extension.js:38:15)
at Module._compile (module.js:570:32)
at Object.Module._extensions..js (module.js:579:10)
</code>```

I have tried installing npm packages and uploaded them but of no use.

Below is snapshot of my serverless provider section:

```<code>provider:
 name: aws
 runtime: nodejs6.10
 environment:
   Environment: ${env:Environment}
 region: ${env:AWS_REGION}
</code>```

This is how i am trying to use datastore:

```<code>let datastore = require('@google-cloud/datastore')({
projectId: configFile[process.env.Environment].project,
keyFilename: configFile[process.env.Environment].keyfile
});
</code>```

Can someone help me with this.

答:
Below code is what I see innode_modules/grpc/src/node/src/grpc_extension.js

```<code>var binary = require('node-pre-gyp/lib/pre-binding');
var path = require('path');
var binding_path =
    binary.find(path.resolve(path.join(__dirname, '../../../package.json')));
var binding = require(binding_path);
</code>```

Had a look at the package.json for grpc and found few paths with local references. Not sure if this is the issue, didn't try with corrections. will try and update

Body:
I am using google datastore for nodejs6.10 and it is working fine with serverless offline. But when i deployed and tried to use the functions urls.

I am getting following error:

module initialization error: Error
at Error (native)
at Object.Module._extensions..node (module.js:597:18)
at Module.load (module.js:487:32)
at tryModuleLoad (module.js:446:12)
at Function.Module._load (module.js:438:3)
at Module.require (module.js:497:17)
at require (internal/module.js:20:19)
at Object.<anonymous>
(/var/task/node_modules/grpc/src/node/src/grpc_extension.js:38:15)
at Module._compile (module.js:570:32)
at Object.Module._extensions..js (module.js:579:10)

I have tried installing npm packages and uploaded them but of no use.

Below is snapshot of my serverless provider section:

provider:
 name: aws
 runtime: nodejs6.10
 environment:
   Environment: ${env:Environment}
 region: ${env:AWS_REGION}

This is how i am trying to use datastore:

let datastore = require('@google-cloud/datastore')({
projectId: configFile[process.env.Environment].project,
keyFilename: configFile[process.env.Environment].keyfile
});

Can someone help me with this.

Body:
Below code is what I see innode_modules/grpc/src/node/src/grpc_extension.js

var binary = require('node-pre-gyp/lib/pre-binding');
var path = require('path');
var binding_path =
    binary.find(path.resolve(path.join(__dirname, '../../../package.json')));
var binding = require(binding_path);

Had a look at the package.json for grpc and found few paths with local references. Not sure if this is the issue, didn't try with corrections. will try and update


问:
Rails 5 API: Globally Set config.time_zone to UTC
Rails 5.0.2 API only application running on Ruby 2.4.1.

Set time_zone in config to "UTC"

Set ActiveRecord default_timezone to :utc

Application restarted multiple times after the config change

application.rb

```<code>config.time_zone = "UTC"
config.active_record.default_timezone = :utc
</code>```

Model query

```<code>weight_entry = @current_user.weight_entries
                            .where(taken_on: Time.now.beginning_of_day..Time.now.end_of_day)
                            .first
</code>```

Executes the following query

```<code>WeightEntry Load (3.2ms)  SELECT  "weight_entries".*
FROM "weight_entries" WHERE "weight_entries"."user_id" = $1
AND ("weight_entries"."taken_on" BETWEEN $2 AND $3)
ORDER BY "weight_entries"."id"
ASC LIMIT $4  [["user_id", 3],
["taken_on", 2017-06-07 06:00:00 UTC],
["taken_on", 2017-06-08 05:59:59 UTC], ["LIMIT", 1]]
</code>```

As you can see, despite setting UTC globally, the ActiveRecord query against the database is still using an offset (6 hours) in the time component:

```<code>["taken_on", 2017-06-07 06:00:00 UTC],
["taken_on", 2017-06-08 05:59:59 UTC], ["LIMIT", 1]]
</code>```

I expect, with UTC being the default across the application, that the timestamps would look more like this:

```<code>["taken_on", 2017-06-07 00:00:00 UTC],
["taken_on", 2017-06-08 23:59:59 UTC], ["LIMIT", 1]]
</code>```

If I change the model query to this (inserting utc manually):

```<code>weight_entry = @current_user.weight_entries
                        .where(taken_on: Time.now.utc.beginning_of_day..Time.now.utc.end_of_day)
                        .first
</code>```

I get the expected results:

```<code>["taken_on", 2017-06-07 00:00:00 UTC],
["taken_on", 2017-06-08 23:59:59 UTC], ["LIMIT", 1]]
</code>```

Do I really need to insert .utc every time I use a time element when inserting and querying the database via Rails, even though I have set UTC as the default timezone?

What am I missing here?

答:
you should use Time.zone.now instead of Time.now or Time.now.utc

Good explanation here

https://rails-bestpractices.com/posts/2014/10/22/use-time-zone-now-instead-of-time-now/

http://danilenko.org/2012/7/6/rails_timezones/

Body:
Rails 5.0.2 API only application running on Ruby 2.4.1.

Set time_zone in config to "UTC"

Set ActiveRecord default_timezone to :utc

Application restarted multiple times after the config change

application.rb

config.time_zone = "UTC"
config.active_record.default_timezone = :utc

Model query

weight_entry = @current_user.weight_entries
                            .where(taken_on: Time.now.beginning_of_day..Time.now.end_of_day)
                            .first

Executes the following query

WeightEntry Load (3.2ms)  SELECT  "weight_entries".*
FROM "weight_entries" WHERE "weight_entries"."user_id" = $1
AND ("weight_entries"."taken_on" BETWEEN $2 AND $3)
ORDER BY "weight_entries"."id"
ASC LIMIT $4  [["user_id", 3],
["taken_on", 2017-06-07 06:00:00 UTC],
["taken_on", 2017-06-08 05:59:59 UTC], ["LIMIT", 1]]

As you can see, despite setting UTC globally, the ActiveRecord query against the database is still using an offset (6 hours) in the time component:

["taken_on", 2017-06-07 06:00:00 UTC],
["taken_on", 2017-06-08 05:59:59 UTC], ["LIMIT", 1]]

I expect, with UTC being the default across the application, that the timestamps would look more like this:

["taken_on", 2017-06-07 00:00:00 UTC],
["taken_on", 2017-06-08 23:59:59 UTC], ["LIMIT", 1]]

If I change the model query to this (inserting utc manually):

weight_entry = @current_user.weight_entries
                        .where(taken_on: Time.now.utc.beginning_of_day..Time.now.utc.end_of_day)
                        .first

I get the expected results:

["taken_on", 2017-06-07 00:00:00 UTC],
["taken_on", 2017-06-08 23:59:59 UTC], ["LIMIT", 1]]

Do I really need to insert .utc every time I use a time element when inserting and querying the database via Rails, even though I have set UTC as the default timezone?

What am I missing here?


问:
How to save a Python interactive session?
I find myself frequently using Python's interpreter to work with databases, files, etc -- basically a lot of manual formatting of semi-structured data.  I don't properly save and clean up the useful bits as often as I would like.  Is there a way to save my input into the shell (db connections, variable assignments, little for loops and bits of logic) -- some history of the interactive session?  If I use something like script I get too much stdout noise.  I don't really need to pickle all the objects -- though if there is a solution that does that, it would be OK.  Ideally I would just be left with a script that ran as the one I created interactively, and I could just delete the bits I didn't need.  Is there a package that does this, or a DIY approach?

答:
I'd like to suggest another way to maintain python session through tmux on linux. you run tmux, attach your self to the session you opened (if not attached after opening it directly). execute python and do whatever you are doing on it. then detach from session. detaching from a tmux session does not close the session. the session remains open.

pros of this method:
you can attach to this session from any other device (in case you can ssh your pc)

cons of this method:
this method does not relinquish the resources used by the opened python session until you actually exist the python interpreter.


问:
Using a FlatList with scrollToEnd
I have two issues when using a FlatList (that both work with a ListView).

I have a list that is displayed via a display property for each item and then checked in my FlatList like so:

```<code><FlatList
  ref='flatList'
  data={this.state.dataSource}
  enableEmptySections
  renderItem={({item}) => item.display && <Text>{item.text}</Text>} />
</code>```

When I change the display property, it doesn't display however. This worked fine in the ListView setup.

My second problem is that scrollToEnd is firing an undefined error on "this._listref" which is within the scrollToEnd function. I pass no parameters to it.

```<code>setTimeout(this.refs.flatList.scrollToEnd, 0)
</code>```

My questions are, how do I update the data in my array for the list so it changes in the list, and the second question is how do I fix the scrollToEnd error?

Update 1: (data removed, not needed anymore)

Update 2: Problem ONE solved, the list needs "extraData" comparison to see if it updates. The fixed edition:

```<code><FlatList
  ref='flatList'
  data={this.state.dataSource}
  extraData={this.state}
  enableEmptySections
  renderItem={({item}) => item.display && <Text>{item.text}</Text>} />
</code>```

It's a bit convoluted, but I believe extraData acts as a comparison to see if anything in that data set updates. If so, re-render. That problem is solved.

"undefined is not an object (evaluating 'this._listRef')" still not fixed

Update 3: Scroll function works IF taken outside the setTimeoutfunction

Update 4:

Setting the initial data array

```<code>  this.state = {
    dataSource: pageService(state.params.page),
    cursor: 0
  }
</code>```

Setting display as true:

```<code>  renderNextModule() {
    let newCursor = this.state.cursor
    if (newCursor < this.state.dataSource.length-1) {

        newCursor++
        let newSource = this.state.dataSource
        newSource[newCursor].display = true
        this.setState({
            dataSource: newSource,
            cursor: newCursor
        })
    }
  }
</code>```

答:
this._listRef is undefined because setTimeout calls the function and sets its context (this) to null.

As a workaround, you can actually use a wrapper function (here with ES6 syntax) :

```<code>setTimeout(() => this.refs.flatList.scrollToEnd(), 0)
</code>```

Regarding your 1st problem, I don't think you're solving it the right way.
You were right that it uses a shallow comparison, but you might not need the extraData prop.

Are you mutating your array directly? How are you updating the item.display property?

For your 1st problem,

Replace this line

```<code>let newSource = this.state.dataSource
</code>```

By this

```<code>let newSource = this.state.dataSource.slice()
</code>```

In JavaScript, arrays are copied by reference, which means that you were not cloning the array but mutating it ; and as FlatList is efficient (and this is for every PureComponent), when you want to re-render it (by setting the state like you did), it does a === comparison on its old and new props to see if anything changed.

As you were mutating the old array, 'oldArray === newArray', so it was deciding to not update again.

This was a bit concise and fast but you can read more about why you need to create a new array with .slice() here. This is true for arrays and objects in JavaScript.

Title: Using a FlatList with scrollToEnd

Body:
I have two issues when using a FlatList (that both work with a ListView).

I have a list that is displayed via a display property for each item and then checked in my FlatList like so:

<FlatList
  ref='flatList'
  data={this.state.dataSource}
  enableEmptySections
  renderItem={({item}) => item.display && <Text>{item.text}</Text>} />

When I change the display property, it doesn't display however. This worked fine in the ListView setup.

My second problem is that scrollToEnd is firing an undefined error on "this._listref" which is within the scrollToEnd function. I pass no parameters to it.

setTimeout(this.refs.flatList.scrollToEnd, 0)

My questions are, how do I update the data in my array for the list so it changes in the list, and the second question is how do I fix the scrollToEnd error?

Update 1: (data removed, not needed anymore)

Update 2: Problem ONE solved, the list needs "extraData" comparison to see if it updates. The fixed edition:

<FlatList
  ref='flatList'
  data={this.state.dataSource}
  extraData={this.state}
  enableEmptySections
  renderItem={({item}) => item.display && <Text>{item.text}</Text>} />

It's a bit convoluted, but I believe extraData acts as a comparison to see if anything in that data set updates. If so, re-render. That problem is solved.

"undefined is not an object (evaluating 'this._listRef')" still not fixed

Update 3: Scroll function works IF taken outside the setTimeoutfunction

Update 4:

Setting the initial data array

  this.state = {
    dataSource: pageService(state.params.page),
    cursor: 0
  }

Setting display as true:

  renderNextModule() {
    let newCursor = this.state.cursor
    if (newCursor < this.state.dataSource.length-1) {

        newCursor++
        let newSource = this.state.dataSource
        newSource[newCursor].display = true
        this.setState({
            dataSource: newSource,
            cursor: newCursor
        })
    }
  }

Body:
this._listRef is undefined because setTimeout calls the function and sets its context (this) to null.

As a workaround, you can actually use a wrapper function (here with ES6 syntax) :

setTimeout(() => this.refs.flatList.scrollToEnd(), 0)

Regarding your 1st problem, I don't think you're solving it the right way.
You were right that it uses a shallow comparison, but you might not need the extraData prop.

Are you mutating your array directly? How are you updating the item.display property?

For your 1st problem,

Replace this line

let newSource = this.state.dataSource

By this

let newSource = this.state.dataSource.slice()

In JavaScript, arrays are copied by reference, which means that you were not cloning the array but mutating it ; and as FlatList is efficient (and this is for every PureComponent), when you want to re-render it (by setting the state like you did), it does a === comparison on its old and new props to see if anything changed.

As you were mutating the old array, 'oldArray === newArray', so it was deciding to not update again.

This was a bit concise and fast but you can read more about why you need to create a new array with .slice() here. This is true for arrays and objects in JavaScript.


问:
Should I use sync or blocking channels?
I have several go routines and I use unbuffered channels as sync mechanism.

I'm wondering if there is anything wrong in this(e.g. compared with a WaitGroup implementation). A known "drawback" that I'm aware of is that two go routines may stay blocked until the 3rd(last) one completes because the channel is not buffered but I don't know the internals/what this really means.

```<code>func main() {
    chan1, chan2, chan3 := make(chan bool), make(chan bool), make(chan bool)
    go fn(chan1)
    go fn(chan2)
    go fn(chan3)
    res1, res2, res3 := <-chan1, <-chan2, <-chan3
}
</code>```

答:
Channels and WaitGroups are both available for you to use as appropriate. For a given problem, your solution could be solved using channels or WaitGroup or even a combination of both.

From what I understand, channels are more appropriate when your goroutines need to communicate with each other (as in they are not independent). WaitGroup is usually used when your goroutines are independent of each other.

Personally, I like WaitGroup because it is more readable and simpler to use. However, just like channels, I do not like that we need to pass the reference to the goroutine because that would mean that the concurrency logic would be mixed with your business logic.

So I came up with this generic function to solve this problem for me:

```<code>// Parallelize parallelizes the function calls
func Parallelize(functions ...func()) {
    var waitGroup sync.WaitGroup
    waitGroup.Add(len(functions))

    defer waitGroup.Wait()

    for _, function := range functions {
        go func(copy func()) {
            defer waitGroup.Done()
            copy()
        }(function)
    }
}
</code>```

Here is an example:

```<code>func1 := func() {
        for char := 'a'; char < 'a' + 3; char++ {
            fmt.Printf("%c ", char)
        }
}

func2 := func() {
        for number := 1; number < 4; number++ {
            fmt.Printf("%d ", number)
        }
}

Parallelize(func1, func2)  // a 1 b 2 c 3
</code>```

If you would like to use it, you can find it here https://github.com/shomali11/util

Title: Should I use sync or blocking channels?

Body:
I have several go routines and I use unbuffered channels as sync mechanism.

I'm wondering if there is anything wrong in this(e.g. compared with a WaitGroup implementation). A known "drawback" that I'm aware of is that two go routines may stay blocked until the 3rd(last) one completes because the channel is not buffered but I don't know the internals/what this really means.

func main() {
    chan1, chan2, chan3 := make(chan bool), make(chan bool), make(chan bool)
    go fn(chan1)
    go fn(chan2)
    go fn(chan3)
    res1, res2, res3 := <-chan1, <-chan2, <-chan3
}

Body:
Channels and WaitGroups are both available for you to use as appropriate. For a given problem, your solution could be solved using channels or WaitGroup or even a combination of both.

From what I understand, channels are more appropriate when your goroutines need to communicate with each other (as in they are not independent). WaitGroup is usually used when your goroutines are independent of each other.

Personally, I like WaitGroup because it is more readable and simpler to use. However, just like channels, I do not like that we need to pass the reference to the goroutine because that would mean that the concurrency logic would be mixed with your business logic.

So I came up with this generic function to solve this problem for me:

// Parallelize parallelizes the function calls
func Parallelize(functions ...func()) {
    var waitGroup sync.WaitGroup
    waitGroup.Add(len(functions))

    defer waitGroup.Wait()

    for _, function := range functions {
        go func(copy func()) {
            defer waitGroup.Done()
            copy()
        }(function)
    }
}

Here is an example:

func1 := func() {
        for char := 'a'; char < 'a' + 3; char++ {
            fmt.Printf("%c ", char)
        }
}

func2 := func() {
        for number := 1; number < 4; number++ {
            fmt.Printf("%d ", number)
        }
}

Parallelize(func1, func2)  // a 1 b 2 c 3

If you would like to use it, you can find it here https://github.com/shomali11/util