问:
how to programmatically handle null output within a bash function with some custom formatting
I have a bash function that uses a list of IPs in result and for each IP, its used as part of a database query to return a string.  What I need help with now is how to handle the output, if the IP does NOT return data (see the testoutput)

The code:

```<code>set -x
demo() {
        local result='10.8.3.34
        10.8.2.191
        10.8.3.54
        10.8.4.150
        10.8.3.249
        10.8.2.197'
        read -d '' -a servers <<< $result
        echo "Checking ${#servers[@]} servers";
        for i in ${servers[@]};
        do
          local host='10.1.2.130'
          local db='myapplication_cluster_state'
          _mongo=$(which mongo);
          echo -n "$i:";
          local exp="db.myapplicationcluster_servers.find(
          {\"node_host\":\"${i}\",\"node_type\":\"APP_PROCESS\",\"region\":\"us-east-1\",\"status\":\"ACTIVE\"},{\"partition_range_start\":1,\"partition_range_end\":1, _id:0}).pretty();";
          ${_mongo} ${host}/${db} --eval "$exp" | grep -o -e "{[^}]*}";
        done
}
set +x
demo
</code>```

My testoutput:

```<code>+ set +x
Checking 6 servers
10.8.3.34:{ "partition_range_start" : 31, "partition_range_end" : 31 }
10.8.2.191:{ "partition_range_start" : 79, "partition_range_end" : 79 }
10.8.3.54:{ "partition_range_start" : 62, "partition_range_end" : 62 }
10.8.4.150:{ "partition_range_start" : 22, "partition_range_end" : 22 }
10.8.3.249:10.8.2.197:{ "partition_range_start" : 16, "partition_range_end" : 16 }
</code>```

Note: 10.8.3.249 has NO data, so the next string is appended as 10.8.3.249:10.8.2.197:{ "partition_range_start"

I would like the output format to be this:

```<code>+ set +x
Checking 6 servers
10.8.3.34:{ "partition_range_start" : 31, "partition_range_end" : 31 }
10.8.2.191:{ "partition_range_start" : 79, "partition_range_end" : 79 }
10.8.3.54:{ "partition_range_start" : 62, "partition_range_end" : 62 }
10.8.4.150:{ "partition_range_start" : 22, "partition_range_end" : 22 }
10.8.3.249:
10.8.2.197:{ "partition_range_start" : 16, "partition_range_end" : 16 }
</code>```

OR  If no data for the IP that is read, put some value, i.e. EMPTY

```<code>10.8.3.34:{ "partition_range_start" : 31, "partition_range_end" : 31 }
10.8.2.191:{ "partition_range_start" : 79, "partition_range_end" : 79 }
10.8.3.54:{ "partition_range_start" : 62, "partition_range_end" : 62 }
10.8.4.150:{ "partition_range_start" : 22, "partition_range_end" : 22 }
10.8.3.249: EMPTY
10.8.2.197:{ "partition_range_start" : 16, "partition_range_end" : 16 }
</code>```

How can I achieve this output? Thanks.

答:
Change your for loop to…

```<code>for i in ${servers[@]}
do
  local host='10.1.2.130'
  local db='myapplication_cluster_state'
  _mongo=$(which mongo)
  local exp="db.myapplicationcluster_servers.find({\"node_host\":\"${i}\",\"node_type\":\"APP_PROCESS\",\"region\":\"us-east-1\",\"status\":\"ACTIVE\"},{\"partition_range_start\":1,\"partition_range_end\":1, _id:0}).pretty();"

  # Store output of mongo command in variable
  output=$(${_mongo} ${host}/${db} --eval "$exp" | grep -o -e "{[^}]*}")

  # Print {} if output variable is empty
  echo "${i}:${output:-{}}"
done
</code>```

To switch {} with nothing, use echo "${i}:${output:-}"

To switch {} with EMPTY, use echo "${i}:${output:- EMPTY}"

Sorting

To sort on the value of partition_range_start, pipe the output of the demo function to the sort command…

```<code>demo | sort -n -k4
</code>```

This says "sort the output of demo numerically (-n) on field 4 (-k4)". Fields are, by default, characters separated by whitespace.

This is what sort sees for the line 10.8.3.34:{ "partition_range_start" : 31, "partition_range_end" : 31 }...

field 1 10.8.3.34:{

field 2 "partition_range_start"

field 3 :

field 4 31,

field 5 "partition_range_end"

field 6 :

field 7 31

field 8 }

Body:
I have a bash function that uses a list of IPs in result and for each IP, its used as part of a database query to return a string.  What I need help with now is how to handle the output, if the IP does NOT return data (see the testoutput)

The code:

set -x
demo() {
        local result='10.8.3.34
        10.8.2.191
        10.8.3.54
        10.8.4.150
        10.8.3.249
        10.8.2.197'
        read -d '' -a servers <<< $result
        echo "Checking ${#servers[@]} servers";
        for i in ${servers[@]};
        do
          local host='10.1.2.130'
          local db='myapplication_cluster_state'
          _mongo=$(which mongo);
          echo -n "$i:";
          local exp="db.myapplicationcluster_servers.find(
          {\"node_host\":\"${i}\",\"node_type\":\"APP_PROCESS\",\"region\":\"us-east-1\",\"status\":\"ACTIVE\"},{\"partition_range_start\":1,\"partition_range_end\":1, _id:0}).pretty();";
          ${_mongo} ${host}/${db} --eval "$exp" | grep -o -e "{[^}]*}";
        done
}
set +x
demo

My testoutput:

+ set +x
Checking 6 servers
10.8.3.34:{ "partition_range_start" : 31, "partition_range_end" : 31 }
10.8.2.191:{ "partition_range_start" : 79, "partition_range_end" : 79 }
10.8.3.54:{ "partition_range_start" : 62, "partition_range_end" : 62 }
10.8.4.150:{ "partition_range_start" : 22, "partition_range_end" : 22 }
10.8.3.249:10.8.2.197:{ "partition_range_start" : 16, "partition_range_end" : 16 }

Note: 10.8.3.249 has NO data, so the next string is appended as 10.8.3.249:10.8.2.197:{ "partition_range_start"

I would like the output format to be this:

+ set +x
Checking 6 servers
10.8.3.34:{ "partition_range_start" : 31, "partition_range_end" : 31 }
10.8.2.191:{ "partition_range_start" : 79, "partition_range_end" : 79 }
10.8.3.54:{ "partition_range_start" : 62, "partition_range_end" : 62 }
10.8.4.150:{ "partition_range_start" : 22, "partition_range_end" : 22 }
10.8.3.249:
10.8.2.197:{ "partition_range_start" : 16, "partition_range_end" : 16 }

OR  If no data for the IP that is read, put some value, i.e. EMPTY

10.8.3.34:{ "partition_range_start" : 31, "partition_range_end" : 31 }
10.8.2.191:{ "partition_range_start" : 79, "partition_range_end" : 79 }
10.8.3.54:{ "partition_range_start" : 62, "partition_range_end" : 62 }
10.8.4.150:{ "partition_range_start" : 22, "partition_range_end" : 22 }
10.8.3.249: EMPTY
10.8.2.197:{ "partition_range_start" : 16, "partition_range_end" : 16 }

How can I achieve this output? Thanks.

Body:
Change your for loop to…

for i in ${servers[@]}
do
  local host='10.1.2.130'
  local db='myapplication_cluster_state'
  _mongo=$(which mongo)
  local exp="db.myapplicationcluster_servers.find({\"node_host\":\"${i}\",\"node_type\":\"APP_PROCESS\",\"region\":\"us-east-1\",\"status\":\"ACTIVE\"},{\"partition_range_start\":1,\"partition_range_end\":1, _id:0}).pretty();"

  # Store output of mongo command in variable
  output=$(${_mongo} ${host}/${db} --eval "$exp" | grep -o -e "{[^}]*}")

  # Print {} if output variable is empty
  echo "${i}:${output:-{}}"
done

To switch {} with nothing, use echo "${i}:${output:-}"

To switch {} with EMPTY, use echo "${i}:${output:- EMPTY}"

Sorting

To sort on the value of partition_range_start, pipe the output of the demo function to the sort command…

demo | sort -n -k4

This says "sort the output of demo numerically (-n) on field 4 (-k4)". Fields are, by default, characters separated by whitespace.

This is what sort sees for the line 10.8.3.34:{ "partition_range_start" : 31, "partition_range_end" : 31 }...

field 1 10.8.3.34:{

field 2 "partition_range_start"

field 3 :

field 4 31,

field 5 "partition_range_end"

field 6 :

field 7 31

field 8 }


来源: stackexchange

问:
React JS event handler arguments
I was reading about "Lifting State Up" in React JS documentation and there is something I am not very clear about. The codepen can be found here: https://codepen.io/valscion/pen/jBNjja?editors=0010

In the TemperatureInput component, the onTemperatureChange event handler calls the handleCelsiusChange, but the latter contains a parameter of temperature. How are we passing this parameter? There is no argument passed in the onTemperatureChange. What am I missing here?

Hope someone can help me understand this.

```<code>class TemperatureInput extends React.Component {
  constructor(props) {
    super(props);
    this.handleChange = this.handleChange.bind(this);
  }

  handleChange(e) {
    this.props.onTemperatureChange(e.target.value);
  }

  render() {
    const temperature = this.props.temperature;
    const scale = this.props.scale;
    return (
      <fieldset>
        <legend>Enter temperature in {scaleNames[scale]}:</legend>
        <input value={temperature}
               onChange={this.handleChange} />
      </fieldset>
    );
  }
}
</code>```

```<code>class Calculator extends React.Component {
  constructor(props) {
    super(props);
    this.handleCelsiusChange = this.handleCelsiusChange.bind(this);
    this.handleFahrenheitChange = this.handleFahrenheitChange.bind(this);
    this.state = {temperature: '', scale: 'c'};
  }

  handleCelsiusChange(temperature) {
    this.setState({scale: 'c', temperature});
  }

  handleFahrenheitChange(temperature) {
    this.setState({scale: 'f', temperature});
  }

  render() {
    const scale = this.state.scale;
    const temperature = this.state.temperature;
    const celsius = scale === 'f' ? tryConvert(temperature, toCelsius) : temperature;
    const fahrenheit = scale === 'c' ? tryConvert(temperature, toFahrenheit) : temperature;

    return (
      <div>
        <TemperatureInput
          scale="c"
          temperature={celsius}
          onTemperatureChange={this.handleCelsiusChange} />
        <TemperatureInput
          scale="f"
          temperature={fahrenheit}
          onTemperatureChange={this.handleFahrenheitChange} />
        <BoilingVerdict
          celsius={parseFloat(celsius)} />
      </div>
    );
  }
}
</code>```

答:
In the TemperatureInput component, the onTemperatureChange event handler calls the handleCelsiusChange...

This assumption is incorrect.
You are passing a reference to the function object this.handleCelsiusChange to the attribute onTemperatureChange in the render function.

This function object is then used by calling it in TemperatureInput class.

```<code>this.props.onTemperatureChange(e.target.value)
</code>```

If it were to call the handleCelciusChange in the JSX, the render would look like:

```<code>    <TemperatureInput
      scale="c"
      temperature={celsius}
      onTemperatureChange={this.handleCelsiusChange(some_value)} />
</code>```

ContentLicense: CC BY-SA 3.0

Title: React JS event handler arguments

Body:
I was reading about "Lifting State Up" in React JS documentation and there is something I am not very clear about. The codepen can be found here: https://codepen.io/valscion/pen/jBNjja?editors=0010

In the TemperatureInput component, the onTemperatureChange event handler calls the handleCelsiusChange, but the latter contains a parameter of temperature. How are we passing this parameter? There is no argument passed in the onTemperatureChange. What am I missing here?

Hope someone can help me understand this.

class TemperatureInput extends React.Component {
  constructor(props) {
    super(props);
    this.handleChange = this.handleChange.bind(this);
  }

  handleChange(e) {
    this.props.onTemperatureChange(e.target.value);
  }

  render() {
    const temperature = this.props.temperature;
    const scale = this.props.scale;
    return (
      <fieldset>
        <legend>Enter temperature in {scaleNames[scale]}:</legend>
        <input value={temperature}
               onChange={this.handleChange} />
      </fieldset>
    );
  }
}

class Calculator extends React.Component {
  constructor(props) {
    super(props);
    this.handleCelsiusChange = this.handleCelsiusChange.bind(this);
    this.handleFahrenheitChange = this.handleFahrenheitChange.bind(this);
    this.state = {temperature: '', scale: 'c'};
  }

  handleCelsiusChange(temperature) {
    this.setState({scale: 'c', temperature});
  }

  handleFahrenheitChange(temperature) {
    this.setState({scale: 'f', temperature});
  }

  render() {
    const scale = this.state.scale;
    const temperature = this.state.temperature;
    const celsius = scale === 'f' ? tryConvert(temperature, toCelsius) : temperature;
    const fahrenheit = scale === 'c' ? tryConvert(temperature, toFahrenheit) : temperature;

    return (

        <TemperatureInput
          scale="c"
          temperature={celsius}
          onTemperatureChange={this.handleCelsiusChange} />
        <TemperatureInput
          scale="f"
          temperature={fahrenheit}
          onTemperatureChange={this.handleFahrenheitChange} />
        <BoilingVerdict
          celsius={parseFloat(celsius)} />

    );
  }
}

Body:
In the TemperatureInput component, the onTemperatureChange event handler calls the handleCelsiusChange...

This assumption is incorrect.
You are passing a reference to the function object this.handleCelsiusChange to the attribute onTemperatureChange in the render function.

This function object is then used by calling it in TemperatureInput class.

this.props.onTemperatureChange(e.target.value)

If it were to call the handleCelciusChange in the JSX, the render would look like:

    <TemperatureInput
      scale="c"
      temperature={celsius}
      onTemperatureChange={this.handleCelsiusChange(some_value)} />


问:
How to put up and down arrow just above dots in the slideshow of forms?
I am working on making a slideshow of forms. Here is my working codepen link. As you can see I have two dots on the right side which if I click then it opens another form. Now I want to put an up arrow just above those dots and down arrow just below those dots.

For example as shown in this image. I am trying to replicate exactly like this image and as you can see there is a up arrow just above those dots and down arrow just below those dots and they are perfectly aligned in one vertical line and  also their color is orange I believe. I want to do exactly like that. How can I achieve this? I am already using font-awesome css in my actual code, do I have to use that here?

Below is my HTML code:

```<code><!doctype html>
<html>
<head>
  <meta charset="utf-8">
  <title>SlidesJS Standard Code Example</title>
  <meta name="description" content="SlidesJS is a simple slideshow plugin for jQuery. Packed with a useful set of features to help novice and advanced developers alike create elegant and user-friendly slideshows.">
  <meta name="author" content="Nathan Searles">

  <!-- SlidesJS Required (if responsive): Sets the page width to the device width. -->
  <meta name="viewport" content="width=device-width">
  <!-- End SlidesJS Required -->

  <!-- CSS for slidesjs.com example -->
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css">
  <!-- End CSS for slidesjs.com example -->

  <!-- SlidesJS Optional: If you'd like to use this design -->
  <style>
    body {
      -webkit-font-smoothing: antialiased;
      font: normal 15px/1.5 "Helvetica Neue", Helvetica, Arial, sans-serif;
      color: #232525;
    }

    #slides,
    #slides2,
    #slides3 {
      display: none;
      margin-bottom:50px;
    }

    .slidesjs-navigation {
      margin-top:3px;
    }

    .slidesjs-previous {
      margin-right: 5px;
      float: left;
    }

    .slidesjs-next {
      margin-right: 5px;
      float: left;
    }

    .slidesjs-pagination {
      margin: 6px 0 0;
      float: right;
      list-style: none;
    }

    .slidesjs-pagination li {
      float: left;
      margin: 0 1px;
    }

    .slidesjs-pagination li a {
      display: block;
      width: 13px;
      height: 0;
      padding-top: 13px;
      background-image: url("https://s16.postimg.org/pt4k43i9x/pagination.png");
      background-position: 0 0;
      float: left;
      overflow: hidden;
    }

    .slidesjs-pagination li a.active,
    .slidesjs-pagination li a:hover.active {
      background-position: 0 -13px
    }

    .slidesjs-pagination li a:hover {
      background-position: 0 -26px
    }
    .navbar {
      overflow: hidden
    }
  </style>
  <!-- End SlidesJS Optional-->

  <!-- SlidesJS Required: These styles are required if you'd like a responsive slideshow -->
  <style>
    #slides {
      display: none
    }

    .container {
      margin: 0 auto
    }

    /* For tablets & smart phones */
    @media (max-width: 767px) {
      body {
        padding-left: 20px;
        padding-right: 20px;
      }
      .container {
        width: auto
      }
    }

    /* For smartphones */
    @media (max-width: 480px) {
      .container {
        width: auto
      }
    }

    /* For smaller displays like laptops */
    @media (min-width: 768px) and (max-width: 979px) {
      .container {
        width: 724px
      }
    }

    /* For larger displays */
    @media (min-width: 1200px) {
      .container {
        width: 1170px
      }
    }
  </style>
  <!-- SlidesJS Required: -->
</head>
<body>
<div class="topnav">
   <img src="https://s4.postimg.org/ojd13poal/northman_wordmark_CMYK.png">
   <nav>
      <ul>
         <li class="dropdown">
            <a href="#"><b>INSURANCE</b> <i class="fa fa-angle-down"></i></a>
            <ul class="dropdown-content">
               <li><a href="#"><i>INDIVIDUAL</i></a>
               </li>
               <li><a href="#"><i>CORPORATE</i></a>
               </li>
            </ul>
         </li>
         <li class="our-story">OUR STORY</li>
         <li class="login-signup">Log In | Sign up</li>
         <li class="get-covered">GET <strong style="font-style:italic">COVERED</strong>
         </li>
      </ul>
   </nav>
</div>
  <!-- SlidesJS Required: Start Slides -->
  <!-- The container is used to define the width of the slideshow -->
  <div class="container">
   <h3>INSURANCE FORM</h3>
   <h4><i>BASIC DETAILS</i></h4>
   <br>
    <div id="slides" class="container-fluid" >
  <form action="/action_page.php" class="form-horizontal">
      <div class="form-group">
         <div class="col-sm-6">
            <label>FIRST NAME</label>
            <input type="text" class="form-control" name="fname" value="Mickey 1">
         </div>
         <div class="col-sm-6">
            <label>LAST NAME</label>
            <input type="text" class="form-control" name="lname" value="Mouse">
         </div>
      </div>
      <div class="form-group">
         <div class="col-sm-6">
            <label>EMAIL</label>
            <input type="text" class="form-control" name="email" value="abc@host.com">
         </div>
         <div class="col-sm-6">
            <label>PHONE NUMBER</label>
            <input type="text" class="form-control" name="number" value="123-456-789">
         </div>
      </div>
      <div class="form-group">
         <div class="col-sm-6">
            <label>COUNTRY</label>
            <select name="country" class="form-control">
               <option value="canada">Canada</option>
            </select>
         </div>
         <div class="col-sm-3">
            <label>PROVINCE</label>
            <select name="province" class="form-control">
               <option value="ontario">ONTARIO</option>
            </select>
         </div>
         <div class="col-sm-3">
            <label>CITY</label>
            <select name="city" class="form-control">
               <option value="ottawa">OTTAWA</option>
            </select>
         </div>
      </div>
   </form>
  <form action="/action_page.php" class="form-horizontal">
      <div class="form-group">
         <div class="col-sm-6">
            <label>FIRST NAME</label>
            <input type="text" class="form-control" name="fname" value="Mickey 2">
         </div>
         <div class="col-sm-6">
            <label>LAST NAME</label>
            <input type="text" class="form-control" name="lname" value="Mouse">
         </div>
      </div>
      <div class="form-group">
         <div class="col-sm-6">
            <label>EMAIL</label>
            <input type="text" class="form-control" name="email" value="abc@host.com">
         </div>
         <div class="col-sm-6">
            <label>PHONE NUMBER</label>
            <input type="text" class="form-control" name="number" value="123-456-789">
         </div>
      </div>
      <div class="form-group">
         <div class="col-sm-6">
            <label>COUNTRY</label>
            <select name="country" class="form-control">
               <option value="canada">Canada</option>
            </select>
         </div>
         <div class="col-sm-3">
            <label>PROVINCE</label>
            <select name="province" class="form-control">
               <option value="ontario">ONTARIO</option>
            </select>
         </div>
         <div class="col-sm-3">
            <label>CITY</label>
            <select name="city" class="form-control">
               <option value="ottawa">OTTAWA</option>
            </select>
         </div>
      </div>
   </form>
            <a href="#" class="slidesjs-previous slidesjs-navigation"><i class="icon-chevron-left"></i></a>
      <a href="#" class="slidesjs-next slidesjs-navigation"><i class="icon-chevron-right"></i></a>
    </div>
  </div>
    <!-- End SlidesJS Required: Start Slides -->

  <!-- SlidesJS Required: Link to jQuery -->
  <script src="http://code.jquery.com/jquery-1.9.1.min.js"></script>
  <!-- End SlidesJS Required -->

  <!-- SlidesJS Required: Link to jquery.slides.js -->
  <script src="js/jquery.slides.min.js"></script>
  <!-- End SlidesJS Required -->

  <!-- SlidesJS Required: Initialize SlidesJS with a jQuery doc ready -->
  <script>
    $(function() {
      $('#slides').slidesjs({
        width: 800,
        height: 528,
        navigation: false
      });

      /*
        To have multiple slideshows on the same page
        they just need to have separate IDs
      */
      $('#slides2').slidesjs({
        width: 800,
        height: 528,
        navigation: false,
        start: 3,
        play: {
          auto: true
        }
      });

      $('#slides3').slidesjs({
        width: 800,
        height: 528,
        navigation: false
      });
    });
  </script>
  <!-- End SlidesJS Required -->
</body>
</html>
</code>```

答: You cas use :after and :before pseudo elements to put arrows before first dot and after last. Just set dots positions to relative and in :after/before add arrow in content and set it absolute position.</p>

Body:
I am working on making a slideshow of forms. Here is my working codepen link. As you can see I have two dots on the right side which if I click then it opens another form. Now I want to put an up arrow just above those dots and down arrow just below those dots.

For example as shown in this image. I am trying to replicate exactly like this image and as you can see there is a up arrow just above those dots and down arrow just below those dots and they are perfectly aligned in one vertical line and  also their color is orange I believe. I want to do exactly like that. How can I achieve this? I am already using font-awesome css in my actual code, do I have to use that here?

Below is my HTML code:

<!doctype html>

  <meta charset="utf-8">
  <title>SlidesJS Standard Code Example</title>
  <meta name="description" content="SlidesJS is a simple slideshow plugin for jQuery. Packed with a useful set of features to help novice and advanced developers alike create elegant and user-friendly slideshows.">
  <meta name="author" content="Nathan Searles">

  <meta name="viewport" content="width=device-width">

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

            INSURANCE

INDIVIDUAL

CORPORATE

OUR STORY

Log In | Sign up

GET COVERED

INSURANCE FORM

BASIC DETAILS

  <form action="/action_page.php" class="form-horizontal">

            FIRST NAME
            <input type="text" class="form-control" name="fname" value="Mickey 1">

            LAST NAME
            <input type="text" class="form-control" name="lname" value="Mouse">

            EMAIL
            <input type="text" class="form-control" name="email" value="abc@host.com">

            PHONE NUMBER
            <input type="text" class="form-control" name="number" value="123-456-789">

            COUNTRY
            <select name="country" class="form-control">
               <option value="canada">Canada</option>
            </select>

            PROVINCE
            <select name="province" class="form-control">
               <option value="ontario">ONTARIO</option>
            </select>

            CITY
            <select name="city" class="form-control">
               <option value="ottawa">OTTAWA</option>
            </select>

   </form>
  <form action="/action_page.php" class="form-horizontal">

            FIRST NAME
            <input type="text" class="form-control" name="fname" value="Mickey 2">

            LAST NAME
            <input type="text" class="form-control" name="lname" value="Mouse">

            EMAIL
            <input type="text" class="form-control" name="email" value="abc@host.com">

            PHONE NUMBER
            <input type="text" class="form-control" name="number" value="123-456-789">

            COUNTRY
            <select name="country" class="form-control">
               <option value="canada">Canada</option>
            </select>

            PROVINCE
            <select name="province" class="form-control">
               <option value="ontario">ONTARIO</option>
            </select>

            CITY
            <select name="city" class="form-control">
               <option value="ottawa">OTTAWA</option>
            </select>

   </form>


问:
Fragment is recreate on back press from other Fragment
I am facing a problem in regarding fragment.
In my scenario,

There are two fragment associated with FragmentActivity.
In FragmentActivity, there are a container layout (Frame Layout) in which all fragment will replace.

```<code>public void replaceFragment(Fragment fragmentClass) {
        String selectedFragment = fragmentClass.getClass().getName();

            FragmentManager fragmentManager = getSupportFragmentManager();
            FragmentTransaction fragmentTransaction = fragmentManager
                    .beginTransaction();
            fragmentTransaction
                    .replace(R.id.content_frame, fragmentClass);
            fragmentTransaction.addToBackStack(null);
            fragmentTransaction.commit();

    }
</code>```

First time , I set a List type fragment (Fragment A) in which get the data from web service and papulate over listview. I execute the AsyncTask from onCreateView() method.

In MainActivity: onCreate

```<code>SherlockFragment fragment = new FragmentA();
replaceFragment(fragment);
</code>```

On list item click of Fragment A, Fragment A will callback the activity method to replace it to details type fragment Fragment B.

```<code>@Override
    public void onAttach(Activity activity) {
        // TODO Auto-generated method stub
        super.onAttach(activity);
        callback = (ICallBack) activity;

    }

@Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {
        /*View rootView = inflater.inflate(R.layout.fragment_locate, container,
                false);*/
        View rootView = inflater.inflate(R.layout.fragment_a, container,
                false);

        ListView list = (ListView) rootView
                .findViewById(R.id.listView);
        adapter = new MyListAdapter();
        list.setAdapter(adapter);
        list
                .setOnItemClickListener(new AdapterView.OnItemClickListener() {

                    @Override
                    public void onItemClick(AdapterView<?> parent,
                            View convertView, int position, long id) {
                                SherlockFragment fragment = new SalonDetailFragment();
                                callback.replaceFragment(fragment);
                    }
                });

        ListDataTask task = new  ListDataTask();
        task.execute();

        return rootView;
    }

    class ListDataTask extends AsynTask<Void,Void,List<Data>>{

    public Void doInBackground(Void parems){

        List<Data> = getDataFromServer();
    }
    onPostExecute(List<Data> data){
        adapter.addAllData(data);
        adapter.notifyDataSetChanged();
    }

    }
</code>```

When I press back button, from Fragment B then Application will show Fragment A but it execute Asynctask again and get the data to papulate the listview.

So I need to know, How to maintain the pervious state of Fragment like Activity.

Is there are any way to not to create Fragment after come back from Other activity

Have a look my pseudo code.

答:
I have the same problem and solved by replacing

```<code> fragmentTransaction
                    .replace(R.id.content_frame, fragmentClass);
to
 fragmentTransaction
                    .add(R.id.content_frame, fragmentClass);
</code>```

Replace will always create new instance on back press while Add is just add a new fragment in Stack. for more information check this link

Body:
I am facing a problem in regarding fragment.
In my scenario,

There are two fragment associated with FragmentActivity.
In FragmentActivity, there are a container layout (Frame Layout) in which all fragment will replace.

public void replaceFragment(Fragment fragmentClass) {
        String selectedFragment = fragmentClass.getClass().getName();

            FragmentManager fragmentManager = getSupportFragmentManager();
            FragmentTransaction fragmentTransaction = fragmentManager
                    .beginTransaction();
            fragmentTransaction
                    .replace(R.id.content_frame, fragmentClass);
            fragmentTransaction.addToBackStack(null);
            fragmentTransaction.commit();

    }

First time , I set a List type fragment (Fragment A) in which get the data from web service and papulate over listview. I execute the AsyncTask from onCreateView() method.

In MainActivity: onCreate

SherlockFragment fragment = new FragmentA();
replaceFragment(fragment);

On list item click of Fragment A, Fragment A will callback the activity method to replace it to details type fragment Fragment B.

@Override
    public void onAttach(Activity activity) {
        // TODO Auto-generated method stub
        super.onAttach(activity);
        callback = (ICallBack) activity;

    }

@Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {
        /*View rootView = inflater.inflate(R.layout.fragment_locate, container,
                false);*/
        View rootView = inflater.inflate(R.layout.fragment_a, container,
                false);

        ListView list = (ListView) rootView
                .findViewById(R.id.listView);
        adapter = new MyListAdapter();
        list.setAdapter(adapter);
        list
                .setOnItemClickListener(new AdapterView.OnItemClickListener() {

                    @Override
                    public void onItemClick(AdapterView<?> parent,
                            View convertView, int position, long id) {
                                SherlockFragment fragment = new SalonDetailFragment();
                                callback.replaceFragment(fragment);
                    }
                });

        ListDataTask task = new  ListDataTask();
        task.execute();

        return rootView;
    }

    class ListDataTask extends AsynTask<Void,Void,List<Data>>{

    public Void doInBackground(Void parems){

        List<Data> = getDataFromServer();
    }
    onPostExecute(List<Data> data){
        adapter.addAllData(data);
        adapter.notifyDataSetChanged();
    }

    }

When I press back button, from Fragment B then Application will show Fragment A but it execute Asynctask again and get the data to papulate the listview.

So I need to know, How to maintain the pervious state of Fragment like Activity.

Is there are any way to not to create Fragment after come back from Other activity

Have a look my pseudo code.

Body:
I have the same problem and solved by replacing

 fragmentTransaction
                    .replace(R.id.content_frame, fragmentClass);
to
 fragmentTransaction
                    .add(R.id.content_frame, fragmentClass);

Replace will always create new instance on back press while Add is just add a new fragment in Stack. for more information check this link


问:
C# WebBrowser open new window and keep javascript object
I'm trying to design a multiple tab browser with webbrowser-control,

when my webrowser invoke the following javascript.

```<code>function myFunction() {
    var myWindow = window.open("", "_blank");
    // The website need do something to get url
    myWindow.location.href = "https://www.google.com";
}
</code>```

my webbrowser fire newWindow event first,
then i will open a new webbrowser,

in this case the url is "about:blank",

but the problem is how to bring "myWindow" to the new webbrowser and navigate to the correct url.

thanks a lot.

答: Use _parent instead of _blank in window.open.</p>

Body:
I'm trying to design a multiple tab browser with webbrowser-control,

when my webrowser invoke the following javascript.

function myFunction() {
    var myWindow = window.open("", "_blank");
    // The website need do something to get url
    myWindow.location.href = "https://www.google.com";
}

my webbrowser fire newWindow event first,
then i will open a new webbrowser,

in this case the url is "about:blank",

but the problem is how to bring "myWindow" to the new webbrowser and navigate to the correct url.

thanks a lot.


问:
Using password_hash PASSWORD_DEFAULT legacy concerns
From the php page: http://php.net/manual/en/function.password-hash.php

PASSWORD_DEFAULT - Use the bcrypt algorithm (default as of PHP 5.5.0). Note that this constant is designed to change over time as new and stronger algorithms are added to PHP. For that reason, the length of the result from using this identifier can change over time. Therefore, it is recommended to store the result in a database column that can expand beyond 60 characters (255 characters would be a good choice).

Would this mean that if I password_verify a password with a later version e.g. PHP8, it might not be able to decipher the stored password correctly? Or is all that information safely embedded already and all I have to do is store the output of password_hash into my DB and just call password_verify for validation without worries?

答:
Would this mean that if I password_verify a password with a later version e.g. PHP8, it might not be able to decipher the stored password correctly?

No. The password hash includes information on which specific algorithm was actually used. If a future version of PHP supports more than one password hashing algorithm, it will be able to read that information from an old hash to figure out how to reproduce it.

(Specifically, the $2y$ prefix currently present on all hashes indicates that they were generated using the PASSWORD_BCRYPT algorithm. Any future algorithm will use a different prefix.)


问:
Displaying a DAE file with ARKit and tracking an Anchor in the scene
I'm trying out ARKit, and I set up an ARSCNView using this tutorial.

Then set up tracking horizontal 3D planes with the second part of this tutorial.

I created a single view application then constrained an ARSCNView flush to the root view with an outlet to my ViewController.

Here is the code in the ViewController:

```<code>import UIKit
import ARKit

class ViewController: UIViewController {

    //MARK: Properties
    @IBOutlet weak var arScene: ARSCNView!

    //MARK: ARKit variables
    var realityConfiguration: ARWorldTrackingSessionConfiguration?

    //MARK: Lifecycle
    override func viewDidLoad() {
        super.viewDidLoad()
    }

    override func viewDidAppear(_ animated: Bool) {
        super.viewDidAppear(animated)
        self.prepare()
    }

    //MARK: Actions

    //MARK: Overrides
}

extension ViewController {
    func prepare() {
        //Check to see if active reality is supported
        guard ARSessionConfiguration.isSupported else {
            //Custom alert function that just quickly displays a UIAlertController
            AppDelegate.alert(title: "Not Supported", message: "Active Reality is not supported on this device")
            return
        }
        //Set up the ARSessionConfiguration
        self.realityConfiguration = ARWorldTrackingSessionConfiguration()
        //Set up the ARSCNView
        guard let config = self.realityConfiguration else {
            return
        }
        //Run the ARSCNView and set its delegate
        self.arScene.session.run(config)
        self.arScene.delegate = self
    }
}

extension ViewController: ARSCNViewDelegate {
    func renderer(_ renderer: SCNSceneRenderer, nodeFor anchor: ARAnchor) -> SCNNode? {
        return nil
    }

    func renderer(_ renderer: SCNSceneRenderer, didAdd node: SCNNode, for anchor: ARAnchor) {
        guard let planAnchor = anchor as? ARPlaneAnchor else {
            return
        }

        let plane = SCNPlane(width: CGFloat(planAnchor.extent.x), height: CGFloat(planAnchor.extent.z))
        let planeNode = SCNNode(geometry: plane)
        planeNode.position = SCNVector3Make(planAnchor.center.x, 0, planAnchor.center.z)

        planeNode.transform = SCNMatrix4MakeRotation(-Float.pi / 2, 1, 0, 0)

        node.addChildNode(planeNode)
    }

    func renderer(_ renderer: SCNSceneRenderer, willUpdate node: SCNNode, for anchor: ARAnchor) {
        print("Will updated Node on Anchor: \(anchor.identifier)")
    }

    func renderer(_ renderer: SCNSceneRenderer, didUpdate node: SCNNode, for anchor: ARAnchor) {
        print("Did updated Node on Anchor: \(anchor.identifier)")
    }

    func renderer(_ renderer: SCNSceneRenderer, didRemove node: SCNNode, for anchor: ARAnchor) {
        print("Removed Node on Anchor: \(anchor.identifier)")
    }
}
</code>```

I downloaded Xcode 9 beta, followed Apple's tutorials and realized my iPhone 6 does not have the A9 chip required for the ARWorldTrackingSessionConfiguration object.

About halfway down in the first tutorial I linked, Apple says you can still create AR experiences without the A9 chip. However, they do not go into further detail. Has anyone else found a starting point, and is willing to provide a code example of using a .dae file and

Choosing an anchor point to display it

Tracking that anchor point

Actually displaying the .dae file

答:
There's not really anything to see using your code — just a live camera view.

The main reason you're not seeing any augmentations in your reality is that your code adds SceneKit content to the scene only when anchors are added to the ARSession... but you're not manually adding any anchors, and you haven't enabled plane detection so ARKit isn't automatically adding anchors. If you enable plane detection, you'll start getting somewhere...

```<code>self.realityConfiguration = ARWorldTrackingSessionConfiguration()
realityConfiguration?.planeDetection = .horizontal
</code>```

But you still won't see anything. That's because your ARSCNViewDelegate implementation has conflicting instructions. This part:

```<code>func renderer(_ renderer: SCNSceneRenderer, nodeFor anchor: ARAnchor) -> SCNNode? {
    return nil
}
</code>```

...means that no SceneKit nodes will be created for your anchors. Because there's no nodes, your renderer(_:didAdd:for:) function is never being called, so your code within that method is never creating any SceneKit content.

If you turn on plane detection and delete / comment out the renderer(_: nodeFor:) method, the rest of your code should get you something like this:

(The pure white area is your SCNPlane. I had to unfold my iPad cover on the white table get enough scene detail for plane detection to find anything. Also, check the background... there was actually a moment at WWDC today where the merch store wasn't packed full of people.)

As for whether you need an A9, Apple's messaging is a little unclear here. When they say ARKit requires A9 or better, what they really mean is ARWorldTrackingSessionConfiguration does. And that's where all the best AR magic is. (There's even a UIRequiredDeviceCapabilities key for arkit that actually covers devices with world tracking support, so you can restrict your app on the App Store to being offered only to those devices.)

There's still some ARKit without world tracking, though. Run a session with the base class ARSessionConfiguration and you get orientation-only tracking. (No position tracking, no plane detection, no hit testing.)

What does that get you? Well, if you've played the current version of Pokémon GO, it works like that: because it tracks only device orientation, not position, you can't get closer to Pikachu or walk around behind him — the illusion that he occupies the real world holds as long as you only tilt or turn your device without moving it.

You load 3D content with SceneKit and place it in AR just like you load and place it in any other SceneKit app/game. There are plenty of resources out there for this, and lots of ways to do it. One of them you'll find in the Xcode template when you create a new AR project and choose SceneKit. The loading part goes something like this:

```<code>let scene = SCNScene(named: "ship.scn" inDirectory: "assets.scnassets")
let ship = scene.rootNode.childNode(withName: "ship", recursively: true)
</code>```

Then to place it:

```<code>ship.simdPosition = float3(0, 0, -0.5)
// half a meter in front of the *initial* camera position
myARSCNView.scene.rootNode.addChildNode(ship)
</code>```

The main difference to remember for placing things in AR is that positions are measured in meters (and your content needs to be designed so that it's sensibly sized in meters).

ContentLicense: CC BY-SA 4.0

Body:
I'm trying out ARKit, and I set up an ARSCNView using this tutorial.

Then set up tracking horizontal 3D planes with the second part of this tutorial.

I created a single view application then constrained an ARSCNView flush to the root view with an outlet to my ViewController.

Here is the code in the ViewController:

import UIKit
import ARKit

class ViewController: UIViewController {

    //MARK: Properties
    @IBOutlet weak var arScene: ARSCNView!

    //MARK: ARKit variables
    var realityConfiguration: ARWorldTrackingSessionConfiguration?

    //MARK: Lifecycle
    override func viewDidLoad() {
        super.viewDidLoad()
    }

    override func viewDidAppear(_ animated: Bool) {
        super.viewDidAppear(animated)
        self.prepare()
    }

    //MARK: Actions

    //MARK: Overrides
}

extension ViewController {
    func prepare() {
        //Check to see if active reality is supported
        guard ARSessionConfiguration.isSupported else {
            //Custom alert function that just quickly displays a UIAlertController
            AppDelegate.alert(title: "Not Supported", message: "Active Reality is not supported on this device")
            return
        }
        //Set up the ARSessionConfiguration
        self.realityConfiguration = ARWorldTrackingSessionConfiguration()
        //Set up the ARSCNView
        guard let config = self.realityConfiguration else {
            return
        }
        //Run the ARSCNView and set its delegate
        self.arScene.session.run(config)
        self.arScene.delegate = self
    }
}

extension ViewController: ARSCNViewDelegate {
    func renderer(_ renderer: SCNSceneRenderer, nodeFor anchor: ARAnchor) -> SCNNode? {
        return nil
    }

    func renderer(_ renderer: SCNSceneRenderer, didAdd node: SCNNode, for anchor: ARAnchor) {
        guard let planAnchor = anchor as? ARPlaneAnchor else {
            return
        }

        let plane = SCNPlane(width: CGFloat(planAnchor.extent.x), height: CGFloat(planAnchor.extent.z))
        let planeNode = SCNNode(geometry: plane)
        planeNode.position = SCNVector3Make(planAnchor.center.x, 0, planAnchor.center.z)

        planeNode.transform = SCNMatrix4MakeRotation(-Float.pi / 2, 1, 0, 0)

        node.addChildNode(planeNode)
    }

    func renderer(_ renderer: SCNSceneRenderer, willUpdate node: SCNNode, for anchor: ARAnchor) {
        print("Will updated Node on Anchor: \(anchor.identifier)")
    }

    func renderer(_ renderer: SCNSceneRenderer, didUpdate node: SCNNode, for anchor: ARAnchor) {
        print("Did updated Node on Anchor: \(anchor.identifier)")
    }

    func renderer(_ renderer: SCNSceneRenderer, didRemove node: SCNNode, for anchor: ARAnchor) {
        print("Removed Node on Anchor: \(anchor.identifier)")
    }
}

I downloaded Xcode 9 beta, followed Apple's tutorials and realized my iPhone 6 does not have the A9 chip required for the ARWorldTrackingSessionConfiguration object.

About halfway down in the first tutorial I linked, Apple says you can still create AR experiences without the A9 chip. However, they do not go into further detail. Has anyone else found a starting point, and is willing to provide a code example of using a .dae file and

Choosing an anchor point to display it

Tracking that anchor point

Actually displaying the .dae file

Body:
There's not really anything to see using your code — just a live camera view.

The main reason you're not seeing any augmentations in your reality is that your code adds SceneKit content to the scene only when anchors are added to the ARSession... but you're not manually adding any anchors, and you haven't enabled plane detection so ARKit isn't automatically adding anchors. If you enable plane detection, you'll start getting somewhere...

self.realityConfiguration = ARWorldTrackingSessionConfiguration()
realityConfiguration?.planeDetection = .horizontal

But you still won't see anything. That's because your ARSCNViewDelegate implementation has conflicting instructions. This part:

func renderer(_ renderer: SCNSceneRenderer, nodeFor anchor: ARAnchor) -> SCNNode? {
    return nil
}

...means that no SceneKit nodes will be created for your anchors. Because there's no nodes, your renderer(_:didAdd:for:) function is never being called, so your code within that method is never creating any SceneKit content.

If you turn on plane detection and delete / comment out the renderer(_: nodeFor:) method, the rest of your code should get you something like this:

(The pure white area is your SCNPlane. I had to unfold my iPad cover on the white table get enough scene detail for plane detection to find anything. Also, check the background... there was actually a moment at WWDC today where the merch store wasn't packed full of people.)

As for whether you need an A9, Apple's messaging is a little unclear here. When they say ARKit requires A9 or better, what they really mean is ARWorldTrackingSessionConfiguration does. And that's where all the best AR magic is. (There's even a UIRequiredDeviceCapabilities key for arkit that actually covers devices with world tracking support, so you can restrict your app on the App Store to being offered only to those devices.)

There's still some ARKit without world tracking, though. Run a session with the base class ARSessionConfiguration and you get orientation-only tracking. (No position tracking, no plane detection, no hit testing.)

What does that get you? Well, if you've played the current version of Pokémon GO, it works like that: because it tracks only device orientation, not position, you can't get closer to Pikachu or walk around behind him — the illusion that he occupies the real world holds as long as you only tilt or turn your device without moving it.

You load 3D content with SceneKit and place it in AR just like you load and place it in any other SceneKit app/game. There are plenty of resources out there for this, and lots of ways to do it. One of them you'll find in the Xcode template when you create a new AR project and choose SceneKit. The loading part goes something like this:

let scene = SCNScene(named: "ship.scn" inDirectory: "assets.scnassets")
let ship = scene.rootNode.childNode(withName: "ship", recursively: true)

Then to place it:

ship.simdPosition = float3(0, 0, -0.5)
// half a meter in front of the *initial* camera position
myARSCNView.scene.rootNode.addChildNode(ship)

The main difference to remember for placing things in AR is that positions are measured in meters (and your content needs to be designed so that it's sensibly sized in meters).


问:
jquery parallax.js not work
I've been trying more than 10 times to use parallax.js jquery plugin. But it doesn't work. I don't understand what's going on with me.

plugin Site: http://matthew.wagerfield.com/parallax/

my demo work site: http://contact.themeshef.com/

Can anybody help me about how to use parallax js ?
Thanks in advance!

Page source:

```<code><!DOCTYPE HTML>
<html lang="en-US">
<head>
    <meta charset="UTF-8">
    <title></title>
    <style type="text/css">
        #container {
            width: 100%;
            height: 500px;
        }
    </style>

</head>
<body>
    <div id="container">
        <div id="scene">
          <div class="layer" data-depth="0.00"><img src="layer1.png"></div>
          <div class="layer" data-depth="0.20"><img src="layer2.png"></div>
          <div class="layer" data-depth="0.40"><img src="layer3.png"></div>
          <div class="layer" data-depth="0.60"><img src="layer4.png"></div>
          <div class="layer" data-depth="0.80"><img src="layer5.png"></div>
          <div class="layer" data-depth="1.00"><img src="layer6.png"></div>
        </div>
    </div>

    <script src="jquery-3.2.1.min.js"></script>
    <script src="parallax.js"></script>
    <script>
      var scene = document.getElementById('scene');
      var parallax = new Parallax(scene);
    </script>
</body>
</html>
</code>```

答:
You are using non-compiled version of library. either you should compile and use or you can download compiled version of parallax.min.js file from here or you can use cdn.

In this example i'm using CDN

<!DOCTYPE HTML>

    <meta charset="UTF-8">
    <title></title>

```

Title: jquery parallax.js not work

Body:
I've been trying more than 10 times to use parallax.js jquery plugin. But it doesn't work. I don't understand what's going on with me.

plugin Site: http://matthew.wagerfield.com/parallax/

my demo work site: http://contact.themeshef.com/

Can anybody help me about how to use parallax js ?
Thanks in advance!

Page source:

<!DOCTYPE HTML>

    <meta charset="UTF-8">
    <title></title>

Body:
You are using non-compiled version of library. either you should compile and use or you can download compiled version of parallax.min.js file from here or you can use cdn.

In this example i'm using CDN

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/parallax/2.1.3/parallax.min.js"></script>
<!DOCTYPE HTML>
<html lang="en-US">
<head>
    <meta charset="UTF-8">
    <title></title>
    <style type="text/css">
        #container {
            width: 100%;
            height: 500px;
        }
    </style>

</head>
<body>
    <div id="container">
        <div id="scene">
          <div class="layer" data-depth="0.00"><img src="layer1.png"></div>
          <div class="layer" data-depth="0.20"><img src="layer2.png"></div>
          <div class="layer" data-depth="0.40"><img src="layer3.png"></div>
          <div class="layer" data-depth="0.60"><img src="layer4.png"></div>
          <div class="layer" data-depth="0.80"><img src="layer5.png"></div>
          <div class="layer" data-depth="1.00"><img src="layer6.png"></div>
        </div>
    </div>

    <script src="jquery-3.2.1.min.js"></script>
    <script src="parallax.js"></script>
    <script>
      var scene = document.getElementById('scene');
      var parallax = new Parallax(scene);
    </script>
</body>
</html>


问:
The jquery $.each function console.log(this) ,prints result is string like "a" 'b' 'c'
```<code>var arr=["aaa","bbb","cccc"];
$.each(arr,function(a,b){
    console.log(this);
})
</code>```

the result is in the Chrome console following :

the Chrome console

i think the result is "aaa" "bbb","cccc",why the result is "a" "a" "a" 'b''b''b'....

答:
Try change to this:</p>

```<code>var arr=["aaa","bbb","cccc"];
$.each(arr,function(a,b){
    console.log(b);
})
</code>```

Body:
var arr=["aaa","bbb","cccc"];
$.each(arr,function(a,b){
    console.log(this);
})

the result is in the Chrome console following :

the Chrome console

i think the result is "aaa" "bbb","cccc",why the result is "a" "a" "a" 'b''b''b'....

Body:
Try change to this:

var arr=["aaa","bbb","cccc"];
$.each(arr,function(a,b){
    console.log(b);
})


问:
Rails link_to :method => :put send a GET request
I'm trying to use link_to to send PUT request but every time i send a GET request instead.

I tried :

```<code><%= link_to raw('Valider'), roommates_join_path(:reference => var['reference']), :method => :put, :class => "btn btn-primary" %>
</code>```

in my browser I get :

```<code><a class="btn btn-primary" data-method="put" href="/roommates/join" rel="nofollow">Valider</a>
</code>```

my routes.rb:

```<code> put 'roommates/join'
</code>```

When I click :

No route matches [GET] "/roommates/join"

答:
I have the same problem where I use link_to path, method: :put, data: {} and it fire AJAX to GET and PUT.

Change the link_to to button_to to use the actual form instead of using jquery_ujs fixes the problem. Though, I did not really find put the is the cause.

Body:
I'm trying to use link_to to send PUT request but every time i send a GET request instead.

I tried :

<%= link_to raw('Valider'), roommates_join_path(:reference => var['reference']), :method => :put, :class => "btn btn-primary" %>

in my browser I get :

Valider

my routes.rb:

 put 'roommates/join'

When I click :

No route matches [GET] "/roommates/join"


问:
Order by in exists sub query
When I execute below query I give this error:

ORA-00907: missing right parenthesis

error hint to like.

```<code>select *
from image img, imageinfo info
where
   img.i_id = info.i_id and
   (info.i_state like 'delete%' or
    exists (select * from back bk where rownum = 1 order by bk.b_date desc)
   )
</code>```

答: Remove order by clause from your exists clause</p>

Title: Order by in exists sub query

Body:
When I execute below query I give this error:

ORA-00907: missing right parenthesis

error hint to like.

select *
from image img, imageinfo info
where
   img.i_id = info.i_id and
   (info.i_state like 'delete%' or
    exists (select * from back bk where rownum = 1 order by bk.b_date desc)
   )


问:
Having Troubles with trying to fix an error I'm receiving from MYSQL
Here is the PHP Code I have that is Causing this Error, I haven't had this error come up before and I searched and looked around before posting and Couldn't find a way to get ride of the error.

PHP (WORKING PHP) :

```<code>   <?php
    require('includes/config.php');
    $username = $_SESSION['username'];

    if($_POST['username'] != $_SESSION['user']['username'])
    {
        // Define our query parameter values
        $query_params = array(
            ':username' => $_POST['username']
        );

        $stmt = $db->prepare("SELECT username FROM members WHERE username = :username");
        $stmt->execute($query_params);

        // Retrieve results (if any)
        if($stmt->rowCount() > 0)
        {
            die("This username is already in use");
        }

        try
        {
            $query_params = array(
                ':username' => $_POST['username'],
                ':last_username' => $username
            );

            // Execute the query
            $stmt = $db->prepare("UPDATE members SET username = :username WHERE username = :last_username");
            $result = $stmt->execute($query_params);
        }
        catch(PDOException $ex)
        {
            // Note: On a production website, you should not output $ex->getMessage().
            // It may provide an attacker with helpful information about your code.
            die("Failed to run query: " . $ex->getMessage());
        }
          }

?>
</code>```

HTML:

```<code>                               <div id="changeusername" class="tab-pane">
                     <h3> Change Your Username : </h3>
  <form  method="post" action="changeusername.php" autocomplete="off">
                    <input type="text" name="username" id="username" class="form-control" placeholder="New Username" autofocus  value="<?php if(isset($error)){ echo $_POST['username']; } ?>" tabindex="1">
                    <br>
                    <input type="password" name="password" id="password" class="form-control" placeholder="Confirm Your Password">
                   <br>
                    <button class="btn btn-theme btn-block" name="submit" type="submit"><i class="fa fa-lock"></i> Change Username</button>

              </form>
</code>```

Error I'm Receiving, after I input Boom2 Which is the New Username and boom1 is the oldd Username:
Failed to run query: SQLSTATE[42000]: Syntax error or access violation: 1064 You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ''boom2' WHERE username = 'boom1'' at line 1

答:
you have to bind column next line of the query.

$stmt = $db->prepare("UPDATE members SET :username WHERE username = '$username'");
$stmt->bindParam(':username', $username);
$result = $stmt->execute();

you may get Notice Error: "Undefined variable: _SESSION" and
"Undefined index: user"
Solutions :
$username               = $_POST['username'];
$_SESSION['username']  = $username;

Body:
Here is the PHP Code I have that is Causing this Error, I haven't had this error come up before and I searched and looked around before posting and Couldn't find a way to get ride of the error.

PHP (WORKING PHP) :

   <?php
    require('includes/config.php');
    $username = $_SESSION['username'];

    if($_POST['username'] != $_SESSION['user']['username'])
    {
        // Define our query parameter values
        $query_params = array(
            ':username' => $_POST['username']
        );

        $stmt = $db->prepare("SELECT username FROM members WHERE username = :username");
        $stmt->execute($query_params);

        // Retrieve results (if any)
        if($stmt->rowCount() > 0)
        {
            die("This username is already in use");
        }

        try
        {
            $query_params = array(
                ':username' => $_POST['username'],
                ':last_username' => $username
            );

            // Execute the query
            $stmt = $db->prepare("UPDATE members SET username = :username WHERE username = :last_username");
            $result = $stmt->execute($query_params);
        }
        catch(PDOException $ex)
        {
            // Note: On a production website, you should not output $ex->getMessage().
            // It may provide an attacker with helpful information about your code.
            die("Failed to run query: " . $ex->getMessage());
        }
          }

?>

HTML:

 Change Your Username :

  <form  method="post" action="changeusername.php" autocomplete="off">
                    <input type="text" name="username" id="username" class="form-control" placeholder="New Username" autofocus  value="<?php if(isset($error)){ echo $_POST['username']; } ?>" tabindex="1">

                    <input type="password" name="password" id="password" class="form-control" placeholder="Confirm Your Password">

                    <button class="btn btn-theme btn-block" name="submit" type="submit"> Change Username</button>

              </form>

Error I'm Receiving, after I input Boom2 Which is the New Username and boom1 is the oldd Username:
Failed to run query: SQLSTATE[42000]: Syntax error or access violation: 1064 You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ''boom2' WHERE username = 'boom1'' at line 1


问:
Missing template in angular 2
I am new to Angular 2. I am developing I app that I completed the Root component that contains a navigation bar and footer. I am working on the homepage module right now and I am getting this error.

[Error] Unhandled Promise rejection: (8)
      Template parse errors:
      site-header' is not a known element:
      1. If 'site-header' is an Angular component, then verify that it is part of this module.

This is my main.ts file in the homage folder

```<code>import { platformBrowserDynamic } from '@angular/platform-browser-  dynamic';
import { HomepageModule } from './homepage.module';

const platform = platformBrowserDynamic();
platform.bootstrapModule(HomepageModule);
</code>```

This is  the module file

```<code>import { NgModule }      from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { platformBrowserDynamic } from '@angular/platform-browser-dynamic';

import { HomepageComponent} from './homepage.component'
import { SiteHeaderComponent } from '../site-header/site-header.component'

@NgModule({
  imports:      [ BrowserModule ],
  declarations: [ SiteHeaderComponent ],
  bootstrap:    [ HomepageComponent ]
})
export class HomepageModule { }
</code>```

This is the content of the homepage template file

```<code><site-header>header</site-header>
</code>```

This is the contents of site-header html

```<code><!-- Site header -->
<header class="site-header size-lg text-center" style="background-image: url(assets/img/bg-banner1.jpg)">
  <div class="container">
    <div class="col-xs-12">

    </div>

  </div>
</header>
<!-- END Site header -->
</code>```

I checked my imports multiple times and I do not see anything that looks off.

I even tried to restart the server maybe that was the issue.

答:
The HomepageComponent should be included in the declarations.  Bootstrap should only be used if this is the root module of your application.</p>

```<code>@NgModule({
  imports:      [BrowserModule],
  declarations: [
                 HomepageComponent,
                 SiteHeaderComponent
  ]
})
export class HomepageModule { }
</code>```

Title: Missing template in angular 2

Body:
I am new to Angular 2. I am developing I app that I completed the Root component that contains a navigation bar and footer. I am working on the homepage module right now and I am getting this error.

[Error] Unhandled Promise rejection: (8)
      Template parse errors:
      site-header' is not a known element:
      1. If 'site-header' is an Angular component, then verify that it is part of this module.

This is my main.ts file in the homage folder

import { platformBrowserDynamic } from '@angular/platform-browser-  dynamic';
import { HomepageModule } from './homepage.module';

const platform = platformBrowserDynamic();
platform.bootstrapModule(HomepageModule);

This is  the module file

import { NgModule }      from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { platformBrowserDynamic } from '@angular/platform-browser-dynamic';

import { HomepageComponent} from './homepage.component'
import { SiteHeaderComponent } from '../site-header/site-header.component'

@NgModule({
  imports:      [ BrowserModule ],
  declarations: [ SiteHeaderComponent ],
  bootstrap:    [ HomepageComponent ]
})
export class HomepageModule { }

This is the content of the homepage template file

<site-header>header</site-header>

This is the contents of site-header html

I checked my imports multiple times and I do not see anything that looks off.

I even tried to restart the server maybe that was the issue.

Body:
The HomepageComponent should be included in the declarations.  Bootstrap should only be used if this is the root module of your application.

@NgModule({
  imports:      [BrowserModule],
  declarations: [
                 HomepageComponent,
                 SiteHeaderComponent
  ]
})
export class HomepageModule { }


问:
Ios Swift making font toggle bold, italic, boldItalic, normal without change other attributes
I am surprised, that simply setting bold and italic for existing font is so complicated in Swift.

I just want to simplify things by having following methods on font class.

I want the below methods to be added to existing font which has font-family and font-size set. I need to preserve these and change only the following.

setBold : Shud preserve italic

setItalic : Shud preserve bold

setBoldItalic

setNormal : remove both bold and italic

removeBold : Shud preserve italic

removeitalic : Shud preserve bold

I tried the below, and it's feeling like a nightmare for me using fontDescriptorWithSymbolicTraits.

Is there a simpler way of doing these in a few lines of code?

```<code>extension UIFont
{
    var isBold: Bool
    {
        return fontDescriptor().symbolicTraits.contains(.TraitBold)
    }

    var isItalic: Bool
    {
        return fontDescriptor().symbolicTraits.contains(.TraitItalic)
    }

    func setBold() -> UIFont
    {
        var fontDescriptorVar: UIFontDescriptor
        if(isBold){
            return self
        }
        else
        {
            fontDescriptorVar = fontDescriptor().fontDescriptorWithSymbolicTraits(.TraitBold)
        }
        return UIFont(descriptor: fontDescriptorVar, size: 0)
    }

    func setItalic()-> UIFont
    {
        var fontDescriptorVar: UIFontDescriptor
        if(isItalic) {
            return self
        }
        else
        {
            fontDescriptorVar = fontDescriptor().fontDescriptorWithSymbolicTraits(.TraitItalic)
        }
        return UIFont(descriptor: fontDescriptorVar, size: 0)
    }

    func setBoldItalic()-> UIFont
    {
        let fontDescriptorVar = fontDescriptor().fontDescriptorWithSymbolicTraits(UIFontDescriptorSymbolicTraits(arrayLiteral: .TraitBold, .TraitItalic))
        return UIFont(descriptor: fontDescriptorVar, size: 0)
    }

    // Things I need are

    // To set back to normal

    func setNormal()-> UIFont
    {

    }

    // Remove only bold if it's both bold and Italic

    func removeBold()-> UIFont
    {

    }

    // Remove only italic if it's both bold and Italic

    func removeitalic()-> UIFont
    {

    }
}
</code>```

I don't want to use this which asks me the size and font as input:

```<code>UIFont(name "namFontFamily", size: 16)

UIFont.systemFontOfSize(16, weight: UIFontWeightLight)
</code>```

I searched everywhere and found no simple solution matching my needs.

答:
SWIFT 3.1

```<code>func changeTrait(trait: UIFontDescriptorSymbolicTraits) {
        let range = textView.selectedRange
        let currentAttributes = textView.textStorage.attributes(at: range.location, effectiveRange: nil)
        guard let currentFont = currentAttributes[NSFontAttributeName] as? UIFont else {
            return
        }

        let fontDescriptor = currentFont.fontDescriptor
        var changedFontDescriptor: UIFontDescriptor!

        if fontDescriptor.symbolicTraits.contains(trait) {
            let existingTraitsWithNewTrait = UIFontDescriptorSymbolicTraits(rawValue: fontDescriptor.symbolicTraits.rawValue & ~trait.rawValue)
            changedFontDescriptor = fontDescriptor.withSymbolicTraits(existingTraitsWithNewTrait)
        } else {
            changedFontDescriptor = fontDescriptor.withSymbolicTraits(UIFontDescriptorSymbolicTraits(rawValue: fontDescriptor.symbolicTraits.rawValue | trait.rawValue))
        }

        let updatedFont = UIFont(descriptor: changedFontDescriptor , size: 0)

        let newAttributes = [NSFontAttributeName: updatedFont]
        textView.textStorage.beginEditing()
        textView.textStorage.setAttributes(newAttributes, range: range)
        textView.textStorage.endEditing()
 }
</code>```

INVOKE:

FOR BOLD:  changeTrait(trait: .traitBold)

FOR ITALIC: changeTrait(trait: .traitItalic)

Body:
I am surprised, that simply setting bold and italic for existing font is so complicated in Swift.

I just want to simplify things by having following methods on font class.

I want the below methods to be added to existing font which has font-family and font-size set. I need to preserve these and change only the following.

setBold : Shud preserve italic

setItalic : Shud preserve bold

setBoldItalic

setNormal : remove both bold and italic

removeBold : Shud preserve italic

removeitalic : Shud preserve bold

I tried the below, and it's feeling like a nightmare for me using fontDescriptorWithSymbolicTraits.

Is there a simpler way of doing these in a few lines of code?

extension UIFont
{
    var isBold: Bool
    {
        return fontDescriptor().symbolicTraits.contains(.TraitBold)
    }

    var isItalic: Bool
    {
        return fontDescriptor().symbolicTraits.contains(.TraitItalic)
    }

    func setBold() -> UIFont
    {
        var fontDescriptorVar: UIFontDescriptor
        if(isBold){
            return self
        }
        else
        {
            fontDescriptorVar = fontDescriptor().fontDescriptorWithSymbolicTraits(.TraitBold)
        }
        return UIFont(descriptor: fontDescriptorVar, size: 0)
    }

    func setItalic()-> UIFont
    {
        var fontDescriptorVar: UIFontDescriptor
        if(isItalic) {
            return self
        }
        else
        {
            fontDescriptorVar = fontDescriptor().fontDescriptorWithSymbolicTraits(.TraitItalic)
        }
        return UIFont(descriptor: fontDescriptorVar, size: 0)
    }

    func setBoldItalic()-> UIFont
    {
        let fontDescriptorVar = fontDescriptor().fontDescriptorWithSymbolicTraits(UIFontDescriptorSymbolicTraits(arrayLiteral: .TraitBold, .TraitItalic))
        return UIFont(descriptor: fontDescriptorVar, size: 0)
    }

    // Things I need are

    // To set back to normal

    func setNormal()-> UIFont
    {

    }

    // Remove only bold if it's both bold and Italic

    func removeBold()-> UIFont
    {

    }

    // Remove only italic if it's both bold and Italic

    func removeitalic()-> UIFont
    {

    }
}

I don't want to use this which asks me the size and font as input:

UIFont(name "namFontFamily", size: 16)

UIFont.systemFontOfSize(16, weight: UIFontWeightLight)

I searched everywhere and found no simple solution matching my needs.

Body:
SWIFT 3.1

func changeTrait(trait: UIFontDescriptorSymbolicTraits) {
        let range = textView.selectedRange
        let currentAttributes = textView.textStorage.attributes(at: range.location, effectiveRange: nil)
        guard let currentFont = currentAttributes[NSFontAttributeName] as? UIFont else {
            return
        }

        let fontDescriptor = currentFont.fontDescriptor
        var changedFontDescriptor: UIFontDescriptor!

        if fontDescriptor.symbolicTraits.contains(trait) {
            let existingTraitsWithNewTrait = UIFontDescriptorSymbolicTraits(rawValue: fontDescriptor.symbolicTraits.rawValue & ~trait.rawValue)
            changedFontDescriptor = fontDescriptor.withSymbolicTraits(existingTraitsWithNewTrait)
        } else {
            changedFontDescriptor = fontDescriptor.withSymbolicTraits(UIFontDescriptorSymbolicTraits(rawValue: fontDescriptor.symbolicTraits.rawValue | trait.rawValue))
        }

        let updatedFont = UIFont(descriptor: changedFontDescriptor , size: 0)

        let newAttributes = [NSFontAttributeName: updatedFont]
        textView.textStorage.beginEditing()
        textView.textStorage.setAttributes(newAttributes, range: range)
        textView.textStorage.endEditing()
 }

INVOKE:

FOR BOLD:  changeTrait(trait: .traitBold)

FOR ITALIC: changeTrait(trait: .traitItalic)


问:
In JMeter how can I capture multiple (varying) values of a regular expression?
I need to parse a html page that can contain multiple (unspecified how many) links.
Here an example (pseudo html):

```<code><a href="../entrygroups/GROUPIDENTIFIER/3">edit</a>
[...]
<a href="../entrygroups/GROUPIDENTIFIER/7">edit</a>
[...]
<a href="../entrygroups/GROUPIDENTIFIER/12">edit</a>
[...]
<a href="../entrygroups/GROUPIDENTIFIER/16">edit</a>
</code>```

I am basically just interested in the numbers 3,7,12,16 of the url.

Is there a way to put those values into some sort of array and loop over them (in a for each kind of way).

Is this possible and if so, how would I do this?
I looked at the regular expression extractor but it seems that that one can only assign a fixed set of groups to a fixed set of variables.

答:
Extract the values using Regular Expression Extractor configured like:

Reference Name: anything meaningful, i.e. edit

Regular Expression: edit

Template: $1

Match No: -1

Add ForEach Controller configured like:

Input variable prefix: edit (or whatever you used as the Regular Expression Extractor Reference Name)

Output variable prefix: again anything meaningful, i.e. current_edit

Put the sampler(s) you need under the ForEach Controller

Refer the "GROUPIDENTIFIER" value as ${current_edit} where required

See Using Regular Expressions in JMeter guide for another example of looping through all links found in the page with the Regular Expression Extractor and ForEach Controller.

Body:
I need to parse a html page that can contain multiple (unspecified how many) links.
Here an example (pseudo html):

edit
[...]
edit
[...]
edit
[...]
edit

I am basically just interested in the numbers 3,7,12,16 of the url.

Is there a way to put those values into some sort of array and loop over them (in a for each kind of way).

Is this possible and if so, how would I do this?
I looked at the regular expression extractor but it seems that that one can only assign a fixed set of groups to a fixed set of variables.

Body:
Extract the values using Regular Expression Extractor configured like:

Reference Name: anything meaningful, i.e. edit

Regular Expression: <a href="../entrygroups/GROUPIDENTIFIER/(.+?)">edit</a>

Template: $1

Match No: -1

Add ForEach Controller configured like:

Input variable prefix: edit (or whatever you used as the Regular Expression Extractor Reference Name)

Output variable prefix: again anything meaningful, i.e. current_edit

Put the sampler(s) you need under the ForEach Controller

Refer the "GROUPIDENTIFIER" value as ${current_edit} where required

See Using Regular Expressions in JMeter guide for another example of looping through all links found in the page with the Regular Expression Extractor and ForEach Controller.


答:
The reason is that inside your each loop, this is not scoped for the current element being iterated.

In JQuery.each(),
The variable you use as a is the iteration index
The Variable you use as b is the current iterated element.

If you want to log the current iterated element, use b instead of this:

```<code>$.each(arr,function(a,b){
    console.log(b);
                ▲
})
</code>```

Title: The jquery $.each function console.log(this) ,prints result is string like "a" 'b' 'c'

Body:
The reason is that inside your each loop, this is not scoped for the current element being iterated.

In JQuery.each(),
The variable you use as a is the iteration index
The Variable you use as b is the current iterated element.

If you want to log the current iterated element, use b instead of this:

$.each(arr,function(a,b){
    console.log(b);
                ▲
})


问:
simple authorisation / login capability in php
I'm looking to implement user login onto my site for the first time.  I'm happy to either build my own solution, or implement something open source, however no package has been an obvious choice in my search so far.  Equally, I'm fully aware that as an intermediate php programmer at best, I am highly likely to miss something obvious if I roll my own solution, and leave the doors well and truly open.

Any suggestions?  We're not talking super sensitive or payment data here, but equally, I'm keen not to have people mess up my site!

requirements are
- php based
- simple as possible, not need for fancy bells and whistles
- not Zend framework, since i've now rolled my own very basic frameworkthanks to this post

Thanks for your input.

答:
"You'll put your eye out kid."

Security is hard. I hate to say this, but the odds of you making a simple authorization scheme that is secure are quite slim. There is no easy mode here. So you might want to start by reading through a bunch of authentication code in the various frameworks/cmses, and other places where you can see how others have done it, and begin researching.

Here are some links:
http://www.topmost.se/personal/articles/casual-cryptography-for-web-developers.htm
http://pear.php.net/packages.php?catpid=1

OwnerDisplayName: Rob Y

ContentLicense: CC BY-SA 2.5


问:
AliasToBeanResultTransformer and Hibernate SQLQuery
I have a rather complex query (too many nested levels for either HQL or Criteria queries), so I've written it as a SQLQuery.  I'd really like to use the AliasToBeanResultTransformer to transform my results into a List, but I'm having some issues.  I've included code snippets below of what I've got right now.

When I log the results for the transformed query, I can see that the transformer does create a List, however, all the fields in each AdvancedClauseSearchResultDTO are null.  I assume that means that I'm doing something wrong with aliasing ... that the AliasToBeanResultTransformer can't find the correct setters to call.   However, the AdvancedClauseSearchResultDTO class does have public setters for each of the columns that I've aliased in my sql string.  If this was a Criteria query, I'd use projections to define an alias for each column to be returned, but I'm unsure of how to accomplish the same thing using a SQLQuery.

Any advice on how to get the aliases set so that the ResultTransformer can use them? I've seen some limited documentation that suggested that using the 'as aliasName' method should work, but it doesn't seem to be for me.

Beginning snippet of query string definition, note the 'as' alias definitions

```<code>StringBuffer clauseBaseQuery = new StringBuffer();
        clauseBaseQuery.append("select ");
        clauseBaseQuery.append(" clauseDetail.clause_detail_id as clauseDetailId,");
        clauseBaseQuery.append(" clauseDetail.clause_id as clauseId,");
        clauseBaseQuery.append(" providers.provider_name as provider, ");
        clauseBaseQuery.append(" products.product_name as product, ");
</code>```

SQLQuery creation & setting of resultTransformer

```<code>Query query  = session.createSQLQuery(clauseBaseQuery.toString());
query.setResultTransformer(new AdvancedClauseSearchResultTransformer());
return (List<AdvancedClauseSearchResultDTO>)query.list();
</code>```

AdvancedClauseSearchResultTransformer class (uses AliasToBeanResultTransformer and then does some extra processing):

```<code>class AdvancedClauseSearchResultTransformer implements ResultTransformer {

        //Use the aliasTransformer to do most of the work
        ResultTransformer aliasTransformer = Transformers.aliasToBean(AdvancedClauseSearchResultDTO.class);

        @Override
        public List transformList(List list) {
            log.debug("transforming CLAUSE results");
            List<AdvancedClauseSearchResultDTO> result = aliasTransformer.transformList(list);
            //for each row, set the status field
           for (AdvancedClauseSearchResultDTO dto : result) {
                log.debug("dto = " + dto);
                String status = null;
                Date effectiveDate = dto.getEffectiveDate();
                Date terminationDate = dto.getTerminationDate();
                Date now = new Date(System.currentTimeMillis());
                if (now.before(effectiveDate)) {
                    status = "Pending";
                } else if (now.after(terminationDate)) {
                    status = "Terminated";
                } else {
                    status = "Active";
                }
                dto.setStatus(status);

                if (StringUtils.isNotEmpty(dto.getReasonForAmendment())){
                    dto.setAmended(Boolean.TRUE);
                }else{
                    dto.setAmended(Boolean.FALSE);
                }
            }

            return result;
        }

        @Override
        public Object transformTuple(Object[] os, String[] strings) {
            Object result = aliasTransformer.transformTuple(os, strings);

            return result;
        }
    }
</code>```

答:
I think it is not a good method to write a result transformer to solve
your problem. Try something like this,

```<code>Query query  = session.createSQLQuery(clauseBaseQuery.toString());
query.setResultTransformer(Transformers.aliasToBean(AdvancedClauseSearchResultDTO.class));
</code>```

And in AdvancedClauseSearchResultDTO class, modify setter methods to set required
fields for you. For example,

```<code>class AdvancedClauseSearchResultDTO {
    private Date effectiveDate;

    private String status;
    .
    .

    public void getEffectiveDate() {
        return effectiveDate;
    }

    public void setEffectiveDate(Date aDate) {
                Date now = new Date(System.currentTimeMillis());
                if (now.before(effectiveDate)) {
                    this.status = "Pending";
                } else if (now.after(terminationDate)) {
                    this.status = "Terminated";
                } else {
                    this.status = "Active";
                }
        this.effectiveDate = aDate;
    }
}
</code>```

You got the idea...

Body:
I have a rather complex query (too many nested levels for either HQL or Criteria queries), so I've written it as a SQLQuery.  I'd really like to use the AliasToBeanResultTransformer to transform my results into a List, but I'm having some issues.  I've included code snippets below of what I've got right now.

When I log the results for the transformed query, I can see that the transformer does create a List, however, all the fields in each AdvancedClauseSearchResultDTO are null.  I assume that means that I'm doing something wrong with aliasing ... that the AliasToBeanResultTransformer can't find the correct setters to call.   However, the AdvancedClauseSearchResultDTO class does have public setters for each of the columns that I've aliased in my sql string.  If this was a Criteria query, I'd use projections to define an alias for each column to be returned, but I'm unsure of how to accomplish the same thing using a SQLQuery.

Any advice on how to get the aliases set so that the ResultTransformer can use them? I've seen some limited documentation that suggested that using the 'as aliasName' method should work, but it doesn't seem to be for me.

Beginning snippet of query string definition, note the 'as' alias definitions

StringBuffer clauseBaseQuery = new StringBuffer();
        clauseBaseQuery.append("select ");
        clauseBaseQuery.append(" clauseDetail.clause_detail_id as clauseDetailId,");
        clauseBaseQuery.append(" clauseDetail.clause_id as clauseId,");
        clauseBaseQuery.append(" providers.provider_name as provider, ");
        clauseBaseQuery.append(" products.product_name as product, ");

SQLQuery creation & setting of resultTransformer

Query query  = session.createSQLQuery(clauseBaseQuery.toString());
query.setResultTransformer(new AdvancedClauseSearchResultTransformer());
return (List<AdvancedClauseSearchResultDTO>)query.list();

AdvancedClauseSearchResultTransformer class (uses AliasToBeanResultTransformer and then does some extra processing):

class AdvancedClauseSearchResultTransformer implements ResultTransformer {

        //Use the aliasTransformer to do most of the work
        ResultTransformer aliasTransformer = Transformers.aliasToBean(AdvancedClauseSearchResultDTO.class);

        @Override
        public List transformList(List list) {
            log.debug("transforming CLAUSE results");
            List<AdvancedClauseSearchResultDTO> result = aliasTransformer.transformList(list);
            //for each row, set the status field
           for (AdvancedClauseSearchResultDTO dto : result) {
                log.debug("dto = " + dto);
                String status = null;
                Date effectiveDate = dto.getEffectiveDate();
                Date terminationDate = dto.getTerminationDate();
                Date now = new Date(System.currentTimeMillis());
                if (now.before(effectiveDate)) {
                    status = "Pending";
                } else if (now.after(terminationDate)) {
                    status = "Terminated";
                } else {
                    status = "Active";
                }
                dto.setStatus(status);

                if (StringUtils.isNotEmpty(dto.getReasonForAmendment())){
                    dto.setAmended(Boolean.TRUE);
                }else{
                    dto.setAmended(Boolean.FALSE);
                }
            }

            return result;
        }

        @Override
        public Object transformTuple(Object[] os, String[] strings) {
            Object result = aliasTransformer.transformTuple(os, strings);

            return result;
        }
    }

Body:
I think it is not a good method to write a result transformer to solve
your problem. Try something like this,

Query query  = session.createSQLQuery(clauseBaseQuery.toString());
query.setResultTransformer(Transformers.aliasToBean(AdvancedClauseSearchResultDTO.class));

And in AdvancedClauseSearchResultDTO class, modify setter methods to set required
fields for you. For example,

class AdvancedClauseSearchResultDTO {
    private Date effectiveDate;

    private String status;
    .
    .

    public void getEffectiveDate() {
        return effectiveDate;
    }

    public void setEffectiveDate(Date aDate) {
                Date now = new Date(System.currentTimeMillis());
                if (now.before(effectiveDate)) {
                    this.status = "Pending";
                } else if (now.after(terminationDate)) {
                    this.status = "Terminated";
                } else {
                    this.status = "Active";
                }
        this.effectiveDate = aDate;
    }
}

You got the idea...


问:
Create ZIP Files and Deploy as GitHub-Release on AppVeyor
I wan't to create ZIP Files on AppVeyor to publish it on GitHub as an Release.

Currently, the Build-Process make following Steps:

Install Node.js v7

Start the .\Build-All.bat

The Bild.bat has following Steps:

Create Temp and Build Directory

Move Source to Temp

Install depencies with npm install

Start electron-packager to create binary files (See directory structure of /Build/ directory)

Directory Structure:

```<code>/Source/
/Build/
  L /DSTEd-darwin-x64/
  L /DSTEd-linux-armv7l/
  L /DSTEd-linux-ia32/
  L /DSTEd-linux-x64/
  L /DSTEd-mas-x64/
  L /DSTEd-win32-ia32/
  L /DSTEd-win32-x64/
/Temp/
/Build.bat
</code>```

Here is that, what i want:

Package each Build-Directory (for sample /Build/DSTEd-win32-x64/) to an ZIP-Archive like /Build/DSTEd-win32-x64.zip

Add all ZIP-Archives (/Build/DSTEd-*-*.zip) to the release

I had created manually a Release on GitHub for sample; That is, what i want:
 https://github.com/DST-Tools/DSTEd/releases/tag/1.0.0

Here is my appveyor.yml:

```<code>version: 1.0.0-{build}

# Set the Node Version
environment:
  matrix:
    - nodejs_version: "7"

# Install scripts. (runs after repo cloning)
install:
  - ps: Install-Product node $env:nodejs_version
  - npm -g install electron-packager
  - .\Build-All.bat

# Caching
cache:
  - node_modules

# Deployment Options
deploy:
  tag: $(appveyor_build_version)
  release: 'DSTEd v${appveyor_build_version} - Pre-Release (Preview)'
  description: ' ![Preview](https://github.com/DST-Tools/DSTEd/raw/master/Screenshots/preview.png)  ## Pre-Release v1.0.0 (Preview) Builded binarys for `Windows` (`32bit` & `64bit`), `Linux` (`32bit`, `64bit` & `armv7`) and `Mac OS X` (`darwin` & `mas`, only `64bit`).'
  provider: GitHub
  auth_token:
    secure: b202f536350628ff69af69d08daee9f76a9cff20
  artifact: '**\*.zip'
  draft: false
  prerelease: true
  on:
    branch: master
    appveyor_repo_tag: true

matrix:
  fast_finish: true

build: OFF
test: OFF
</code>```

答:
The packaging artifacts is very complex. By the docs, you can define filters there won't work correctly.

I've implement a own solution to trigger the before_deploy. Before the deployment-phase starts, a Script package the Files as ZIP and add these as an Artifact:

```<code># Deployment Options
before_deploy:
  - node .\Tools\PackageBuild.js
  - ps: Get-ChildItem .\Build\*.zip | % { Push-AppveyorArtifact $_.FullName -FileName $_.Name }
</code>```

On the Deployment-Process we add all available artifacts to leave the property blank:

```<code>deploy:
  [...]
  artifact: #leave blank
</code>```

Body:
I wan't to create ZIP Files on AppVeyor to publish it on GitHub as an Release.

Currently, the Build-Process make following Steps:

Install Node.js v7

Start the .\Build-All.bat

The Bild.bat has following Steps:

Create Temp and Build Directory

Move Source to Temp

Install depencies with npm install

Start electron-packager to create binary files (See directory structure of /Build/ directory)

Directory Structure:

/Source/
/Build/
  L /DSTEd-darwin-x64/
  L /DSTEd-linux-armv7l/
  L /DSTEd-linux-ia32/
  L /DSTEd-linux-x64/
  L /DSTEd-mas-x64/
  L /DSTEd-win32-ia32/
  L /DSTEd-win32-x64/
/Temp/
/Build.bat

Here is that, what i want:

Package each Build-Directory (for sample /Build/DSTEd-win32-x64/) to an ZIP-Archive like /Build/DSTEd-win32-x64.zip

Add all ZIP-Archives (/Build/DSTEd-*-*.zip) to the release

I had created manually a Release on GitHub for sample; That is, what i want:
 https://github.com/DST-Tools/DSTEd/releases/tag/1.0.0

Here is my appveyor.yml:

version: 1.0.0-{build}

# Set the Node Version
environment:
  matrix:
    - nodejs_version: "7"

# Install scripts. (runs after repo cloning)
install:
  - ps: Install-Product node $env:nodejs_version
  - npm -g install electron-packager
  - .\Build-All.bat

# Caching
cache:
  - node_modules

# Deployment Options
deploy:
  tag: $(appveyor_build_version)
  release: 'DSTEd v${appveyor_build_version} - Pre-Release (Preview)'
  description: ' ![Preview](https://github.com/DST-Tools/DSTEd/raw/master/Screenshots/preview.png)  ## Pre-Release v1.0.0 (Preview) Builded binarys for `Windows` (`32bit` & `64bit`), `Linux` (`32bit`, `64bit` & `armv7`) and `Mac OS X` (`darwin` & `mas`, only `64bit`).'
  provider: GitHub
  auth_token:
    secure: b202f536350628ff69af69d08daee9f76a9cff20
  artifact: '**\*.zip'
  draft: false
  prerelease: true
  on:
    branch: master
    appveyor_repo_tag: true

matrix:
  fast_finish: true

build: OFF
test: OFF

Body:
The packaging artifacts is very complex. By the docs, you can define filters there won't work correctly.

I've implement a own solution to trigger the before_deploy. Before the deployment-phase starts, a Script package the Files as ZIP and add these as an Artifact:

# Deployment Options
before_deploy:
  - node .\Tools\PackageBuild.js
  - ps: Get-ChildItem .\Build\*.zip | % { Push-AppveyorArtifact $_.FullName -FileName $_.Name }

On the Deployment-Process we add all available artifacts to leave the property blank:

deploy:
  [...]
  artifact: #leave blank


问:
Storing API keys on the Realtime Database (Firebase)
My android app requires using the Google Place Search API but since it's not available for android, I'll have to call the Web API. I've considered using Cloud Functions but that's too expensive and can be done for a lot less if done locally on each client. The problem is storing the API key on the user's devices as it can be easily retrieved. Thus is it safe if I store the key on the RT DB and reference it only when needed?

Also, if you have suggestions, I'd me more than happy to implement them :D

答:
Google Places APIs are available for android.

Sample Code

```<code>public void findPlace(View view) {
try {
    Intent intent =
            new PlaceAutocomplete.IntentBuilder(PlaceAutocomplete.MODE_FULLSCREEN)
                    .setFilter(typeFilter)
                    .build(this);
        startActivityForResult(intent, PLACE_AUTOCOMPLETE_REQUEST_CODE);
    } catch (GooglePlayServicesRepairableException e) {
        // TODO: Handle the error.
    } catch (GooglePlayServicesNotAvailableException e) {
        // TODO: Handle the error.
    }
}

// A place has been received; use requestCode to track the request.
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    if (requestCode == PLACE_AUTOCOMPLETE_REQUEST_CODE) {
        if (resultCode == RESULT_OK) {
            Place place = PlaceAutocomplete.getPlace(this, data);
            Log.i(TAG, "Place: " + place.getName());
        } else if (resultCode == PlaceAutocomplete.RESULT_ERROR) {
            Status status = PlaceAutocomplete.getStatus(this, data);
            // TODO: Handle the error.
            Log.i(TAG, status.getStatusMessage());

        } else if (resultCode == RESULT_CANCELED) {
            // The user canceled the operation.
        }
    }
}
</code>```

Complete tutorial is available here.

Body:
Google Places APIs are available for android.

Sample Code

public void findPlace(View view) {
try {
    Intent intent =
            new PlaceAutocomplete.IntentBuilder(PlaceAutocomplete.MODE_FULLSCREEN)
                    .setFilter(typeFilter)
                    .build(this);
        startActivityForResult(intent, PLACE_AUTOCOMPLETE_REQUEST_CODE);
    } catch (GooglePlayServicesRepairableException e) {
        // TODO: Handle the error.
    } catch (GooglePlayServicesNotAvailableException e) {
        // TODO: Handle the error.
    }
}

// A place has been received; use requestCode to track the request.
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    if (requestCode == PLACE_AUTOCOMPLETE_REQUEST_CODE) {
        if (resultCode == RESULT_OK) {
            Place place = PlaceAutocomplete.getPlace(this, data);
            Log.i(TAG, "Place: " + place.getName());
        } else if (resultCode == PlaceAutocomplete.RESULT_ERROR) {
            Status status = PlaceAutocomplete.getStatus(this, data);
            // TODO: Handle the error.
            Log.i(TAG, status.getStatusMessage());

        } else if (resultCode == RESULT_CANCELED) {
            // The user canceled the operation.
        }
    }
}

Complete tutorial is available here.