问:
React-redux : listening to state changes to trigger action
I have my redux state like this:

```<code>{
  parks: [
    {
      _id:"ad1esdad",
      fullName : "Some Name"
    },
    {
      _id:"ad1es3s",
      fullName : "Some Name2"
    }
  ],
  parkInfo: {
    id : "search Id",
    start_time : "Some Time",
    end_time : "Some Time"
  }
}
</code>```

I have a parkSelector component from which a user selects parkId and start_time and end_time

```<code>import React, { Component } from 'react';
import { changeParkInfo } from '../../Actions';

class ParkSelector extends Component {

  constructor(props) {
    super(props);

    this.handleApply = this.handleApply.bind(this);
    this.rederOptions = this.rederOptions.bind(this);

    this.state = {
      startDate: moment().subtract(1, 'days'),
      endDate: moment(),
      parkId : this.props.parks[0]
    };
  }

  handleApply(event) {
    this.setState({
      parkId : event.target.parkId.value
      startDate: event.target.start_time.value,
      endDate: event.target.end_time.value,
    });
    this.props.changeParkInfo(this.state.parkId,this.state.startDate,this.state.endDate);
  }

  rederOptions(){
    return _.map(this.props.parks,(park,index)=>{
      return(
        <option value={park._id} key={park._id}>{park.profile.fullName}</option>
      );
    });
  }

  render() {

    return (
      <div className="row">
        <div className="pb-4 col-sm-3">
          <form onSubmit={this.handleApply}>
          <select name="parkId" value={this.state.parkId} className="form-control input-sm">
              {this.rederOptions()}
          </select>
          <input name="start_time" type="date" />
          <input name="end_time" type="date" />
          <button type="submit">Apply</button>
          </form>
        </div>
      </div>
    )
  }
}

function mapStateToProps(state){
  return {
    parks : state.parks
  };
}

export default connect(mapStateToProps,{ changeParkInfo })(ParkSelector);
</code>```

I have another component 'stats' which needs to displays information related with parkInfo which will be loaded my api request.

```<code>import React, { Component } from 'react';
import StatsCard from '../../components/StatsCard';
import { getDashboardStats } from '../../Actions';

class Dashboard extends Component {

  constructor(props) {
    super(props);
  }

  render() {

    return (
      <div className="animated fadeIn">
        <div className="row">
          <StatsCard text="Revenue Collected" value={9999} cardStyle="card-success" />
          <StatsCard text="Total Checkins" value={39} cardStyle="card-info" />
          <StatsCard text="Total Checkouts" value={29} cardStyle="card-danger" />
          <StatsCard text="Passes Issued" value={119} cardStyle="card-warning" />
        </div>

      </div>
    )
  }
}

function mapStateToProps(state){
  return {
    parkInfo : state.parkInfo,
    dashboardStats : state.dashboardStats
  };
}

export default connect(mapStateToProps,{ getDashboardStats })(Dashboard);
</code>```

I need to call getDashboardStats action (which makes api call and stores in results in dashboardStats of the redux state) whenever the redux state of parkInfo changes.

What is the best way to call this action, I have tried componentWillUpdate but it keeps on updating infinitely. What is best practice for this scenario ?

答:
If my understanding is correct, you need to make the API call to get the dashboardStats in your Dashboard component, whenever the parkInfo changes.

The correct life-cycle hook in this scenario would be the componentWillReceiveProps

```<code>    componentWillReceiveProps(nextProps){
         // this check makes sure that the getDashboardStats action is not getting called for other prop changes
         if(this.props.parkInfo !== nextProps.parkInfo){
              this.props.getDashboardStats()
         }
    }
</code>```

Also note that, componentWillReceiveProps will not be called for the first time, so you may have to call the this.props.getDashboardStats() in componentDidMount too.

Body:
I have my redux state like this:

{
  parks: [
    {
      _id:"ad1esdad",
      fullName : "Some Name"
    },
    {
      _id:"ad1es3s",
      fullName : "Some Name2"
    }
  ],
  parkInfo: {
    id : "search Id",
    start_time : "Some Time",
    end_time : "Some Time"
  }
}

I have a parkSelector component from which a user selects parkId and start_time and end_time

import React, { Component } from 'react';
import { changeParkInfo } from '../../Actions';

class ParkSelector extends Component {

  constructor(props) {
    super(props);

    this.handleApply = this.handleApply.bind(this);
    this.rederOptions = this.rederOptions.bind(this);

    this.state = {
      startDate: moment().subtract(1, 'days'),
      endDate: moment(),
      parkId : this.props.parks[0]
    };
  }

  handleApply(event) {
    this.setState({
      parkId : event.target.parkId.value
      startDate: event.target.start_time.value,
      endDate: event.target.end_time.value,
    });
    this.props.changeParkInfo(this.state.parkId,this.state.startDate,this.state.endDate);
  }

  rederOptions(){
    return _.map(this.props.parks,(park,index)=>{
      return(
        <option value={park._id} key={park._id}>{park.profile.fullName}</option>
      );
    });
  }

  render() {

    return (

          <form onSubmit={this.handleApply}>
          <select name="parkId" value={this.state.parkId} className="form-control input-sm">
              {this.rederOptions()}
          </select>
          <input name="start_time" type="date" />
          <input name="end_time" type="date" />
          <button type="submit">Apply</button>
          </form>

    )
  }
}

function mapStateToProps(state){
  return {
    parks : state.parks
  };
}

export default connect(mapStateToProps,{ changeParkInfo })(ParkSelector);

I have another component 'stats' which needs to displays information related with parkInfo which will be loaded my api request.

import React, { Component } from 'react';
import StatsCard from '../../components/StatsCard';
import { getDashboardStats } from '../../Actions';

class Dashboard extends Component {

  constructor(props) {
    super(props);
  }

  render() {

    return (

          <StatsCard text="Revenue Collected" value={9999} cardStyle="card-success" />
          <StatsCard text="Total Checkins" value={39} cardStyle="card-info" />
          <StatsCard text="Total Checkouts" value={29} cardStyle="card-danger" />
          <StatsCard text="Passes Issued" value={119} cardStyle="card-warning" />

    )
  }
}

function mapStateToProps(state){
  return {
    parkInfo : state.parkInfo,
    dashboardStats : state.dashboardStats
  };
}

export default connect(mapStateToProps,{ getDashboardStats })(Dashboard);

I need to call getDashboardStats action (which makes api call and stores in results in dashboardStats of the redux state) whenever the redux state of parkInfo changes.

What is the best way to call this action, I have tried componentWillUpdate but it keeps on updating infinitely. What is best practice for this scenario ?

Body:
If my understanding is correct, you need to make the API call to get the dashboardStats in your Dashboard component, whenever the parkInfo changes.

The correct life-cycle hook in this scenario would be the componentWillReceiveProps

    componentWillReceiveProps(nextProps){
         // this check makes sure that the getDashboardStats action is not getting called for other prop changes
         if(this.props.parkInfo !== nextProps.parkInfo){
              this.props.getDashboardStats()
         }
    }

Also note that, componentWillReceiveProps will not be called for the first time, so you may have to call the this.props.getDashboardStats() in componentDidMount too.


来源: stackexchange

问:
psql cant connect to PostgreSQL server (postmaster) on IP and port 5432?
Please read before replying it as duplicate (as it perhaps can happen). I am running my postmaster (postgres) server. See below for 'sudo netstat -anp|grep 5432' output?

```<code>tcp  0  0 127.0.0.1:5432    0.0.0.0:*     LISTEN      29606/postmaster
unix  2      [ ACC ]     STREAM     LISTENING     1650581 29606/postmaster /var/run/postgresql/.s.PGSQL.5432
unix  2      [ ACC ]     STREAM     LISTENING     1650582 29606/postmaster    /tmp/.s.PGSQL.5432
</code>```

I am able to connect from localhost using

```<code>psql -h localhost (OR 127.0.0.1) -d <DB> -U user -W
</code>```

But when I try to connect from other hosts using tcp, by specifying

```<code>psql -h ip_add_postmaster -d <DB> -U user -W
</code>```

It throws:

psql: could not connect to server: Connection refused
  Is the server running on host XXXXXX and accepting TCP/IP connections on port 5432?

What's wrong here?

```<code>pg_hba.conf

# TYPE  DATABASE        USER            ADDRESS                 METHOD

# "local" is for Unix domain socket connections only
local   all             all                                     peer
# IPv4 local connections:
host    all             all             127.0.0.1/32            md5
# IPv6 local connections:
host    all             all             ::1/128                 md5
</code>```

In postgresql.conf,

```<code>listen_addresses = 'localhost, 127.0.0.1, ip_add_postmaster'

Note: ip_add_postmaster is same as my Elastic IP and not public DNS. If this information
matters.
</code>```

What am I doing wrong here? Machine is hosted on Amazon EC2 and have open the port 5432.

答:
I ran into this issue and tried all sorts of fixes I found across SO, and want to add a simple solution that worked for me after realizing it had to do with permissions in my case.

Simply, if you're running a psql server on Windows, you are initially restricted to the default postgres superuser for logging in, launching the server, and so on.

So, first try running from the command line:
psql -U postgres -h localhost -p 5432
and enter your password at the prompt. If you've managed to login and the server is up, then it was a permissions issues. From here, you can create a role for yourself that has login privileges to whatever database you are trying to run.

If the error persists, then consider checking postgresql.conf as mentioned above, to make sure default IP is set to * or localhost, and the port set to 5432 or whatever port you want as default.

ContentLicense: CC BY-SA 3.0

Body:
Please read before replying it as duplicate (as it perhaps can happen). I am running my postmaster (postgres) server. See below for 'sudo netstat -anp|grep 5432' output?

tcp  0  0 127.0.0.1:5432    0.0.0.0:*     LISTEN      29606/postmaster
unix  2      [ ACC ]     STREAM     LISTENING     1650581 29606/postmaster /var/run/postgresql/.s.PGSQL.5432
unix  2      [ ACC ]     STREAM     LISTENING     1650582 29606/postmaster    /tmp/.s.PGSQL.5432

I am able to connect from localhost using

psql -h localhost (OR 127.0.0.1) -d <DB> -U user -W

But when I try to connect from other hosts using tcp, by specifying

psql -h ip_add_postmaster -d <DB> -U user -W

It throws:

psql: could not connect to server: Connection refused
  Is the server running on host XXXXXX and accepting TCP/IP connections on port 5432?

What's wrong here?

pg_hba.conf

# TYPE  DATABASE        USER            ADDRESS                 METHOD

# "local" is for Unix domain socket connections only
local   all             all                                     peer
# IPv4 local connections:
host    all             all             127.0.0.1/32            md5
# IPv6 local connections:
host    all             all             ::1/128                 md5

In postgresql.conf,

listen_addresses = 'localhost, 127.0.0.1, ip_add_postmaster'

Note: ip_add_postmaster is same as my Elastic IP and not public DNS. If this information
matters.

What am I doing wrong here? Machine is hosted on Amazon EC2 and have open the port 5432.


问:
java.net.ProtocolException: Unexpected status line: <!DOCTYPE HTML PUBLIC "-//IETF//DTD HTML 2.0//EN">
I am new to Java and Android programming, I'm trying to get the result of a PHP file on my server but I get the following exception:

```<code>java.net.ProtocolException: Unexpected status line: <!DOCTYPE HTML PUBLIC "-//IETF//DTD HTML 2.0//EN">
07-10 11:18:54.112 24683-25081/it.codesnippet.dots W/System.err:     at com.android.okhttp.internal.http.StatusLine.parse(StatusLine.java:54)
07-10 11:18:54.112 24683-25081/it.codesnippet.dots W/System.err:     at com.android.okhttp.internal.http.HttpConnection.readResponse(HttpConnection.java:191)
07-10 11:18:54.112 24683-25081/it.codesnippet.dots W/System.err:     at com.android.okhttp.internal.http.HttpTransport.readResponseHeaders(HttpTransport.java:80)
07-10 11:18:54.112 24683-25081/it.codesnippet.dots W/System.err:     at com.android.okhttp.internal.http.HttpEngine.readNetworkResponse(HttpEngine.java:905)
07-10 11:18:54.112 24683-25081/it.codesnippet.dots W/System.err:     at com.android.okhttp.internal.http.HttpEngine.readResponse(HttpEngine.java:789)
07-10 11:18:54.112 24683-25081/it.codesnippet.dots W/System.err:     at com.android.okhttp.internal.huc.HttpURLConnectionImpl.execute(HttpURLConnectionImpl.java:443)
07-10 11:18:54.112 24683-25081/it.codesnippet.dots W/System.err:     at com.android.okhttp.internal.huc.HttpURLConnectionImpl.getResponse(HttpURLConnectionImpl.java:388)
07-10 11:18:54.112 24683-25081/it.codesnippet.dots W/System.err:     at com.android.okhttp.internal.huc.HttpURLConnectionImpl.getInputStream(HttpURLConnectionImpl.java:231)
07-10 11:18:54.112 24683-25081/it.codesnippet.dots W/System.err:     at it.codesnippet.dots.LoginActivity$1$override.run(LoginActivity.java:49)
07-10 11:18:54.112 24683-25081/it.codesnippet.dots W/System.err:     at it.codesnippet.dots.LoginActivity$1$override.access$dispatch(LoginActivity.java)
07-10 11:18:54.112 24683-25081/it.codesnippet.dots W/System.err:     at it.codesnippet.dots.LoginActivity$1.run(LoginActivity.java:0)
07-10 11:18:54.112 24683-25081/it.codesnippet.dots W/System.err:     at java.lang.Thread.run(Thread.java:818)
</code>```

This is the code (in LoginActivity.java) where the exception comes from:

```<code>Thread loginCheckThread = new Thread(new Runnable() {
    public void run() {
        String result = "", dataObj = "";
        TextView username = (TextView) findViewById(R.id.login_mail);
        TextView password = (TextView) findViewById(R.id.login_password);

        JSONObject jsonObj = new JSONObject();
        try {
            jsonObj.put("loginMail", username.getText());
            jsonObj.put("loginPassword", password.getText());
            dataObj = jsonObj.toString(0);
        } catch (JSONException e) {
            e.printStackTrace();
        }

        try {
            URL url = new URL("http://myserver.it/testandroid.php?data=" + dataObj);
            HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();

            try {
/* line #49 */  InputStream in = new BufferedInputStream(urlConnection.getInputStream());
                ByteArrayOutputStream bo = new ByteArrayOutputStream();
                int i = in.read();
                while (i != -1) {
                    bo.write(i);
                    i = in.read();
                }
                result = bo.toString();
            } catch (IOException e) {
                result = "Exception: Class::IOStream Related";
                e.printStackTrace();

            } finally {
                urlConnection.disconnect();
            }
        } catch (IOException e) {
            result = "Exception: Class::URL Related";
        }

        System.out.println(result);
    }
});
loginCheckThread.start();
</code>```

The line which causes the exception is line #49:

```<code>InputStream in = new BufferedInputStream(urlConnection.getInputStream());
</code>```

The PHP file is just a test file for now and is supposed to return <input_username> - <input_password> retrieved from the data variable in the query string:

```<code>$jsonObj = json_decode($_GET["data"], TRUE);

echo $jsonObj["loginMail"] . " - " . $jsonObj["loginPassword"];
</code>```

Is about two days that this problem blocked me, what can I do to solve this?

答:
Important

To anyone who has this error in you Volley HTTP implementation:

```<code>java.net.ProtocolException: Unexpected status line: <!DOCTYPE HTML PUBLIC “-//IETF//DTD HTML 2.0//EN”>
</code>```

Please check and use OkHttp Dependency for solve it. Here the documentation to check.

In my case (I don't know why), my Android Test Phone (MOTO E V.4.4.4 Kitkat) was getting me back the java.net.ProtocolException: Unexpected status line exception. I tried to reset the phone and deleting the app, and nothing works.

For the other side, my Nexus 5X (With Android Oreo) was working good (same app, same network, same backend).

Please (really) try the OkHttp dependency and it gonna work.

Psd: Some stackoverflow threads says about Volley Cache or something like that, tried everything in my own, but OkHttp solved my trouble.

Body:
I am new to Java and Android programming, I'm trying to get the result of a PHP file on my server but I get the following exception:

java.net.ProtocolException: Unexpected status line: <!DOCTYPE HTML PUBLIC "-//IETF//DTD HTML 2.0//EN">
07-10 11:18:54.112 24683-25081/it.codesnippet.dots W/System.err:     at com.android.okhttp.internal.http.StatusLine.parse(StatusLine.java:54)
07-10 11:18:54.112 24683-25081/it.codesnippet.dots W/System.err:     at com.android.okhttp.internal.http.HttpConnection.readResponse(HttpConnection.java:191)
07-10 11:18:54.112 24683-25081/it.codesnippet.dots W/System.err:     at com.android.okhttp.internal.http.HttpTransport.readResponseHeaders(HttpTransport.java:80)
07-10 11:18:54.112 24683-25081/it.codesnippet.dots W/System.err:     at com.android.okhttp.internal.http.HttpEngine.readNetworkResponse(HttpEngine.java:905)
07-10 11:18:54.112 24683-25081/it.codesnippet.dots W/System.err:     at com.android.okhttp.internal.http.HttpEngine.readResponse(HttpEngine.java:789)
07-10 11:18:54.112 24683-25081/it.codesnippet.dots W/System.err:     at com.android.okhttp.internal.huc.HttpURLConnectionImpl.execute(HttpURLConnectionImpl.java:443)
07-10 11:18:54.112 24683-25081/it.codesnippet.dots W/System.err:     at com.android.okhttp.internal.huc.HttpURLConnectionImpl.getResponse(HttpURLConnectionImpl.java:388)
07-10 11:18:54.112 24683-25081/it.codesnippet.dots W/System.err:     at com.android.okhttp.internal.huc.HttpURLConnectionImpl.getInputStream(HttpURLConnectionImpl.java:231)
07-10 11:18:54.112 24683-25081/it.codesnippet.dots W/System.err:     at it.codesnippet.dots.LoginActivity$1$override.run(LoginActivity.java:49)
07-10 11:18:54.112 24683-25081/it.codesnippet.dots W/System.err:     at it.codesnippet.dots.LoginActivity$1$override.access$dispatch(LoginActivity.java)
07-10 11:18:54.112 24683-25081/it.codesnippet.dots W/System.err:     at it.codesnippet.dots.LoginActivity$1.run(LoginActivity.java:0)
07-10 11:18:54.112 24683-25081/it.codesnippet.dots W/System.err:     at java.lang.Thread.run(Thread.java:818)

This is the code (in LoginActivity.java) where the exception comes from:

Thread loginCheckThread = new Thread(new Runnable() {
    public void run() {
        String result = "", dataObj = "";
        TextView username = (TextView) findViewById(R.id.login_mail);
        TextView password = (TextView) findViewById(R.id.login_password);

        JSONObject jsonObj = new JSONObject();
        try {
            jsonObj.put("loginMail", username.getText());
            jsonObj.put("loginPassword", password.getText());
            dataObj = jsonObj.toString(0);
        } catch (JSONException e) {
            e.printStackTrace();
        }

        try {
            URL url = new URL("http://myserver.it/testandroid.php?data=" + dataObj);
            HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();

            try {
/* line #49 */  InputStream in = new BufferedInputStream(urlConnection.getInputStream());
                ByteArrayOutputStream bo = new ByteArrayOutputStream();
                int i = in.read();
                while (i != -1) {
                    bo.write(i);
                    i = in.read();
                }
                result = bo.toString();
            } catch (IOException e) {
                result = "Exception: Class::IOStream Related";
                e.printStackTrace();

            } finally {
                urlConnection.disconnect();
            }
        } catch (IOException e) {
            result = "Exception: Class::URL Related";
        }

        System.out.println(result);
    }
});
loginCheckThread.start();

The line which causes the exception is line #49:

InputStream in = new BufferedInputStream(urlConnection.getInputStream());

The PHP file is just a test file for now and is supposed to return <input_username> - <input_password> retrieved from the data variable in the query string:

$jsonObj = json_decode($_GET["data"], TRUE);

echo $jsonObj["loginMail"] . " - " . $jsonObj["loginPassword"];

Is about two days that this problem blocked me, what can I do to solve this?

Body:
Important

To anyone who has this error in you Volley HTTP implementation:

java.net.ProtocolException: Unexpected status line: <!DOCTYPE HTML PUBLIC “-//IETF//DTD HTML 2.0//EN”>

Please check and use OkHttp Dependency for solve it. Here the documentation to check.

In my case (I don't know why), my Android Test Phone (MOTO E V.4.4.4 Kitkat) was getting me back the java.net.ProtocolException: Unexpected status line exception. I tried to reset the phone and deleting the app, and nothing works.

For the other side, my Nexus 5X (With Android Oreo) was working good (same app, same network, same backend).

Please (really) try the OkHttp dependency and it gonna work.

Psd: Some stackoverflow threads says about Volley Cache or something like that, tried everything in my own, but OkHttp solved my trouble.


问:
Define global environment variables from inside a stage
I have env vars defined in my environment directive at the top of the pipeline:

```<code>environment {
    var1 = 'sdfsdfdsf'
    var2 = 'sssssss'
}
</code>```

But there are some that I need to dynamically set or override in the stages. But if I use an environment{} directive in a stage the vars won't be accessible to other stages. Initially I thought I could define them all with default values in the top environment directive and overwrite them in the pipeline but this is the behavior I observed:

Define var in environment block

Try to overwrite in script{} block like: script {env.var1 = 'new value'}

The env is not overwritten

How can I change the envs?

答:
You can do it as follow:

Define var in stage environment { env.var1 = 'value' }

you can access same var in other stages and change value in environment { env.var1 = 'value2' }

```<code> pipeline {
  agent any
  environment {
     var1 = 'value'
  }

  stages {
     stage('Initialize') {
       steps {
        script {
        echo ("value : " + env.var1)
         }
       }
    }

    stage('build') {
      environment {
        var1 = 'value2'
       }
       steps {
        script {
          echo ("value : " + env.var1)
        }
      }
    }
  }
}
</code>```

Body:
I have env vars defined in my environment directive at the top of the pipeline:

environment {
    var1 = 'sdfsdfdsf'
    var2 = 'sssssss'
}

But there are some that I need to dynamically set or override in the stages. But if I use an environment{} directive in a stage the vars won't be accessible to other stages. Initially I thought I could define them all with default values in the top environment directive and overwrite them in the pipeline but this is the behavior I observed:

Define var in environment block

Try to overwrite in script{} block like: script {env.var1 = 'new value'}

The env is not overwritten

How can I change the envs?

Body:
You can do it as follow:

Define var in stage environment { env.var1 = 'value' }

you can access same var in other stages and change value in environment { env.var1 = 'value2' }

 pipeline {
  agent any
  environment {
     var1 = 'value'
  }

  stages {
     stage('Initialize') {
       steps {
        script {
        echo ("value : " + env.var1)
         }
       }
    }

    stage('build') {
      environment {
        var1 = 'value2'
       }
       steps {
        script {
          echo ("value : " + env.var1)
        }
      }
    }
  }
}


问:
Getting attributes from XML using c#
I have the following xml contents inside a string variable. i want to get the value of each attribute (JID) in the form of string.

Below is my xml

```<code>  <query xmlns="http://jabber.org/protocol/muc#admin">
  <item affiliation="member" jid="a@something.com" />
  <item affiliation="member" jid="b@something.com" />
  <item affiliation="member" jid="c@something.com" />
  <item affiliation="member" jid="d@something.com" />
  <item affiliation="member" jid="e@something.com" />
  <item affiliation="member" jid="f@something.com" />
  <item affiliation="member" jid="g@something.com" />
  <item affiliation="member" jid="h@something.com" />
  <item affiliation="member" jid="i@something.com" />
  <item affiliation="member" jid="j@something.com" />
  </query>
</code>```

Anyone please suggest some ideas to find this.
my expected output is like

```<code>   a@something.com
   b@something.com
   c@something.com
   d@something.com
   e@something.com
   f@something.com
</code>```

答:
```<code>DataSet dsXml = new DataSet();
dsXml.ReadXmlSchema(Server.MapPath("~/Temp") + "//" + FileName);
dsXml.ReadXml(Server.MapPath("~/Temp") + "//" + FileName, XmlReadMode.InferTypedSchema);
 if (!string.IsNullOrEmpty(dsXml.GetXml()))
{
  for (int i = 0; i < dsXml.Tables.Count; i++)
            {

lblInfo.Text = lblInfo.Text + dsXml.Tables["item"].Rows[i]["jid"].ToString()
           }
}
</code>```

Title: Getting attributes from XML using c#

Body:
I have the following xml contents inside a string variable. i want to get the value of each attribute (JID) in the form of string.

Below is my xml

  <query xmlns="http://jabber.org/protocol/muc#admin">
  <item affiliation="member" jid="a@something.com" />
  <item affiliation="member" jid="b@something.com" />
  <item affiliation="member" jid="c@something.com" />
  <item affiliation="member" jid="d@something.com" />
  <item affiliation="member" jid="e@something.com" />
  <item affiliation="member" jid="f@something.com" />
  <item affiliation="member" jid="g@something.com" />
  <item affiliation="member" jid="h@something.com" />
  <item affiliation="member" jid="i@something.com" />
  <item affiliation="member" jid="j@something.com" />
  </query>

Anyone please suggest some ideas to find this.
my expected output is like

   a@something.com
   b@something.com
   c@something.com
   d@something.com
   e@something.com
   f@something.com


问:
:: acting as delimiter in my csv file and spliting data
I have a django template where I have stored some tables and have written a function to export it to csv but when i am doing it some columns in my table have :: in them and csv is treating it as a delimiter and splitting the column there how can i prevent this from happening

my views.py

```<code>f = open("static/output.csv", "w")

f.write("Customer Name" + "," + "Status" + "," + "Product" + "," + "Operating System" + "," +"Server_Type" + "," + "Version"+"," +"Citrux_URL"+"," +"F5_URL"+","+"\n")

for c in custom:
    f.write(c.summarise()+"\n")
</code>```

my models.py

```<code>def summarise(self):
    s = ",".join([str(self.name), str(self.Status), str(self.Product),str(self.SSO),str(self.SSO_URL),str(self.JCES_URL),str(self.L3),str(self.PM))])
    return s
</code>```

答:
Use the csv writer to correctly handle special characters as delimiters. It is defined by the quoting argument of the csv_writer. In your case you can skip this attribute completely, as it will default to QUOTE_MINIMAL when not defined. Still added into the example for completeness.

Source:

```<code>import csv
with open('output.csv', 'w') as csvfile:
    writer = csv.writer(csvfile, delimiter=',', quoting=csv.QUOTE_MINIMAL)
    writer.writerow(["te,st:foo", "test:nope, yes", "nodelimiter"])
</code>```

output.csv:

```<code>"te,st:foo","test:nope, yes",nodelimiter
</code>```

CSV is automatically controlling when quotes should be generated by the writer and recognised by the reader. It can take on any of the QUOTE_* constants  and defaults to quote_minimal

QUOTE_MINIMAL Instructs writer objects to only quote those fields which contain special characters such as delimiter, quotechar or any of the characters in lineterminator.

NOTE You are passing a string, you need to pass a list of strings

```<code>def summarise(self):
    s = [str(self.name), str(self.Status), str(self.Product),str(self.SSO),str(self.SSO_URL),str(self.JCES_URL),str(self.L3),str(self.PM))]
    return s
</code>```

Body:
I have a django template where I have stored some tables and have written a function to export it to csv but when i am doing it some columns in my table have :: in them and csv is treating it as a delimiter and splitting the column there how can i prevent this from happening

my views.py

f = open("static/output.csv", "w")

f.write("Customer Name" + "," + "Status" + "," + "Product" + "," + "Operating System" + "," +"Server_Type" + "," + "Version"+"," +"Citrux_URL"+"," +"F5_URL"+","+"\n")

for c in custom:
    f.write(c.summarise()+"\n")

my models.py

def summarise(self):
    s = ",".join([str(self.name), str(self.Status), str(self.Product),str(self.SSO),str(self.SSO_URL),str(self.JCES_URL),str(self.L3),str(self.PM))])
    return s

Body:
Use the csv writer to correctly handle special characters as delimiters. It is defined by the quoting argument of the csv_writer. In your case you can skip this attribute completely, as it will default to QUOTE_MINIMAL when not defined. Still added into the example for completeness.

Source:

import csv
with open('output.csv', 'w') as csvfile:
    writer = csv.writer(csvfile, delimiter=',', quoting=csv.QUOTE_MINIMAL)
    writer.writerow(["te,st:foo", "test:nope, yes", "nodelimiter"])

output.csv:

"te,st:foo","test:nope, yes",nodelimiter

CSV is automatically controlling when quotes should be generated by the writer and recognised by the reader. It can take on any of the QUOTE_* constants  and defaults to quote_minimal

QUOTE_MINIMAL Instructs writer objects to only quote those fields which contain special characters such as delimiter, quotechar or any of the characters in lineterminator.

NOTE You are passing a string, you need to pass a list of strings

def summarise(self):
    s = [str(self.name), str(self.Status), str(self.Product),str(self.SSO),str(self.SSO_URL),str(self.JCES_URL),str(self.L3),str(self.PM))]
    return s


问:
Powershell get-content ignore quoted delimiter
Can powershell capture the delimiter of csv file correctly using get-content? By using get-content it will capture comma in the double quotation as delimiter too.
Example of file csv file data used:

Code of get-content tested:

```<code>$path1 = "C:\Users\Soung\Desktop\Datascreening\test1\testing.csv"
Get-Content $path1 | ForEach-Object {($_.Split($delimiter)).Count}
</code>```

Result:

Remarks: Tested using import-csv method however import-csv will capture the result until 4th columns same as the header, row 5 & 6 which contain more than 4 columns of data are unable to capture correctly. Need to use get-content as need to process large sizes of files.

答:
You should use Import-Csv cmdlet for that:

```<code>'"a,b",a,b' > test.txt
'"a,b",a,b' >> test.txt
Import-Csv test.txt
</code>```

If the problema is that the Import-Csv only read as much entries in each row as there are headers you can always specify headers with -Headers parameter:

```<code>Import-CSV -Header @('1','2','3','4','5','6')
</code>```

Body:
Can powershell capture the delimiter of csv file correctly using get-content? By using get-content it will capture comma in the double quotation as delimiter too.
Example of file csv file data used:

Code of get-content tested:

$path1 = "C:\Users\Soung\Desktop\Datascreening\test1\testing.csv"
Get-Content $path1 | ForEach-Object {($_.Split($delimiter)).Count}

Result:

Remarks: Tested using import-csv method however import-csv will capture the result until 4th columns same as the header, row 5 & 6 which contain more than 4 columns of data are unable to capture correctly. Need to use get-content as need to process large sizes of files.

Body:
You should use Import-Csv cmdlet for that:

'"a,b",a,b' > test.txt
'"a,b",a,b' >> test.txt
Import-Csv test.txt

If the problema is that the Import-Csv only read as much entries in each row as there are headers you can always specify headers with -Headers parameter:

Import-CSV -Header @('1','2','3','4','5','6')


问:
Not able to pass # in my password using autoIT
I am using Autoit for authentication window in chrome using selenium. My Password Contains special character, but # is not getting entered in my Password.

My password is " D#e$r@2016"

Could anyone please help.

答:
The following code may helps, # has special meaning in auto IT. so it should be escaped using braces.

Method 1: send(" D{#}e$r@2016")

If you send all characters as raw then set the flag value to 1. By default, the flag is 0.

Method 2: send(" D#e$r@2016",1)


问:
on Event Clicked issue
I'm using Bootstrap 4 Beta and JavaScript for my university project, I'm making some calendar event function. and I'm used Bootbox.js  for popup, my issue is When I click the calendar event alert is display but this alert cant customize ,I want to know how to added
 <button> text and etc for this alert, look my attached image, you can understand it

This is my script,

event

```<code> dp.events.list = [{
      start: "2017-12-20",
      end: "2017-12-28",
      id: "1",
         resource: "A",
      text: "Mahesh",
      backColor: "#70CB85",

    },
</code>```

click

```<code>dp.onEventClicked = function(args) {
 bootbox.alert(" " + args.e.text()); //Alert
};
</code>```

答:
As from their documentation:

An alert callback should not supply an argument; it will be ignored

If you want to pass a button you can use confirm:

```<code>bootbox.confirm({
    message: "This is a confirm with custom button text and color! Do you like it?",
    buttons: {
        confirm: {
            label: 'Yes',
            className: 'btn-success'
        },
        cancel: {
            label: 'No',
            className: 'btn-danger'
        }
    },
    callback: function (result) {
        // ...
    }
});
</code>```

Or use Dialog:

```<code>bootbox.dialog({ message: '<div class="text-center"><i class="fa fa-spin fa-spinner"></i> Loading...</div>' })
</code>```

Title: on Event Clicked issue

Body:
I'm using Bootstrap 4 Beta and JavaScript for my university project, I'm making some calendar event function. and I'm used Bootbox.js  for popup, my issue is When I click the calendar event alert is display but this alert cant customize ,I want to know how to added
 <button> text and etc for this alert, look my attached image, you can understand it

This is my script,

event

 dp.events.list = [{
      start: "2017-12-20",
      end: "2017-12-28",
      id: "1",
         resource: "A",
      text: "Mahesh",
      backColor: "#70CB85",

    },

click

dp.onEventClicked = function(args) {
 bootbox.alert(" " + args.e.text()); //Alert
};

Body:
As from their documentation:

An alert callback should not supply an argument; it will be ignored

If you want to pass a button you can use confirm:

bootbox.confirm({
    message: "This is a confirm with custom button text and color! Do you like it?",
    buttons: {
        confirm: {
            label: 'Yes',
            className: 'btn-success'
        },
        cancel: {
            label: 'No',
            className: 'btn-danger'
        }
    },
    callback: function (result) {
        // ...
    }
});

Or use Dialog:

bootbox.dialog({ message: '<div class="text-center"><i class="fa fa-spin fa-spinner"></i> Loading...</div>' })


问:
Smooth scroling RecyclerViews inside of a ScrollView
I want to implement scrolling of recycler views as one sheet, but unable to reach the desired behavior.
My layout structure is:

```<code><ScrollView
android:id="@+id/search_results_scroll"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:fillViewport="true"
android:isScrollContainer="false"
android:nestedScrollingEnabled="true"
android:scrollbars="none">

<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="vertical">

    <TextView
        style="@style/search_results_group_title"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="RecyclerView 1 Title" />

    <android.support.v7.widget.RecyclerView
        android:id="@+id/search_results_recycler"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" />

    <TextView
        style="@style/search_results_group_title"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="RecyclerView 1 Title" />

    <android.support.v7.widget.RecyclerView
        android:id="@+id/some_static_results_recycler"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:nestedScrollingEnabled="false" />

</LinearLayout>
</code>```

My first recycler fetching new portions of data, and when it's scrolled to the end, i want to show the rest items under it.

Tried at first to make it with NestedScrollView, but it's performance is unacceptable, so i want to stick to ScrollView. Different variations with parameters, custom layout managers, don't helped to reach the desired behavior.
As I understand, I need to stick to ScrollView scrollListener, and disable recyclers inner scrolling, but in that case i get only partly filled first recyclerView (6 items instead of 20), even if recyclerView has android:layout_height="wrap_content". I use LinearLayoutManagers with setAutoMeasureEnabled=true.
So my questions are:
- How to expand recyclerView height after new items added (that exceed the screen height)?
- How better to handle scroll in a such scenario?

Any help would be very appreciated.

答:
Thank you for suggested links with solutions!

Unfortunately, these methods doesn't solve the problem with scroll stuttering in recycler.

And when new portions of data inserted into the first recycler, everything work very slow, cause scrollView recalculate height of every child item when, its contents are changing (the same problem was in NestedScrollView).

And all RecyclerView efficiency is killed by inlining it inside ScrollView or NestedScrollView.

I solved this in another way:

I used one RecyclerView with sections inside of it. Achieved this with custom ViewHolder and custom adapter behavior.

With that approach my recycler works very smooth, and fast.

So my items structure in RecyclerView:

First TextView header

First dynamicly populated items section

Second TextView header

Second items section

TextView footer

For headers i declared custom ViewHolder:

```<code>protected class HeaderViewHolder extends BaseListAdapter.ViewHolder implements View.OnClickListener {
    View view;
    TextView textView;

    protected HeaderViewHolder(View v) {
        super(v);
        this.view = v;
        textView = this.view.findViewById(R.id.header_text);
        v.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        if (itemClickListener != null)
            itemClickListener.onItemClick(v, this.getLayoutPosition());
    }

    public View getView() {
        return this.view;
    }

    // Set custom header text
    public void setTitle(String title) {
        textView.setText(title);
    }

    // Hide or show title, if items section don't have any items
    public void setVisibility(int visibility) {
        textView.setVisibility(visibility);
    }
}
</code>```

Layout for header ViewHolder:

```<code><?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_gravity="center"
    android:orientation="vertical">

    <TextView
        android:id="@+id/search_header"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" />

</LinearLayout>
</code>```

CustomListAdapter to fill and manage recycler sections:

```<code>public class CustomListAdapter extends BaseListAdapter<RecyclerItem> {

    private static final int FOOTER_TYPE = 10;
    private static final int FIRST_HEADER_TYPE = 25;
    private static final int SECOND_HEADER_TYPE = 50;
    private static final int SECOND_ITEMS_TYPE = 100;

    private List<RecyclerItem> secondRecyclerItems = new ArrayList<>();

    public CustomListAdapter(List<RecyclerItem> items, Context context) {
        super(items, R.layout.first_recycler_item, context);
    }

    @Override
    public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        switch (viewType) {
            case FIRST_HEADER_TYPE:
            case SECOND_HEADER_TYPE:
                HeaderViewHolder holder = new HeaderViewHolder(View.inflate(parent.getContext(), R.layout.header_layout, null));
                holder.setTitle(parent.getResources().getString(viewType == FIRST_HEADER_TYPE ? R.string.first_header_title : R.string.second_header_title));
                return holder;

            case FOOTER_TYPE:
                return new HeaderViewHolder(View.inflate(parent.getContext(), R.layout.footer_layout, null));
            default:
                return super.onCreateViewHolder(parent, viewType);
        }
    }

    @Override
    public void onBindViewHolder(BaseListAdapter.ViewHolder holder, int position) {

        if (holder instanceof HeaderViewHolder) {
            if (position == 0) {
                ((HeaderViewHolder) holder).setVisibility(items.size() == 0 ? View.GONE : View.VISIBLE);
            } else if (position == super.getItemCount() + 1 || position == getItemCount() - 1) {
                ((HeaderViewHolder) holder).setVisibility(secondRecyclerItems.size() == 0 ? View.GONE : View.VISIBLE);
            }
            return;
        }

        RecyclerItem item = position <= items.size()
                ? items.get(position - 1)
                : secondRecyclerItems.get(position - (items.size() + 2));

        // Here you populate your items with data, load images, etc...
        // TextView title = holder.itemView.findViewById(R.id.first_recycler_item_title);
    }

    public void clearFirstRecyclerItems() {
        items.clear();
        notifyDataSetChanged();
    }

    public void clearSecondRecyclerItems() {
        secondRecyclerItems.clear();
        notifyDataSetChanged();
    }

    // Define separate collection for second recycler items. First recycler will be populated by default base adapter
    public void swapSecondRecyclerItems(List<RecyclerItem> list) {
        if (secondRecyclerItems != null) {
            secondRecyclerItems.clear();
            secondRecyclerItems.addAll(list);
        } else {
            secondRecyclerItems = new ArrayList<>();
            secondRecyclerItems.addAll(list);
        }
        notifyDataSetChanged();
    }

    // Handle items click, and skip clicks on headers
    public RecyclerItem getClickedItem(int position) {
        if (position == super.getItemCount() + 1 || position == 0 || position == getItemCount() - 1)
            return null;

        return position <= items.size()
                ? items.get(position - 1)
                : secondRecyclerItems.get(position - (items.size() + 2));
    }

    // That's the core method to split recycler items into sections, depending on their position
    @Override
    public int getItemViewType(int position) {
        if (position == 0) {
            return FIRST_HEADER_TYPE;
        } else if (position == super.getItemCount() + 1) {
            return SECOND_HEADER_TYPE;
        } else if (position == getItemCount() - 1) {
            return FOOTER_TYPE;
        } else if (position > super.getItemCount() + 1) {
            return SECOND_ITEMS_TYPE;
        }
        return super.getItemViewType(position);
    }

    // Redefine overall items quantity - super.getItemCount() (base recyclerAdapter items) + secondRecyclerItems + 3 (2 headers and 1 footer)
    @Override
    public int getItemCount() {
        return super.getItemCount() + secondRecyclerItems.size() + 3;
    }

    public int getFirstRecyclerItemsCount() {
        return super.getItemCount() + 1;
    }
}
</code>```

And for completeness BaseListAdapter:

```<code>public abstract class BaseListAdapter<T> extends RecyclerView.Adapter<BaseListAdapter.ViewHolder> {
    protected List<T> items;
    protected @android.support.annotation.LayoutRes int layout;
    protected Context context;
    protected OnItemClickListener itemClickListener;

    public BaseListAdapter(List<T> items, @android.support.annotation.LayoutRes int layout, Context context) {
        this.items = items;
        this.layout = layout;
        this.context = context;
    }

    public T getItem(int position) {
        return items.get(position);
    }

    public List<T> getItems() {
        return items;
    }

    public void setOnItemClickListener(OnItemClickListener onItemClickListener) {
        this.itemClickListener = onItemClickListener;
    }

    // Create new views (invoked by the layout manager)
    @Override
    public BaseListAdapter.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View v = LayoutInflater.from(parent.getContext()).inflate(layout, parent, false);

        return new ViewHolder(v);
    }

    // Return the size of your dataset (invoked by the layout manager)
    @Override
    public int getItemCount() {
        return items.size();
    }

    /**
     * Update the recycler view with a new dataset.
     * */
    public void swap(List<T> list){
        if(items != null) {
            items.clear();
            items.addAll(list);
        }
        else {
            items = new ArrayList<>();
            items.addAll(list);
        }
        notifyDataSetChanged();
    }

    public void add(List<T> list){
        items.addAll(list);
        notifyDataSetChanged();
    }

    protected class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {

        private View view;

        protected ViewHolder(View v) {
            super(v);
            this.view = v;
            v.setOnClickListener(this);
        }

        @Override
        public void onClick(View v) {
            if(itemClickListener != null)
                itemClickListener.onItemClick(v, this.getLayoutPosition());
        }

        public View getView() {
            return this.view;
        }
    }

    public interface OnItemClickListener
    {
        void onItemClick(View v, int position);
    }
}
</code>```

Hope it could help someone.

Body:
I want to implement scrolling of recycler views as one sheet, but unable to reach the desired behavior.
My layout structure is:

<ScrollView
android:id="@+id/search_results_scroll"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:fillViewport="true"
android:isScrollContainer="false"
android:nestedScrollingEnabled="true"
android:scrollbars="none">

<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="vertical">

    <TextView
        style="@style/search_results_group_title"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="RecyclerView 1 Title" />

    <android.support.v7.widget.RecyclerView
        android:id="@+id/search_results_recycler"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" />

    <TextView
        style="@style/search_results_group_title"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="RecyclerView 1 Title" />

    <android.support.v7.widget.RecyclerView
        android:id="@+id/some_static_results_recycler"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:nestedScrollingEnabled="false" />

</LinearLayout>

My first recycler fetching new portions of data, and when it's scrolled to the end, i want to show the rest items under it.

Tried at first to make it with NestedScrollView, but it's performance is unacceptable, so i want to stick to ScrollView. Different variations with parameters, custom layout managers, don't helped to reach the desired behavior.
As I understand, I need to stick to ScrollView scrollListener, and disable recyclers inner scrolling, but in that case i get only partly filled first recyclerView (6 items instead of 20), even if recyclerView has android:layout_height="wrap_content". I use LinearLayoutManagers with setAutoMeasureEnabled=true.
So my questions are:
- How to expand recyclerView height after new items added (that exceed the screen height)?
- How better to handle scroll in a such scenario?

Any help would be very appreciated.

Body:
Thank you for suggested links with solutions!

Unfortunately, these methods doesn't solve the problem with scroll stuttering in recycler.

And when new portions of data inserted into the first recycler, everything work very slow, cause scrollView recalculate height of every child item when, its contents are changing (the same problem was in NestedScrollView).

And all RecyclerView efficiency is killed by inlining it inside ScrollView or NestedScrollView.

I solved this in another way:

I used one RecyclerView with sections inside of it. Achieved this with custom ViewHolder and custom adapter behavior.

With that approach my recycler works very smooth, and fast.

So my items structure in RecyclerView:

First TextView header

First dynamicly populated items section

Second TextView header

Second items section

TextView footer

For headers i declared custom ViewHolder:

protected class HeaderViewHolder extends BaseListAdapter.ViewHolder implements View.OnClickListener {
    View view;
    TextView textView;

    protected HeaderViewHolder(View v) {
        super(v);
        this.view = v;
        textView = this.view.findViewById(R.id.header_text);
        v.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        if (itemClickListener != null)
            itemClickListener.onItemClick(v, this.getLayoutPosition());
    }

    public View getView() {
        return this.view;
    }

    // Set custom header text
    public void setTitle(String title) {
        textView.setText(title);
    }

    // Hide or show title, if items section don't have any items
    public void setVisibility(int visibility) {
        textView.setVisibility(visibility);
    }
}

Layout for header ViewHolder:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_gravity="center"
    android:orientation="vertical">

    <TextView
        android:id="@+id/search_header"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" />

</LinearLayout>

CustomListAdapter to fill and manage recycler sections:

public class CustomListAdapter extends BaseListAdapter<RecyclerItem> {

    private static final int FOOTER_TYPE = 10;
    private static final int FIRST_HEADER_TYPE = 25;
    private static final int SECOND_HEADER_TYPE = 50;
    private static final int SECOND_ITEMS_TYPE = 100;

    private List<RecyclerItem> secondRecyclerItems = new ArrayList<>();

    public CustomListAdapter(List<RecyclerItem> items, Context context) {
        super(items, R.layout.first_recycler_item, context);
    }

    @Override
    public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        switch (viewType) {
            case FIRST_HEADER_TYPE:
            case SECOND_HEADER_TYPE:
                HeaderViewHolder holder = new HeaderViewHolder(View.inflate(parent.getContext(), R.layout.header_layout, null));
                holder.setTitle(parent.getResources().getString(viewType == FIRST_HEADER_TYPE ? R.string.first_header_title : R.string.second_header_title));
                return holder;

            case FOOTER_TYPE:
                return new HeaderViewHolder(View.inflate(parent.getContext(), R.layout.footer_layout, null));
            default:
                return super.onCreateViewHolder(parent, viewType);
        }
    }

    @Override
    public void onBindViewHolder(BaseListAdapter.ViewHolder holder, int position) {

        if (holder instanceof HeaderViewHolder) {
            if (position == 0) {
                ((HeaderViewHolder) holder).setVisibility(items.size() == 0 ? View.GONE : View.VISIBLE);
            } else if (position == super.getItemCount() + 1 || position == getItemCount() - 1) {
                ((HeaderViewHolder) holder).setVisibility(secondRecyclerItems.size() == 0 ? View.GONE : View.VISIBLE);
            }
            return;
        }

        RecyclerItem item = position <= items.size()
                ? items.get(position - 1)
                : secondRecyclerItems.get(position - (items.size() + 2));

        // Here you populate your items with data, load images, etc...
        // TextView title = holder.itemView.findViewById(R.id.first_recycler_item_title);
    }

    public void clearFirstRecyclerItems() {
        items.clear();
        notifyDataSetChanged();
    }

    public void clearSecondRecyclerItems() {
        secondRecyclerItems.clear();
        notifyDataSetChanged();
    }

    // Define separate collection for second recycler items. First recycler will be populated by default base adapter
    public void swapSecondRecyclerItems(List<RecyclerItem> list) {
        if (secondRecyclerItems != null) {
            secondRecyclerItems.clear();
            secondRecyclerItems.addAll(list);
        } else {
            secondRecyclerItems = new ArrayList<>();
            secondRecyclerItems.addAll(list);
        }
        notifyDataSetChanged();
    }

    // Handle items click, and skip clicks on headers
    public RecyclerItem getClickedItem(int position) {
        if (position == super.getItemCount() + 1 || position == 0 || position == getItemCount() - 1)
            return null;

        return position <= items.size()
                ? items.get(position - 1)
                : secondRecyclerItems.get(position - (items.size() + 2));
    }

    // That's the core method to split recycler items into sections, depending on their position
    @Override
    public int getItemViewType(int position) {
        if (position == 0) {
            return FIRST_HEADER_TYPE;
        } else if (position == super.getItemCount() + 1) {
            return SECOND_HEADER_TYPE;
        } else if (position == getItemCount() - 1) {
            return FOOTER_TYPE;
        } else if (position > super.getItemCount() + 1) {
            return SECOND_ITEMS_TYPE;
        }
        return super.getItemViewType(position);
    }

    // Redefine overall items quantity - super.getItemCount() (base recyclerAdapter items) + secondRecyclerItems + 3 (2 headers and 1 footer)
    @Override
    public int getItemCount() {
        return super.getItemCount() + secondRecyclerItems.size() + 3;
    }

    public int getFirstRecyclerItemsCount() {
        return super.getItemCount() + 1;
    }
}

And for completeness BaseListAdapter:

public abstract class BaseListAdapter<T> extends RecyclerView.Adapter<BaseListAdapter.ViewHolder> {
    protected List<T> items;
    protected @android.support.annotation.LayoutRes int layout;
    protected Context context;
    protected OnItemClickListener itemClickListener;

    public BaseListAdapter(List<T> items, @android.support.annotation.LayoutRes int layout, Context context) {
        this.items = items;
        this.layout = layout;
        this.context = context;
    }

    public T getItem(int position) {
        return items.get(position);
    }

    public List<T> getItems() {
        return items;
    }

    public void setOnItemClickListener(OnItemClickListener onItemClickListener) {
        this.itemClickListener = onItemClickListener;
    }

    // Create new views (invoked by the layout manager)
    @Override
    public BaseListAdapter.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View v = LayoutInflater.from(parent.getContext()).inflate(layout, parent, false);

        return new ViewHolder(v);
    }

    // Return the size of your dataset (invoked by the layout manager)
    @Override
    public int getItemCount() {
        return items.size();
    }

    /**
     * Update the recycler view with a new dataset.
     * */
    public void swap(List<T> list){
        if(items != null) {
            items.clear();
            items.addAll(list);
        }
        else {
            items = new ArrayList<>();
            items.addAll(list);
        }
        notifyDataSetChanged();
    }

    public void add(List<T> list){
        items.addAll(list);
        notifyDataSetChanged();
    }

    protected class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {

        private View view;

        protected ViewHolder(View v) {
            super(v);
            this.view = v;
            v.setOnClickListener(this);
        }

        @Override
        public void onClick(View v) {
            if(itemClickListener != null)
                itemClickListener.onItemClick(v, this.getLayoutPosition());
        }

        public View getView() {
            return this.view;
        }
    }

    public interface OnItemClickListener
    {
        void onItemClick(View v, int position);
    }
}

Hope it could help someone.


问:
Convert bitmap array to YUV (YCbCr NV21)
How to convert Bitmap returned by BitmapFactory.decodeFile() to YUV format (simillar to what camera's onPreviewFrame() returns in byte array)?

答: If using java to convert Bitmap to YUV byte[] is too slow for you, you can try libyuv by Google</p>


问:
Get Google Analytics data using GAPI without login in

I have a news website and I have to show the "Top 5 most visited news of the day" using the data tracked with google analytics, but I haven't managed to make it work. Every code example I've found shows a pop up to login, as if he had his google account linked with the data in analytics, but obviously that's not the case.

I'm trying using this with JS, something like this

```<code><script src="https://apis.google.com/js/client:platform.js"></script>

...

<script>
    function start() {
      // 2. Initialize the JavaScript client library.
      gapi.client.load('analytics', 'v3').then(function() {
        gapi.client.init({
          'apiKey': 'SOME_API_KEY',
          'clientId': 'SOME_CLIENT_ID',
          'scope': 'https://www.googleapis.com/auth/analytics.readonly',
        }).then(function() {
            return gapi.client.analytics.data.ga.get({
              'ids': 'ga:' + "SOME_ID",
              'start-date': 'yesterday',
              'end-date': 'today',
              'metrics': 'ga:pageviews',
              'dimensions': 'ga:pagetitle',
              'max-results': '5',
              'sort': '-ga:pageviews,-ga:date'
            });
        }).then(function(response) {
          console.log(response  );
        }, function(reason) {
          console.log(reason)
          console.log('Error: ' + reason.result.error.message);
        });
      });
    };
    gapi.load('client', start);
</script>
</code>```

And I'm getting this response:

```<code>{result: {…}, body: "{↵  "error": {↵    "code": 401,↵    "message": "Re…project.",↵    "status": "UNAUTHENTICATED"↵  }↵}↵", headers: {…}, status: 401, statusText: null}
body
:
"{↵  "error": {↵    "code": 401,↵    "message": "Request is missing required authentication credential. Expected OAuth 2 access token, login cookie or other valid authentication credential. See https://developers.google.com/identity/sign-in/web/devconsole-project.",↵    "status": "UNAUTHENTICATED"↵  }↵}↵"
</code>```

What am i missing?

答: You can circumvent login with client-side code. The easiest workaround would be to create the table in Google Data Studio and then embed that on your site.</p>

Body:
I have a news website and I have to show the "Top 5 most visited news of the day" using the data tracked with google analytics, but I haven't managed to make it work. Every code example I've found shows a pop up to login, as if he had his google account linked with the data in analytics, but obviously that's not the case.

I'm trying using this with JS, something like this

...

And I'm getting this response:

{result: {…}, body: "{↵  "error": {↵    "code": 401,↵    "message": "Re…project.",↵    "status": "UNAUTHENTICATED"↵  }↵}↵", headers: {…}, status: 401, statusText: null}
body
:
"{↵  "error": {↵    "code": 401,↵    "message": "Request is missing required authentication credential. Expected OAuth 2 access token, login cookie or other valid authentication credential. See https://developers.google.com/identity/sign-in/web/devconsole-project.",↵    "status": "UNAUTHENTICATED"↵  }↵}↵"

What am i missing?


问:
Is there any way to make a canvas using only javascript and nothing else?
I have had a lot of trouble finding a way how. everything tells me to use HTML, though I never learned it. if you know how, just show me an example WITHOUT HTML.</p>

答:
var canvas = document.createElement('canvas');
canvas.width = 300;
canvas.height = 300;
document.body.appendChild(canvas);
var ctx = canvas.getContext('2d');
ctx.arc(150,150,100,0,Math.PI*2);
ctx.stroke();```

Create a canvas element using createElement and append it to body. FYI you need to add this script to a HTML page.

Body:
var canvas = document.createElement('canvas');
canvas.width = 300;
canvas.height = 300;
document.body.appendChild(canvas);
var ctx = canvas.getContext('2d');
ctx.arc(150,150,100,0,Math.PI*2);
ctx.stroke();

Create a canvas element using createElement and append it to body. FYI you need to add this script to a HTML page.


问:
How to anchor ImageView to layout
I'm trying to anchor ImageView to layout as below

We can anchor FloatingActionButton but how to anchor a Imageview

I'm not using CoordinatorLayout. i'm using LinearLayout

How can i do that

答:
Try this</p>

```<code><?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/activity_account_detail"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

    <View
        android:id="@+id/view"
        android:layout_width="match_parent"
        android:layout_height="200dp"
        android:layout_alignParentStart="true"
        android:layout_alignParentTop="true"
        android:background="@color/colorPrimary" />

    <ScrollView
        android:id="@+id/scrolView_account"
        android:layout_width="match_parent"
        android:layout_height="match_parent">

        <RelativeLayout
            android:id="@+id/linear_account"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:orientation="vertical">

            <LinearLayout
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:orientation="vertical">

                <android.support.v7.widget.CardView
                    android:id="@+id/cardView_account_details"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:layout_marginLeft="10dp"
                    android:layout_marginRight="10dp"
                    android:layout_marginTop="70dp"
                    app:cardCornerRadius="5dp"
                    app:cardElevation="5dp"
                    app:cardUseCompatPadding="true">

                    <LinearLayout
                        android:layout_width="match_parent"
                        android:layout_height="wrap_content"
                        android:background="@color/colorAccent"
                        android:orientation="vertical">

                        <LinearLayout
                            android:id="@+id/linear_account_input_details"
                            android:layout_width="match_parent"
                            android:layout_height="wrap_content"
                            android:layout_marginTop="50dp"
                            android:orientation="vertical"
                            android:padding="10dp">

                            <TextView
                                android:layout_width="match_parent"
                                android:layout_height="wrap_content"
                                android:layout_marginTop="20dp"
                                android:gravity="center"
                                android:text="NILU"
                                android:textSize="30sp" />

                            <EditText
                                android:layout_width="match_parent"
                                android:layout_height="wrap_content"
                                android:drawableLeft="@mipmap/ic_launcher_round"
                                android:hint="Enter Email" />

                            <EditText
                                android:layout_width="match_parent"
                                android:layout_height="wrap_content"
                                android:drawableLeft="@mipmap/ic_launcher_round"
                                android:hint="Enter Paasword" />

                            <Button
                                android:layout_width="wrap_content"
                                android:layout_height="wrap_content"
                                android:layout_gravity="center"

                                android:text="Login" />

                        </LinearLayout>

                    </LinearLayout>

                </android.support.v7.widget.CardView>

                <TextView
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_gravity="center"
                    android:text="This is demo" />

            </LinearLayout>

            <RelativeLayout
                android:layout_width="match_parent"
                android:layout_height="wrap_content">

                <de.hdodenhof.circleimageview.CircleImageView
                    android:id="@+id/imageview_account_profile"
                    android:layout_width="150dp"
                    android:layout_height="150dp"
                    android:layout_alignParentTop="true"
                    android:layout_centerHorizontal="true"
                    android:src="@mipmap/ic_launcher_round"
                    app:civ_border_color="@color/colorWhite"
                    app:civ_border_width="2dp" />

            </RelativeLayout>

        </RelativeLayout>

    </ScrollView>

</RelativeLayout>
</code>```

Title: How to anchor ImageView to layout

Body:
Try this

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/activity_account_detail"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

    <View
        android:id="@+id/view"
        android:layout_width="match_parent"
        android:layout_height="200dp"
        android:layout_alignParentStart="true"
        android:layout_alignParentTop="true"
        android:background="@color/colorPrimary" />

    <ScrollView
        android:id="@+id/scrolView_account"
        android:layout_width="match_parent"
        android:layout_height="match_parent">

        <RelativeLayout
            android:id="@+id/linear_account"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:orientation="vertical">

            <LinearLayout
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:orientation="vertical">

                <android.support.v7.widget.CardView
                    android:id="@+id/cardView_account_details"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:layout_marginLeft="10dp"
                    android:layout_marginRight="10dp"
                    android:layout_marginTop="70dp"
                    app:cardCornerRadius="5dp"
                    app:cardElevation="5dp"
                    app:cardUseCompatPadding="true">

                    <LinearLayout
                        android:layout_width="match_parent"
                        android:layout_height="wrap_content"
                        android:background="@color/colorAccent"
                        android:orientation="vertical">

                        <LinearLayout
                            android:id="@+id/linear_account_input_details"
                            android:layout_width="match_parent"
                            android:layout_height="wrap_content"
                            android:layout_marginTop="50dp"
                            android:orientation="vertical"
                            android:padding="10dp">

                            <TextView
                                android:layout_width="match_parent"
                                android:layout_height="wrap_content"
                                android:layout_marginTop="20dp"
                                android:gravity="center"
                                android:text="NILU"
                                android:textSize="30sp" />

                            <EditText
                                android:layout_width="match_parent"
                                android:layout_height="wrap_content"
                                android:drawableLeft="@mipmap/ic_launcher_round"
                                android:hint="Enter Email" />

                            <EditText
                                android:layout_width="match_parent"
                                android:layout_height="wrap_content"
                                android:drawableLeft="@mipmap/ic_launcher_round"
                                android:hint="Enter Paasword" />

                            <Button
                                android:layout_width="wrap_content"
                                android:layout_height="wrap_content"
                                android:layout_gravity="center"

                                android:text="Login" />

                        </LinearLayout>

                    </LinearLayout>

                </android.support.v7.widget.CardView>

                <TextView
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_gravity="center"
                    android:text="This is demo" />

            </LinearLayout>

            <RelativeLayout
                android:layout_width="match_parent"
                android:layout_height="wrap_content">

                <de.hdodenhof.circleimageview.CircleImageView
                    android:id="@+id/imageview_account_profile"
                    android:layout_width="150dp"
                    android:layout_height="150dp"
                    android:layout_alignParentTop="true"
                    android:layout_centerHorizontal="true"
                    android:src="@mipmap/ic_launcher_round"
                    app:civ_border_color="@color/colorWhite"
                    app:civ_border_width="2dp" />

            </RelativeLayout>

        </RelativeLayout>

    </ScrollView>

</RelativeLayout>


问:
Unable to get maxheight on resize
I have html and script like this. I want box1 box2 box display with the same height. But when I resize browser to check, the max height is not correct.

```<code><div class="pro_intro>"
   <div class="box box1">
     something 1
   </div>
   <div class="box box2">
     something 2
   </div>
   <div class="box box3">
     something 3
   </div>
</div>

$(window).on("resize", function () {
        var max = -1;
        $(".pro_intro .box").each(function() {
            var h = $(this).outerHeight();
            max = h > max ? h : max;
        });
        $(".pro_intro .box").css("height",max);
        $(".pro_intro .box").css({'visibility':'visible'});
}).resize();
</code>```

Any suggestion for this. Thank you so much

答:
Try to replace your jquery code with this one below

```<code> var max = -1;
        $(".pro_intro .box").each(function() {
            var h = $(this).outerHeight();
            max = h > max ? h : max;
        });
        $(".pro_intro .box").css("height",max);
        $(".pro_intro .box").css({'visibility':'visible'});
</code>```

https://jsfiddle.net/m3rs30tx/

Title: Unable to get maxheight on resize

Body:
I have html and script like this. I want box1 box2 box display with the same height. But when I resize browser to check, the max height is not correct.

"

     something 1

     something 2

     something 3

$(window).on("resize", function () {
        var max = -1;
        $(".pro_intro .box").each(function() {
            var h = $(this).outerHeight();
            max = h > max ? h : max;
        });
        $(".pro_intro .box").css("height",max);
        $(".pro_intro .box").css({'visibility':'visible'});
}).resize();

Any suggestion for this. Thank you so much

Body:
Try to replace your jquery code with this one below

 var max = -1;
        $(".pro_intro .box").each(function() {
            var h = $(this).outerHeight();
            max = h > max ? h : max;
        });
        $(".pro_intro .box").css("height",max);
        $(".pro_intro .box").css({'visibility':'visible'});

https://jsfiddle.net/m3rs30tx/


问:
Javascript events for gestures in Webkit on Mac?
Is it possible to get gesture events, such as a 3 finger swipe back, on Webkit on the Mac desktop in Javascript?  I did a few Google searches and couldn't find anything.  Otherwise, I guess I could pass them from Cocoa to a WebView.  I am particularly interested in the 3 finger swipe back.

EDIT

It appears that even in the Sencha Touch Kitchen Sink app on the latest Webkit night nighlies on my Macbook Pro, swipe events aren't detected. However there is an easier solution for me to simply use the browser history state when doing partial Ajax style page updates (duh, can't believe I didn't think of that) with the Backbone.js history plugin so that the user can go back using the browser back button, or 3 finger swipe.

答:
Webkit is not compatible with the touch API for the moment.

If you want to know if the touch events api is supported, you can use modernizr and modify your UI depending to the results ...

Download it here : http://www.modernizr.com/ Then write something like this :

```<code>if (Modernizr.touch){
  // bind to touchstart, touchmove, etc and watch `event.streamId`
} else {
  // bind to normal click, mousemove, etc
}
</code>```

Modernizr customize also your body element's class, so you can access to it with CSS

You can complete it with yepnope js : http://yepnopejs.com/

```<code>yepnope({
  test: Modernizr.touch,
  yep: 'touch-ui.js',
  nope: 'standard-ui.js'
});
</code>```

And when the events are supported, you can use jQuery mobile.

ContentLicense: CC BY-SA 2.5

Body:
Webkit is not compatible with the touch API for the moment.

If you want to know if the touch events api is supported, you can use modernizr and modify your UI depending to the results ...

Download it here : http://www.modernizr.com/ Then write something like this :

if (Modernizr.touch){
  // bind to touchstart, touchmove, etc and watch `event.streamId`
} else {
  // bind to normal click, mousemove, etc
}

Modernizr customize also your body element's class, so you can access to it with CSS

You can complete it with yepnope js : http://yepnopejs.com/

yepnope({
  test: Modernizr.touch,
  yep: 'touch-ui.js',
  nope: 'standard-ui.js'
});

And when the events are supported, you can use jQuery mobile.


问:
How do I conform to a protocol with associatedtype in Swift?
It's such a shame that I really have no idea with this. I have this project that was developed by someone else and it's using TRON library.

My question is pretty straightforward. How do I conform to a protocol with an associatedtype. I know how to write a protocol and conform to it just like with UITableViewDataSource and UITableViewDelegate.

Here's the code of TRON's protocol:

Serializer.swift

```<code>import Foundation
import Alamofire

/// The type in which all data and upload response serializers must conform to in order to serialize a response.
public protocol ErrorHandlingDataResponseSerializerProtocol : DataResponseSerializerProtocol {
    /// The type of serialized object to be created by this `ErrorHandlingDataResponseSerializerProtocol`.
    associatedtype SerializedError

    /// A closure used by response handlers that takes a parsed result, request, response, data and error and returns a serialized error.
    var serializeError: (Alamofire.Result<SerializedObject>?,URLRequest?, HTTPURLResponse?, Data?, Error?) -> APIError<SerializedError> { get }
}
</code>```

And I'm trying to conform to that protocol like so:

```<code> class CustomErrorHandlingSerializer: ErrorHandlingDataResponseSerializerProtocol {

 }
</code>```

I need to conform to that because there is a function here that needs an ErrorHandlingDataResponseSerializerProtocol,

I have tried reading the library's documentation and even their migration guide. It's either they really do not have a straightforward example on their usage OR I just don't understand their documentation.

https://github.com/MLSDev/TRON/blob/master/Docs/4.0%20Migration%20Guide.md

https://github.com/MLSDev/TRON

答:
You need to specify what type of object will be returned by the serializeError property. There are two ways to do it:

Define a SerializedError subtype of your class, or:

Use typealias to point SerializedError to the appropriate type that your serializeError property will provide.

Body:
It's such a shame that I really have no idea with this. I have this project that was developed by someone else and it's using TRON library.

My question is pretty straightforward. How do I conform to a protocol with an associatedtype. I know how to write a protocol and conform to it just like with UITableViewDataSource and UITableViewDelegate.

Here's the code of TRON's protocol:

Serializer.swift

import Foundation
import Alamofire

/// The type in which all data and upload response serializers must conform to in order to serialize a response.
public protocol ErrorHandlingDataResponseSerializerProtocol : DataResponseSerializerProtocol {
    /// The type of serialized object to be created by this `ErrorHandlingDataResponseSerializerProtocol`.
    associatedtype SerializedError

    /// A closure used by response handlers that takes a parsed result, request, response, data and error and returns a serialized error.
    var serializeError: (Alamofire.Result<SerializedObject>?,URLRequest?, HTTPURLResponse?, Data?, Error?) -> APIError<SerializedError> { get }
}

And I'm trying to conform to that protocol like so:

 class CustomErrorHandlingSerializer: ErrorHandlingDataResponseSerializerProtocol {

 }

I need to conform to that because there is a function here that needs an ErrorHandlingDataResponseSerializerProtocol,

I have tried reading the library's documentation and even their migration guide. It's either they really do not have a straightforward example on their usage OR I just don't understand their documentation.

https://github.com/MLSDev/TRON/blob/master/Docs/4.0%20Migration%20Guide.md

https://github.com/MLSDev/TRON


问:
DatePicker not working on bootstrap 4
I want to used datepicker on my project.This is my first time using bootstrap.The problem is that datepicker not displayed when i click the date form.I already try replace CDN url position inside  and inside  tag and still not worked.I dont know what mistake that i make,hope you guys can help me with this problem thank you.</p>

```<code><!DOCTYPE html>
<html lang="en">

<head>
  <!-- Required meta tags -->
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">

  <!-- Bootstrap CSS -->
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.6/css/bootstrap.min.css" integrity="sha384-rwoIResjU2yc3z8GV/NPeZWAv56rSmLldC3R/AZzGRnGxQQKnKkoFVhFQhNUwEyJ" crossorigin="anonymous">

  <!-- datepicker -->
  <link rel="stylesheet" href="https://code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
  <link rel="stylesheet" href="/resources/demos/style.css">
  <script src="https://code.jquery.com/jquery-1.12.4.js"></script>
  <script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
  <script>
    $(function() {
      $("#datepicker").datepicker();
    });
  </script>
</head>

<body>
  <nav class="navbar navbar-toggleable-md navbar-inverse bg-inverse">
    <button class="navbar-toggler navbar-toggler-right" type="button" data-toggle="collapse" data-target="#navbarsExampleDefault" aria-controls="navbarsExampleDefault" aria-expanded="false" aria-label="Toggle navigation">
        <span class="navbar-toggler-icon"></span>
      </button>
    <a class="navbar-brand" href="#">Menu</a>
    <div class="collapse navbar-collapse" id="navbarsExampleDefault">
      <ul class="navbar-nav mr-auto">
        <li class="nav-item dropdown">
          <a class="nav-link dropdown-toggle" href="http://example.com" id="dropdown01" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">Management</a>
          <div class="dropdown-menu" aria-labelledby="dropdown01">
            <a class="dropdown-item" href="dashboard.php?act=create_program">Create Program</a>
            <a class="dropdown-item" href="dashboard.php?act=view_program">View Program</a>
          </div>
        </li>
      </ul>
    </div>
  </nav>
  <div class="container-fluid">
    <div class="row">
      <div class="col-md-4"></div>
      <div class="col-md-4">
        <!-- Datepicker -->
        Date: <input type="text" id="datepicker">
      </div>
      <div class="col-md-4"></div>
    </div>
  </div>
  <!-- jQuery first, then Tether, then Bootstrap JS. -->
  <script src="https://code.jquery.com/jquery-3.1.1.slim.min.js" integrity="sha384-A7FZj7v+d/sdmMqp/nOQwliLvUsJfDHW+k9Omg/a/EheAdgtzNs3hpfag6Ed950n" crossorigin="anonymous"></script>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/tether/1.4.0/js/tether.min.js" integrity="sha384-DztdAPBWPRXSA/3eYEEUWrWCy7G5KFbe8fFjk5JAIxUYHKkDx6Qin1DkWx51bBrb" crossorigin="anonymous"></script>
  <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.6/js/bootstrap.min.js" integrity="sha384-vBWWzlZJ8ea9aCX4pEW3rVHjgjt7zpkNpZk+02D9phzyeVkE+jo0ieGizqPLForn" crossorigin="anonymous"></script>
</body>

</html>
</code>```

答:
Your Code is working good but you need to change the format.and there is a problem in bottom sources.

jquery conflicts issue

  $( function() {
    $( "#datepicker" ).datepicker();
  } );```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://code.jquery.com/jquery-3.1.1.slim.min.js" integrity="sha384-A7FZj7v+d/sdmMqp/nOQwliLvUsJfDHW+k9Omg/a/EheAdgtzNs3hpfag6Ed950n" crossorigin="anonymous"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/tether/1.4.0/js/tether.min.js" integrity="sha384-DztdAPBWPRXSA/3eYEEUWrWCy7G5KFbe8fFjk5JAIxUYHKkDx6Qin1DkWx51bBrb" crossorigin="anonymous"></script>
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.6/js/bootstrap.min.js" integrity="sha384-vBWWzlZJ8ea9aCX4pEW3rVHjgjt7zpkNpZk+02D9phzyeVkE+jo0ieGizqPLForn" crossorigin="anonymous"></script>
        <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.6/css/bootstrap.min.css" integrity="sha384-rwoIResjU2yc3z8GV/NPeZWAv56rSmLldC3R/AZzGRnGxQQKnKkoFVhFQhNUwEyJ" crossorigin="anonymous">

    <!-- datepicker -->
<link rel="stylesheet" href="https://code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
  <link rel="stylesheet" href="/resources/demos/style.css">
  <script src="https://code.jquery.com/jquery-1.12.4.js"></script>
  <script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
          <nav class="navbar navbar-toggleable-md navbar-inverse bg-inverse">
      <button class="navbar-toggler navbar-toggler-right" type="button" data-toggle="collapse" data-target="#navbarsExampleDefault" aria-controls="navbarsExampleDefault" aria-expanded="false" aria-label="Toggle navigation">
        <span class="navbar-toggler-icon"></span>
      </button>
      Menu

      <div class="collapse navbar-collapse" id="navbarsExampleDefault">
        <ul class="navbar-nav mr-auto">
          <li class="nav-item dropdown">
            Management
            <div class="dropdown-menu" aria-labelledby="dropdown01">
              Create Program
              View Program
            </div>
          </li>
        </ul>
      </div>
    </nav>

    <div class="container-fluid">
    <div class="row">

      <div class="col-md-4"></div>
      <div class="col-md-4">
            <!-- Datepicker -->
            Date: <input type="text" id="datepicker">
      </div>
      <div class="col-md-4"></div>

    </div>
    </div></code>```

Title: DatePicker not working on bootstrap 4

Body:
I want to used datepicker on my project.This is my first time using bootstrap.The problem is that datepicker not displayed when i click the date form.I already try replace CDN url position inside  and inside  tag and still not worked.I dont know what mistake that i make,hope you guys can help me with this problem thank you.

<!DOCTYPE html>

  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">

  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.6/css/bootstrap.min.css" integrity="sha384-rwoIResjU2yc3z8GV/NPeZWAv56rSmLldC3R/AZzGRnGxQQKnKkoFVhFQhNUwEyJ" crossorigin="anonymous">

  <link rel="stylesheet" href="https://code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
  <link rel="stylesheet" href="/resources/demos/style.css">

    <button class="navbar-toggler navbar-toggler-right" type="button" data-toggle="collapse" data-target="#navbarsExampleDefault" aria-controls="navbarsExampleDefault" aria-expanded="false" aria-label="Toggle navigation">

      </button>
    Menu

          Management

            Create Program
            View Program

        Date: <input type="text" id="datepicker">

Body:
Your Code is working good but you need to change the format.and there is a problem in bottom sources.

jquery conflicts issue

  $( function() {
    $( "#datepicker" ).datepicker();
  } );

<script src="https://code.jquery.com/jquery-3.1.1.slim.min.js" integrity="sha384-A7FZj7v+d/sdmMqp/nOQwliLvUsJfDHW+k9Omg/a/EheAdgtzNs3hpfag6Ed950n" crossorigin="anonymous"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/tether/1.4.0/js/tether.min.js" integrity="sha384-DztdAPBWPRXSA/3eYEEUWrWCy7G5KFbe8fFjk5JAIxUYHKkDx6Qin1DkWx51bBrb" crossorigin="anonymous"></script>
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.6/js/bootstrap.min.js" integrity="sha384-vBWWzlZJ8ea9aCX4pEW3rVHjgjt7zpkNpZk+02D9phzyeVkE+jo0ieGizqPLForn" crossorigin="anonymous"></script>
        <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.6/css/bootstrap.min.css" integrity="sha384-rwoIResjU2yc3z8GV/NPeZWAv56rSmLldC3R/AZzGRnGxQQKnKkoFVhFQhNUwEyJ" crossorigin="anonymous">

    <!-- datepicker -->
<link rel="stylesheet" href="https://code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
  <link rel="stylesheet" href="/resources/demos/style.css">
  <script src="https://code.jquery.com/jquery-1.12.4.js"></script>
  <script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
          <nav class="navbar navbar-toggleable-md navbar-inverse bg-inverse">
      <button class="navbar-toggler navbar-toggler-right" type="button" data-toggle="collapse" data-target="#navbarsExampleDefault" aria-controls="navbarsExampleDefault" aria-expanded="false" aria-label="Toggle navigation">
        <span class="navbar-toggler-icon"></span>
      </button>
      <a class="navbar-brand" href="#">Menu</a>

      <div class="collapse navbar-collapse" id="navbarsExampleDefault">
        <ul class="navbar-nav mr-auto">
          <li class="nav-item dropdown">
            <a class="nav-link dropdown-toggle" href="http://example.com" id="dropdown01" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">Management</a>
            <div class="dropdown-menu" aria-labelledby="dropdown01">
              <a class="dropdown-item" href="dashboard.php?act=create_program">Create Program</a>
              <a class="dropdown-item" href="dashboard.php?act=view_program">View Program</a>
            </div>
          </li>
        </ul>
      </div>
    </nav>

    <div class="container-fluid">
    <div class="row">

      <div class="col-md-4"></div>
      <div class="col-md-4">
            <!-- Datepicker -->
            Date: <input type="text" id="datepicker">
      </div>
      <div class="col-md-4"></div>

    </div>
    </div>


问:
How to add target="_blank" to JavaScript window.location?
The following sets the target to _blank:

```<code>if (key == "smk") {
    window.location = "http://www.smkproduction.eu5.org";
    target = "_blank";
    done = 1;
}
</code>```

But this doesn't seem to work. How do I launch the link in a new tab?

Here is my code:

function ToKey() {
  var done = 0;
  var key = document.tokey.key.value;
  key = key.toLowerCase();
  if (key == "smk") {
    window.location = "http://www.smkproduction.eu5.org";
    target = "_blank"
    done = 1;
  }
  if (done == 0) {
    alert("Kodi nuk është valid!");
  }
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><form name="tokey">
  <table>
    <tr>
      <td>Type the key</td>
      <td>
        <input type="text" name="key">
      </td>
      <td>
      </td>
      <td>
        <input type="button" value="Go" onClick="ToKey()">
      </td>
  </table>
</form></code>```

答:
    var linkGo = function(item) {
      $(item).on('click', function() {
        var _$this = $(this);
        var _urlBlank = _$this.attr("data-link");
        var _urlTemp = _$this.attr("data-url");
        if (_urlBlank === "_blank") {
          window.open(_urlTemp, '_blank');
        } else {
          // cross-origin
          location.href = _urlTemp;
        }
      });
    };

    linkGo(".button__main[data-link]");```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.button{cursor:pointer;}</code>```

go stackoverflow```

Body:
The following sets the target to _blank:

if (key == "smk") {
    window.location = "http://www.smkproduction.eu5.org";
    target = "_blank";
    done = 1;
}

But this doesn't seem to work. How do I launch the link in a new tab?

Here is my code:

function ToKey() {
  var done = 0;
  var key = document.tokey.key.value;
  key = key.toLowerCase();
  if (key == "smk") {
    window.location = "http://www.smkproduction.eu5.org";
    target = "_blank"
    done = 1;
  }
  if (done == 0) {
    alert("Kodi nuk është valid!");
  }
}

<form name="tokey">

      Type the key

        <input type="text" name="key">

        <input type="button" value="Go" onClick="ToKey()">

</form>

Body:
    var linkGo = function(item) {
      $(item).on('click', function() {
        var _$this = $(this);
        var _urlBlank = _$this.attr("data-link");
        var _urlTemp = _$this.attr("data-url");
        if (_urlBlank === "_blank") {
          window.open(_urlTemp, '_blank');
        } else {
          // cross-origin
          location.href = _urlTemp;
        }
      });
    };

    linkGo(".button__main[data-link]");

.button{cursor:pointer;}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<span class="button button__main" data-link="" data-url="https://stackoverflow.com/">go stackoverflow</span>


问:
Are Apps for the Google App Engine usable on other servers?
How portable are applications for the Google App Engine? Are these bound forever on the GAE?</p>

答:
As a good consultant, I'd say the answer is "depends."

First of all, you can always run a GAE project in the SDK.  So to that extent you're not bound.  Beyond that, it depends on what other APIs you use.  The webapp library is very much like some others, but I don't think it's available as a standalone; however, GAE supports Django as a web framework as well, and that of course is available stand alone.

The code is just Python.  But some of the APIs, like the data API, are really meant to interact with the Google cloud; you can't be sure you can move an arbitrary GAE program to another platform without rework.

OwnerDisplayName: stesch

OwnerDisplayName: Charlie Martin

LastEditorDisplayName: Hank Gay


问:
How does Corona SDK work ? Is Lua converted to Objective C?
Corona SDK says you code in LUA. But afterwards does it translate to Objective C ? Can I see source code generated somewhere ?

If it uses an engine to interpret Lua is this authorized by Apple Store ?

答:
Corona SDK is a closed source game engine and App development kit. You only get access to the Lua code and interface.

What kind of engine they're running behind the scenes and which language it uses is speculative for the most part. I think I remember that on their forum or blog it was mentioned that it's powered by a C++ engine that they wrote. Makes sense if you consider that Corona Apps run on both iOS and Android devices, the latter doesn't support development with Objective-C.


问:
I want to enable textbox when checkbox is checked in jquery or javascript
I want to enable textbox when checkbox is checked form content load from ajax page in modal popup but its not working and not showing any error in browser console.

function cash(cash) {
  if ($(cash).is(':checked')) {
    $('#cashAmount').attr("disabled", false);
  } else {
    alert("checkbox is not checked");
  }
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="col-md-12 field-option">
  <strong>Cash</strong> <input type="checkbox" name="cash" id="cash" onclick="cash(this)">
</div>
<div class="col-md-6 col-sm-6 custom_field">
  <!-- custom_field -->
  <span><strong>Amount <i>*</i></strong></span>
  <input type="text" name="cashAmount" id="cashAmount" class="form-control" disabled>
</div></code>```

答:
What you need to do is this:

```<code>function cash(cash) {
 var getthevalue = $(cash).attr('id');
  if (getthevalue.is(':checked')) {
    $('#cashAmount').attr("disabled", false);
  }
  else{
    alert("checkbox is not checked");
  }
}
</code>```

This is because when you pass:

```<code><strong>Cash</strong> <input type="checkbox" name="cash" id="cash" onclick="cash(this)">
</code>```

You bass the html element and not the id, your This is referring to the entire strong tag.

So in your method:

```<code>var getthevalue = $(cash).attr('id');
</code>```

Will get the id attribute of your input tag, which is passed through your this:

```<code> onclick="cash(this)"
</code>```

Body:
I want to enable textbox when checkbox is checked form content load from ajax page in modal popup but its not working and not showing any error in browser console.

function cash(cash) {
  if ($(cash).is(':checked')) {
    $('#cashAmount').attr("disabled", false);
  } else {
    alert("checkbox is not checked");
  }
}

  Cash <input type="checkbox" name="cash" id="cash" onclick="cash(this)">

  Amount *
  <input type="text" name="cashAmount" id="cashAmount" class="form-control" disabled>

Body:
What you need to do is this:

function cash(cash) {
 var getthevalue = $(cash).attr('id');
  if (getthevalue.is(':checked')) {
    $('#cashAmount').attr("disabled", false);
  }
  else{
    alert("checkbox is not checked");
  }
}

This is because when you pass:

<strong>Cash</strong> <input type="checkbox" name="cash" id="cash" onclick="cash(this)">

You bass the html element and not the id, your This is referring to the entire strong tag.

So in your method:

var getthevalue = $(cash).attr('id');

Will get the id attribute of your input tag, which is passed through your this:

 onclick="cash(this)"