问:
Why only the first click increases the vote counter but others do not?
The php part of the code:

```<code> //the JS part
 echo "<script>
  function increasevotes(e,location,user,date,vote)
  {
    e.preventDefault();
    var xmlhttp = new XMLHttpRequest();
    xmlhttp.onreadystatechange = function() {
            if (this.readyState == 4 && this.status == 200) {
            e.target.parentNode.previousSibling.textContent=this.responseText;
            }
        };
    xmlhttp.open(\"GET\", \"vote.php?location=\" + location + \"&user=\"+ user +\"&date=\"+date+\"&vote=\"+vote, true);
    xmlhttp.send();
  }
  </script>"
//the HTML part
echo "<span class=\"right nolikes\">{$rows['vote']}</span>
<a href=\"\" onclick=\"increasevotes(event,'{$rows['title']}','{$rows['username']}','{$rows['date']}','{$rows['vote']}')\">
<img src=\"img/like.png\" class=\"right\" width=\"30\" height=\"30\"/>
</a>"
</code>```

The php which is used in the AJAX call. (vote.php)

```<code><?php
    include("configure.php");
    $location = $_REQUEST["location"];
    $username = $_REQUEST["user"];
    $date = $_REQUEST["date"];
    $vote=$_REQUEST["vote"]+1;
    $query="UPDATE journals SET vote={$vote} WHERE title='".$location."' AND username='".$username."' AND date='".$date."'";
    $qresult=mysqli_query($conn,$query);
    echo $vote;
?>
</code>```

Problem:

Initially, the database contains vote as zero. So, a like image and 0 is displayed. When I click on the like image, the vote is increased 1 both in the database and also updated in the html page. But, clicking on the like symbol again does not increase the vote count to two. Why?

答:
The reason is in your JS callback you are updating only the text of

```<code><span class="right nolikes">{$rows['vote']}</span>
</code>```

with this line :

```<code>e.target.parentNode.previousSibling.textContent=this.responseText;
</code>```

But you also need to update the amount of vote on the onclick part :

```<code><a href="" onclick="increasevotes(event,'{$rows['title']}','{$rows['username']}','{$rows['date']}','{$rows['vote']}')">
here it still uses old vote number
</code>```

I would suggest you do it in SQL and PHP part instead of passing current amount of vote to PHP.
so instead of $vote=$_REQUEST["vote"]+1; in your php part do this :

```<code>$query="UPDATE journals SET vote=vote+1 WHERE title='".$location."' AND username='".$username."' AND date='".$date."'";
</code>```

and then to update the value you can either do it quickly or wait until call back but change it to this :

```<code>var oldVote = parseInt(e.target.parentNode.previousSibling.textContent);
e.target.parentNode.previousSibling.textContent= oldVote++;
</code>```

There are also more way to fix this but I think this might help you.

Body:
The php part of the code:

 //the JS part
 echo ""
//the HTML part
echo "{$rows['vote']}

"

The php which is used in the AJAX call. (vote.php)

<?php
    include("configure.php");
    $location = $_REQUEST["location"];
    $username = $_REQUEST["user"];
    $date = $_REQUEST["date"];
    $vote=$_REQUEST["vote"]+1;
    $query="UPDATE journals SET vote={$vote} WHERE title='".$location."' AND username='".$username."' AND date='".$date."'";
    $qresult=mysqli_query($conn,$query);
    echo $vote;
?>

Problem:

Initially, the database contains vote as zero. So, a like image and 0 is displayed. When I click on the like image, the vote is increased 1 both in the database and also updated in the html page. But, clicking on the like symbol again does not increase the vote count to two. Why?

Body:
The reason is in your JS callback you are updating only the text of

<span class="right nolikes">{$rows['vote']}</span>

with this line :

e.target.parentNode.previousSibling.textContent=this.responseText;

But you also need to update the amount of vote on the onclick part :

<a href="" onclick="increasevotes(event,'{$rows['title']}','{$rows['username']}','{$rows['date']}','{$rows['vote']}')">
here it still uses old vote number

I would suggest you do it in SQL and PHP part instead of passing current amount of vote to PHP.
so instead of $vote=$_REQUEST["vote"]+1; in your php part do this :

$query="UPDATE journals SET vote=vote+1 WHERE title='".$location."' AND username='".$username."' AND date='".$date."'";

and then to update the value you can either do it quickly or wait until call back but change it to this :

var oldVote = parseInt(e.target.parentNode.previousSibling.textContent);
e.target.parentNode.previousSibling.textContent= oldVote++;

There are also more way to fix this but I think this might help you.


来源: stackexchange

问:
How to hide a view from a stack view in table view cellForRow delegate method
I'd like to know what's the cleanest way to remove a view from a stack view if a certain property in my data model is nil. I have a table view which is populated by prototype cells. They look like this:

The second label text contains an optional value which may be nil; I want to hide the label if it's nil. Should I call removeArrangedSubview inside the cellForRow table view cell method or inside the CustomTableViewCell class with a function?

答:
I want to hide the label if [optional value] is nil

You should set label's hidden property to true rather than removing it from arranged subview list of stack layout in order to avoid adding it back when the cell gets reused for a different row.

It is mostly a matter of preference where you do it. If most of your cell setup code is in the cellForRow function, you should hide and unhide the label from that function as well:

```<code>if let labelText = model.getTextForMyLabel(indexPath.row) {
    cell.label.text = labelText
    cell.label.hidden = false
} else {
    cell.label.hidden = true
}
</code>```

If you have a setter for label text in the code for your CustomTableViewCell, you can use the same approach to set the label's hidden property along with its text.

ContentLicense: CC BY-SA 3.0

Body:
I want to hide the label if [optional value] is nil

You should set label's hidden property to true rather than removing it from arranged subview list of stack layout in order to avoid adding it back when the cell gets reused for a different row.

It is mostly a matter of preference where you do it. If most of your cell setup code is in the cellForRow function, you should hide and unhide the label from that function as well:

if let labelText = model.getTextForMyLabel(indexPath.row) {
    cell.label.text = labelText
    cell.label.hidden = false
} else {
    cell.label.hidden = true
}

If you have a setter for label text in the code for your CustomTableViewCell, you can use the same approach to set the label's hidden property along with its text.


问:
Ampersand doesn't load in Query String - PHP
I'm passing simple query string:

```<code>index.php?a=orange&apple
</code>```

Getting value with:

```<code>$_GET['a'];
</code>```

it only shows orange value. i have tried

```<code>$a = urlencode($_GET['a']);
$rs = urldecode($a);
echo $rs; // orange;
</code>```

but didn't work. Found similar question here stackoverflow but seems not useful. How do i get complete value orange&apple?

答:
That is because & makes apple as another value in GET request.

Like this -

```<code>/test/demo_form.php?name1=value1&name2=value2
</code>```

So use '%26'(encoding URI Component) in place of & like this -

```<code>index.php?a=orange%26apple
</code>```

And get the value with $_GET['a'];. This should work.

Body:
I'm passing simple query string:

index.php?a=orange&apple

Getting value with:

$_GET['a'];

it only shows orange value. i have tried

$a = urlencode($_GET['a']);
$rs = urldecode($a);
echo $rs; // orange;

but didn't work. Found similar question here stackoverflow but seems not useful. How do i get complete value orange&apple?

Body:
That is because & makes apple as another value in GET request.

Like this -

/test/demo_form.php?name1=value1&name2=value2

So use '%26'(encoding URI Component) in place of & like this -

index.php?a=orange%26apple

And get the value with $_GET['a'];. This should work.


问:
Reporting Services Expression
I'm trying to set the Hidden-property of a Textbox based on this expression:

```<code>=IIf(IsNothing(Parameters!customer_numbers.Value) AND
     IsNothing(Parameters!country_codes.Value),False,True)
</code>```

Error: "Argument not specified for parameter 'FalsePart' of Public Function IIf(Expression As Boolean, TruePart As Object, FalsePart As Object) As Object"

I'm a jScript/C# guy and not used to this pseudo-VB language. What is wrong?

Regards
Alex

答:
My answer is that nothing is wrong!

I just created a test report (RS 2008) with your two parameters: customer_numbers and country_codes. I set the parameters to be text fields and nullable.

I added a textbox with the text "Both parameters are null". I set the visibility expression via copy and paste from your question.

The report starts fine, and if I set both parameters to be null then I see the textbox. The rdl of the textbox turns out like this:

```<code> <Visibility>
      <Hidden>=IIf(IsNothing(Parameters!customer_numbers.Value) AND
 IsNothing(Parameters!country_codes.Value),False,True)</Hidden>
    </Visibility>
</code>```

ContentLicense: CC BY-SA 2.5

Title: Reporting Services Expression

Body:
I'm trying to set the Hidden-property of a Textbox based on this expression:

=IIf(IsNothing(Parameters!customer_numbers.Value) AND
     IsNothing(Parameters!country_codes.Value),False,True)

Error: "Argument not specified for parameter 'FalsePart' of Public Function IIf(Expression As Boolean, TruePart As Object, FalsePart As Object) As Object"

I'm a jScript/C# guy and not used to this pseudo-VB language. What is wrong?

Regards
Alex

Body:
My answer is that nothing is wrong!

I just created a test report (RS 2008) with your two parameters: customer_numbers and country_codes. I set the parameters to be text fields and nullable.

I added a textbox with the text "Both parameters are null". I set the visibility expression via copy and paste from your question.

The report starts fine, and if I set both parameters to be null then I see the textbox. The rdl of the textbox turns out like this:

 <Visibility>
      <Hidden>=IIf(IsNothing(Parameters!customer_numbers.Value) AND
 IsNothing(Parameters!country_codes.Value),False,True)</Hidden>
    </Visibility>


问:
Display text with icon in Xamarin forms
How to display text with icon in button? I am using font awesome icons and displaying them using their uni code. Like this:

Now if i add unicode with text the icon doesnt show although text still shows.

This only shows text and Cross instead of icon.

答: Use Iconize for Xamarin Forms. It let's you use font awesome and other icon fonts too. </p>

Title: Display text with icon in Xamarin forms


问:
Save textField value to cell textLabel (name) [SWIFT]
I'm going to do something like this https://i.stack.imgur.com/jAGsk.png

So if user input points - it'll save points to the user's name. How to do it? I paste textField in the tableViewCell with a functions.
Here is code from the tableViewCell file

```<code>@IBOutlet weak var inputScore: UITextField!

public func configure(text: Int?, placeholder: String) {
    inputScore.text = String(text!)
    inputScore.placeholder = placeholder

    inputScore.accessibilityValue = String(text!)
    inputScore.accessibilityLabel = placeholder
}
</code>```

And here is code from the VC file

```<code>public func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: "InputScore") as! InputScoreTableViewCell
    cell.textLabel?.text = usersIn[indexPath.row]
    cell.configure(text: 100, placeholder: "Score")
    return cell
}
public func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return usersIn.count
}
</code>```

So how to save it to the user's name?

答:
You have to create a data model for your users:

```<code>class User: NSObject {
    var points = 0
}
</code>```

And then create an array of users in your view controller:

```<code>var users = [User]()
</code>```

That way, you can do something like this

```<code>var user = users[indexPath.row]
user.points = 100
print(user.points) // 100
</code>```

You can then display your users' points in your table view. You can also assign a tag to your text fields equal to the indexPath.row so that you can easily work with them.

Body:
I'm going to do something like this https://i.stack.imgur.com/jAGsk.png

So if user input points - it'll save points to the user's name. How to do it? I paste textField in the tableViewCell with a functions.
Here is code from the tableViewCell file

@IBOutlet weak var inputScore: UITextField!

public func configure(text: Int?, placeholder: String) {
    inputScore.text = String(text!)
    inputScore.placeholder = placeholder

    inputScore.accessibilityValue = String(text!)
    inputScore.accessibilityLabel = placeholder
}

And here is code from the VC file

public func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: "InputScore") as! InputScoreTableViewCell
    cell.textLabel?.text = usersIn[indexPath.row]
    cell.configure(text: 100, placeholder: "Score")
    return cell
}
public func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return usersIn.count
}

So how to save it to the user's name?

Body:
You have to create a data model for your users:

class User: NSObject {
    var points = 0
}

And then create an array of users in your view controller:

var users = [User]()

That way, you can do something like this

var user = users[indexPath.row]
user.points = 100
print(user.points) // 100

You can then display your users' points in your table view. You can also assign a tag to your text fields equal to the indexPath.row so that you can easily work with them.


问:
Connecting Samsung S7 to AndroidStudio
I like to start my app directly on Samsung S7 with AndroidStudio.

I have already enabled debugging mode in the developer option by tapping 7 times on build number, but still I don't see the device when starting the app and getting the "Select Deployment Target" Dialog.

What else do I have to do ?

答: In developer options at bottom of setings menu, ensure USB debugging is ticked. Then start again, restart windows and S7 to make sure and try again. With one of my devices, tapping seven times enabled developer mode, but the debugging options was not selected by default and had to be manually selected from developer options after they were enabled.</p>

Title: Connecting Samsung S7 to AndroidStudio


问:
SQL: how to randomly sample a number of values for each row
Suppose I have a table A (id string), what I need is to create a table B (id1 string, id2 string) such that, B.id2 is randomly sampled from A.id. B.id1 is the same as A.id. For example:

table A:

```<code>id
1
2
3
4
</code>```

table B:

```<code>id1   id2
 1     2
 1     3
 2     4
 2     3
 3     1
 3     2
 4     1
 4     4
</code>```

That is, for each id in A, randomly sample 2 id in A as a new column id2. How can I do this with SQL? I would prefer a sample without replacement. But it is ok if id2 equals id1. Thank you for helping me!

答:
One way is this:

```<code> select  id as id1, (select id from A order by rand() limit 1) as id2 from A
 union all
 select  id as id1, (select id from A order by rand() limit 1) as id2 from A
</code>```

you can use insert into ... select ... for put this values into table B.

If you want more than  2 id's, for example several dozens, then this method is bad choice.

Body:
Suppose I have a table A (id string), what I need is to create a table B (id1 string, id2 string) such that, B.id2 is randomly sampled from A.id. B.id1 is the same as A.id. For example:

table A:

id
1
2
3
4

table B:

id1   id2
 1     2
 1     3
 2     4
 2     3
 3     1
 3     2
 4     1
 4     4

That is, for each id in A, randomly sample 2 id in A as a new column id2. How can I do this with SQL? I would prefer a sample without replacement. But it is ok if id2 equals id1. Thank you for helping me!

Body:
One way is this:

 select  id as id1, (select id from A order by rand() limit 1) as id2 from A
 union all
 select  id as id1, (select id from A order by rand() limit 1) as id2 from A

you can use insert into ... select ... for put this values into table B.

If you want more than  2 id's, for example several dozens, then this method is bad choice.


答: Install necessary drivers from this site. Then connect your device with debugging enabled, your device will prompt a dialog for permission, click ok.</p>

Title: Connecting Samsung S7 to AndroidStudio

Body:
I like to start my app directly on Samsung S7 with AndroidStudio.

I have already enabled debugging mode in the developer option by tapping 7 times on build number, but still I don't see the device when starting the app and getting the "Select Deployment Target" Dialog.

What else do I have to do ?


问:
why cant i turn off led's on arduino using android and esp8266
i have tried to make an android application to turn on or off led's using arduino.

esp8266 esp-01 provides access point .

But i cant turn off the led's using the there is always some error

also when i see the data in serial monitor it is partially gibberish

i have taken the code from  allaboutee.com/2015/01/20/esp8266-android-application-for-arduino-pin-control/

but it was modified by me because it was not working for me on 2 and 3 pins

I have used arduino uno.

The circuit diagram is like this

The code for arduino is as follows:

```<code>#include <SoftwareSerial.h>

#define DEBUG true

SoftwareSerial esp8266(10,11); // make RX Arduino line is pin 2, make TX Arduino line is pin 3.
                             // This means that you need to connect the TX line from the esp to the Arduino's pin 2
                             // and the RX line from the esp to the Arduino's pin 3
void setup()
{
  Serial.begin(115200);
  esp8266.begin(115200); // your esp's baud rate might be different

  pinMode(2,OUTPUT);
  digitalWrite(2,LOW);

  pinMode(3,OUTPUT);
  digitalWrite(3,LOW);

  pinMode(4,OUTPUT);
  digitalWrite(4,LOW);

  pinMode(6,OUTPUT);
  digitalWrite(6,LOW);

  sendCommand("AT+RST\r\n",2000,DEBUG); // reset module
  sendCommand("AT+CWMODE=2\r\n",1000,DEBUG); // configure as access point
  delay(1000);
  sendCommand("AT+CIFSR\r\n",1000,DEBUG); // get ip address
  sendCommand("AT+CIPMUX=1\r\n",1000,DEBUG); // configure for multiple connections
  sendCommand("AT+CIPSERVER=1,80\r\n",1000,DEBUG); // turn on server on port 80

  Serial.println("Server Ready");
}

void loop()
{
  if(esp8266.available()) // check if the esp is sending a message
  {

    if(esp8266.find("+IPD,"))
    {
     delay(1000); // wait for the serial buffer to fill up (read all the serial data)
     // get the connection id so that we can then disconnect
     int connectionId = esp8266.read()-48; // subtract 48 because the read() function returns
                                           // the ASCII decimal value and 0 (the first decimal number) starts at 48

     esp8266.find("pin="); // advance cursor to "pin="

     int pinNumber = (esp8266.read()-48); // get first number i.e. if the pin 13 then the 1st number is 1
     int secondNumber = (esp8266.read()-48);
     if(secondNumber>=0 && secondNumber<=9)
     {
      pinNumber*=10;
      pinNumber +=secondNumber; // get second number, i.e. if the pin number is 13 then the 2nd number is 3, then add to the first number
     }

     digitalWrite(pinNumber, !digitalRead(pinNumber)); // toggle pin

     // build string that is send back to device that is requesting pin toggle
     String content;
     content = "Pin ";
     content += pinNumber;
     content += " is ";

     if(digitalRead(pinNumber))
     {
       content += "ON";
     }
     else
     {
       content += "OFF";
     }

     sendHTTPResponse(connectionId,content);

     // make close command
     String closeCommand = "AT+CIPCLOSE=";
     closeCommand+=connectionId; // append connection id
     closeCommand+="\r\n";

     sendCommand(closeCommand,1000,DEBUG); // close connection
    }
  }
}

/*
* Name: sendData
* Description: Function used to send data to ESP8266.
* Params: command - the data/command to send; timeout - the time to wait for a response; debug - print to Serial window?(true = yes, false = no)
* Returns: The response from the esp8266 (if there is a reponse)
*/
String sendData(String command, const int timeout, boolean debug)
{
    String response = "";

    int dataSize = command.length();
    char data[dataSize];
    command.toCharArray(data,dataSize);

    esp8266.write(data,dataSize); // send the read character to the esp8266
    if(debug)
    {
      Serial.println("\r\n====== HTTP Response From Arduino ======");
      Serial.write(data,dataSize);
      Serial.println("\r\n========================================");
    }

    long int time = millis();

    while( (time+timeout) > millis())
    {
      while(esp8266.available())
      {

        // The esp has data so display its output to the serial window
        char c = esp8266.read(); // read the next character.
        response+=c;
      }
    }

    if(debug)
    {
      Serial.print(response);
    }

    return response;
}

/*
* Name: sendHTTPResponse
* Description: Function that sends HTTP 200, HTML UTF-8 response
*/
void sendHTTPResponse(int connectionId, String content)
{

     // build HTTP response
     String httpResponse;
     String httpHeader;
     // HTTP Header
     httpHeader = "HTTP/1.1 200 OK\r\nContent-Type: text/html; charset=UTF-8\r\n";
     httpHeader += "Content-Length: ";
     httpHeader += content.length();
     httpHeader += "\r\n";
     httpHeader +="Connection: close\r\n\r\n";
     httpResponse = httpHeader + content; // There is a bug in this code: the last character of "content" is not sent, I cheated by adding this extra space
     sendCIPData(connectionId,httpResponse);
}

/*
* Name: sendCIPDATA
* Description: sends a CIPSEND=<connectionId>,<data> command
*
*/
void sendCIPData(int connectionId, String data)
{
   String cipSend = "AT+CIPSEND=";
   cipSend += connectionId;
   cipSend += ",";
   cipSend +=data.length();
   cipSend +="\r\n";
   sendCommand(cipSend,1000,DEBUG);
   sendData(data,1000,DEBUG);
}

/*
* Name: sendCommand
* Description: Function used to send data to ESP8266.
* Params: command - the data/command to send; timeout - the time to wait for a response; debug - print to Serial window?(true = yes, false = no)
* Returns: The response from the esp8266 (if there is a reponse)
*/
String sendCommand(String command, const int timeout, boolean debug)
{
    String response = "";

    esp8266.print(command); // send the read character to the esp8266

    long int time = millis();

    while( (time+timeout) > millis())
    {
      while(esp8266.available())
      {

        // The esp has data so display its output to the serial window
        char c = esp8266.read(); // read the next character.
        response+=c;
      }
    }

    if(debug)
    {
      Serial.print(response);
    }

    return response;
}
</code>```

The code for android is as follow :

Mainactivity:

```<code>package com.example.autohome;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.SharedPreferences;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;

import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URI;
import java.net.URISyntaxException;

public class MainActivity extends Activity implements View.OnClickListener {

    public final static String PREF_IP = "PREF_IP_ADDRESS";
    public final static String PREF_PORT = "PREF_PORT_NUMBER";
    // declare buttons and text inputs
    private Button buttonPin11,buttonPin12,buttonPin13;
    private EditText editTextIPAddress, editTextPortNumber;
    // shared preferences objects used to save the IP address and port so that the user doesn't have to
    // type them next time he/she opens the app.
    SharedPreferences.Editor editor;
    SharedPreferences sharedPreferences;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        sharedPreferences = getSharedPreferences("HTTP_HELPER_PREFS",Context.MODE_PRIVATE);
        editor = sharedPreferences.edit();

        // assign buttons
        buttonPin11 = (Button)findViewById(R.id.buttonPin11);
        buttonPin12 = (Button)findViewById(R.id.buttonPin12);
        buttonPin13 = (Button)findViewById(R.id.buttonPin13);

        // assign text inputs
        editTextIPAddress = (EditText)findViewById(R.id.editTextIPAddress);
        editTextPortNumber = (EditText)findViewById(R.id.editTextPortNumber);

        // set button listener (this class)
        buttonPin11.setOnClickListener(this);
        buttonPin12.setOnClickListener(this);
        buttonPin13.setOnClickListener(this);

        // get the IP address and port number from the last time the user used the app,
        // put an empty string "" is this is the first time.
        editTextIPAddress.setText(sharedPreferences.getString(PREF_IP,""));
        editTextPortNumber.setText(sharedPreferences.getString(PREF_PORT,""));
    }

    @Override
    public void onClick(View view) {

        // get the pin number
        String parameterValue = "";
        // get the ip address
        String ipAddress = editTextIPAddress.getText().toString().trim();
        // get the port number
        String portNumber = editTextPortNumber.getText().toString().trim();

        // save the IP address and port for the next time the app is used
        editor.putString(PREF_IP,ipAddress); // set the ip address value to save
        editor.putString(PREF_PORT,portNumber); // set the port number to save
        editor.commit(); // save the IP and PORT

        // get the pin number from the button that was clicked
        if(view.getId()==buttonPin11.getId())
        {
            parameterValue = "2";
        }
        else if(view.getId()==buttonPin12.getId())
        {
            parameterValue = "3";
        }
        else
        {
            parameterValue = "4";
        }

        // execute HTTP request
        if(ipAddress.length()>0 && portNumber.length()>0) {
            new HttpRequestAsyncTask(
                    view.getContext(), parameterValue, ipAddress, portNumber, "pin"
            ).execute();
        }
    }

    /**
     * Description: Send an HTTP Get request to a specified ip address and port.
     * Also send a parameter "parameterName" with the value of "parameterValue".
     * @param parameterValue the pin number to toggle
     * @param ipAddress the ip address to send the request to
     * @param portNumber the port number of the ip address
     * @param parameterName
     * @return The ip address' reply text, or an ERROR message is it fails to receive one
     */
    public String sendRequest(String parameterValue, String ipAddress, String portNumber, String parameterName) {
        String serverResponse = "ERROR";

        try {

            HttpClient httpclient = new DefaultHttpClient(); // create an HTTP client
            // define the URL e.g. http://myIpaddress:myport/?pin=13 (to toggle pin 13 for example)
            URI website = new URI("http://"+ipAddress+":"+portNumber+"/?"+parameterName+"="+parameterValue);
            HttpGet getRequest = new HttpGet(); // create an HTTP GET object
            getRequest.setURI(website); // set the URL of the GET request
            HttpResponse response = httpclient.execute(getRequest); // execute the request
            // get the ip address server's reply
            InputStream content = null;
            content = response.getEntity().getContent();
            BufferedReader in = new BufferedReader(new InputStreamReader(
                    content
            ));
            serverResponse = in.readLine();
            // Close the connection
            content.close();
        } catch (ClientProtocolException e) {
            // HTTP error
            serverResponse = e.getMessage();
            e.printStackTrace();
        } catch (IOException e) {
            // IO error
            serverResponse = e.getMessage();
            e.printStackTrace();
        } catch (URISyntaxException e) {
            // URL syntax error
            serverResponse = e.getMessage();
            e.printStackTrace();
        }
        // return the server's reply/response text
        return serverResponse;
    }

    /**
     * An AsyncTask is needed to execute HTTP requests in the background so that they do not
     * block the user interface.
     */
    private class HttpRequestAsyncTask extends AsyncTask<Void, Void, Void> {

        // declare variables needed
        private String requestReply,ipAddress, portNumber;
        private Context context;
        private AlertDialog alertDialog;
        private String parameter;
        private String parameterValue;

        /**
         * Description: The asyncTask class constructor. Assigns the values used in its other methods.
         * @param context the application context, needed to create the dialog
         * @param parameterValue the pin number to toggle
         * @param ipAddress the ip address to send the request to
         * @param portNumber the port number of the ip address
         */
        public HttpRequestAsyncTask(Context context, String parameterValue, String ipAddress, String portNumber, String parameter)
        {
            this.context = context;

            alertDialog = new AlertDialog.Builder(this.context)
                    .setTitle("HTTP Response From IP Address:")
                    .setCancelable(true)
                    .create();

            this.ipAddress = ipAddress;
            this.parameterValue = parameterValue;
            this.portNumber = portNumber;
            this.parameter = parameter;
        }

        /**
         * Name: doInBackground
         * Description: Sends the request to the ip address
         * @param voids
         * @return
         */
        @Override
        protected Void doInBackground(Void... voids) {
            alertDialog.setMessage("Data sent, waiting for reply from server...");
            if(!alertDialog.isShowing())
            {
                alertDialog.show();
            }
            requestReply = sendRequest(parameterValue,ipAddress,portNumber, parameter);
            return null;
        }

        /**
         * Name: onPostExecute
         * Description: This function is executed after the HTTP request returns from the ip address.
         * The function sets the dialog's message with the reply text from the server and display the dialog
         * if it's not displayed already (in case it was closed by accident);
         * @param aVoid void parameter
         */
        @Override
        protected void onPostExecute(Void aVoid) {
            alertDialog.setMessage(requestReply);
            if(!alertDialog.isShowing())
            {
                alertDialog.show(); // show dialog
            }
        }

        /**
         * Name: onPreExecute
         * Description: This function is executed before the HTTP request is sent to ip address.
         * The function will set the dialog's message and display the dialog.
         */
        @Override
        protected void onPreExecute() {
            alertDialog.setMessage("Sending data to server, please wait...");
            if(!alertDialog.isShowing())
            {
                alertDialog.show();
            }
        }

    }
}
</code>```

Layout file:

```<code><?xml version="1.0" encoding="utf-8"?>
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
     >

    <LinearLayout
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:orientation="vertical">

        <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="20dp"
        android:text="IP Address:"
        android:id="@+id/textView" />

    <EditText
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:hint="e.g. 192.168.0.10"
        android:id="@+id/editTextIPAddress" />

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Port Number:"
        android:id="@+id/textView2" />

    <EditText
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:inputType="number"
        android:ems="10"
        android:hint="e.g. 80"
        android:id="@+id/editTextPortNumber" />

        <Button
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Pin 11"
        android:id="@+id/buttonPin11" />

    <Button
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Pin 12"
        android:id="@+id/buttonPin12" />

    <Button
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Pin 13"
        android:id="@+id/buttonPin13" />
    </LinearLayout>

</ScrollView>
</code>```

These are the serial monitor images.

When the response is not gibberish the program works. when its gibberish there is a problem

please forgive me if the post is lacking any information.
i also apologize for any mistakes in the post as it is my first

答: Mine experiments with ESP8266 on stock firmware made me think that communication baud rate 115200 works unstable.  Try 57600 instead,  this definitely works well. </p>

Body:
i have tried to make an android application to turn on or off led's using arduino.

esp8266 esp-01 provides access point .

But i cant turn off the led's using the there is always some error

also when i see the data in serial monitor it is partially gibberish

i have taken the code from  allaboutee.com/2015/01/20/esp8266-android-application-for-arduino-pin-control/

but it was modified by me because it was not working for me on 2 and 3 pins

I have used arduino uno.

The circuit diagram is like this

The code for arduino is as follows:

#include <SoftwareSerial.h>

#define DEBUG true

SoftwareSerial esp8266(10,11); // make RX Arduino line is pin 2, make TX Arduino line is pin 3.
                             // This means that you need to connect the TX line from the esp to the Arduino's pin 2
                             // and the RX line from the esp to the Arduino's pin 3
void setup()
{
  Serial.begin(115200);
  esp8266.begin(115200); // your esp's baud rate might be different

  pinMode(2,OUTPUT);
  digitalWrite(2,LOW);

  pinMode(3,OUTPUT);
  digitalWrite(3,LOW);

  pinMode(4,OUTPUT);
  digitalWrite(4,LOW);

  pinMode(6,OUTPUT);
  digitalWrite(6,LOW);

  sendCommand("AT+RST\r\n",2000,DEBUG); // reset module
  sendCommand("AT+CWMODE=2\r\n",1000,DEBUG); // configure as access point
  delay(1000);
  sendCommand("AT+CIFSR\r\n",1000,DEBUG); // get ip address
  sendCommand("AT+CIPMUX=1\r\n",1000,DEBUG); // configure for multiple connections
  sendCommand("AT+CIPSERVER=1,80\r\n",1000,DEBUG); // turn on server on port 80

  Serial.println("Server Ready");
}

void loop()
{
  if(esp8266.available()) // check if the esp is sending a message
  {

    if(esp8266.find("+IPD,"))
    {
     delay(1000); // wait for the serial buffer to fill up (read all the serial data)
     // get the connection id so that we can then disconnect
     int connectionId = esp8266.read()-48; // subtract 48 because the read() function returns
                                           // the ASCII decimal value and 0 (the first decimal number) starts at 48

     esp8266.find("pin="); // advance cursor to "pin="

     int pinNumber = (esp8266.read()-48); // get first number i.e. if the pin 13 then the 1st number is 1
     int secondNumber = (esp8266.read()-48);
     if(secondNumber>=0 && secondNumber<=9)
     {
      pinNumber*=10;
      pinNumber +=secondNumber; // get second number, i.e. if the pin number is 13 then the 2nd number is 3, then add to the first number
     }

     digitalWrite(pinNumber, !digitalRead(pinNumber)); // toggle pin

     // build string that is send back to device that is requesting pin toggle
     String content;
     content = "Pin ";
     content += pinNumber;
     content += " is ";

     if(digitalRead(pinNumber))
     {
       content += "ON";
     }
     else
     {
       content += "OFF";
     }

     sendHTTPResponse(connectionId,content);

     // make close command
     String closeCommand = "AT+CIPCLOSE=";
     closeCommand+=connectionId; // append connection id
     closeCommand+="\r\n";

     sendCommand(closeCommand,1000,DEBUG); // close connection
    }
  }
}

/*
* Name: sendData
* Description: Function used to send data to ESP8266.
* Params: command - the data/command to send; timeout - the time to wait for a response; debug - print to Serial window?(true = yes, false = no)
* Returns: The response from the esp8266 (if there is a reponse)
*/
String sendData(String command, const int timeout, boolean debug)
{
    String response = "";

    int dataSize = command.length();
    char data[dataSize];
    command.toCharArray(data,dataSize);

    esp8266.write(data,dataSize); // send the read character to the esp8266
    if(debug)
    {
      Serial.println("\r\n====== HTTP Response From Arduino ======");
      Serial.write(data,dataSize);
      Serial.println("\r\n========================================");
    }

    long int time = millis();

    while( (time+timeout) > millis())
    {
      while(esp8266.available())
      {

        // The esp has data so display its output to the serial window
        char c = esp8266.read(); // read the next character.
        response+=c;
      }
    }

    if(debug)
    {
      Serial.print(response);
    }

    return response;
}

/*
* Name: sendHTTPResponse
* Description: Function that sends HTTP 200, HTML UTF-8 response
*/
void sendHTTPResponse(int connectionId, String content)
{

     // build HTTP response
     String httpResponse;
     String httpHeader;
     // HTTP Header
     httpHeader = "HTTP/1.1 200 OK\r\nContent-Type: text/html; charset=UTF-8\r\n";
     httpHeader += "Content-Length: ";
     httpHeader += content.length();
     httpHeader += "\r\n";
     httpHeader +="Connection: close\r\n\r\n";
     httpResponse = httpHeader + content; // There is a bug in this code: the last character of "content" is not sent, I cheated by adding this extra space
     sendCIPData(connectionId,httpResponse);
}

/*
* Name: sendCIPDATA
* Description: sends a CIPSEND=<connectionId>,<data> command
*
*/
void sendCIPData(int connectionId, String data)
{
   String cipSend = "AT+CIPSEND=";
   cipSend += connectionId;
   cipSend += ",";
   cipSend +=data.length();
   cipSend +="\r\n";
   sendCommand(cipSend,1000,DEBUG);
   sendData(data,1000,DEBUG);
}

/*
* Name: sendCommand
* Description: Function used to send data to ESP8266.
* Params: command - the data/command to send; timeout - the time to wait for a response; debug - print to Serial window?(true = yes, false = no)
* Returns: The response from the esp8266 (if there is a reponse)
*/
String sendCommand(String command, const int timeout, boolean debug)
{
    String response = "";

    esp8266.print(command); // send the read character to the esp8266

    long int time = millis();

    while( (time+timeout) > millis())
    {
      while(esp8266.available())
      {

        // The esp has data so display its output to the serial window
        char c = esp8266.read(); // read the next character.
        response+=c;
      }
    }

    if(debug)
    {
      Serial.print(response);
    }

    return response;
}

The code for android is as follow :

Mainactivity:

package com.example.autohome;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.SharedPreferences;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;

import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URI;
import java.net.URISyntaxException;

public class MainActivity extends Activity implements View.OnClickListener {

    public final static String PREF_IP = "PREF_IP_ADDRESS";
    public final static String PREF_PORT = "PREF_PORT_NUMBER";
    // declare buttons and text inputs
    private Button buttonPin11,buttonPin12,buttonPin13;
    private EditText editTextIPAddress, editTextPortNumber;
    // shared preferences objects used to save the IP address and port so that the user doesn't have to
    // type them next time he/she opens the app.
    SharedPreferences.Editor editor;
    SharedPreferences sharedPreferences;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        sharedPreferences = getSharedPreferences("HTTP_HELPER_PREFS",Context.MODE_PRIVATE);
        editor = sharedPreferences.edit();

        // assign buttons
        buttonPin11 = (Button)findViewById(R.id.buttonPin11);
        buttonPin12 = (Button)findViewById(R.id.buttonPin12);
        buttonPin13 = (Button)findViewById(R.id.buttonPin13);

        // assign text inputs
        editTextIPAddress = (EditText)findViewById(R.id.editTextIPAddress);
        editTextPortNumber = (EditText)findViewById(R.id.editTextPortNumber);

        // set button listener (this class)
        buttonPin11.setOnClickListener(this);
        buttonPin12.setOnClickListener(this);
        buttonPin13.setOnClickListener(this);

        // get the IP address and port number from the last time the user used the app,
        // put an empty string "" is this is the first time.
        editTextIPAddress.setText(sharedPreferences.getString(PREF_IP,""));
        editTextPortNumber.setText(sharedPreferences.getString(PREF_PORT,""));
    }

    @Override
    public void onClick(View view) {

        // get the pin number
        String parameterValue = "";
        // get the ip address
        String ipAddress = editTextIPAddress.getText().toString().trim();
        // get the port number
        String portNumber = editTextPortNumber.getText().toString().trim();

        // save the IP address and port for the next time the app is used
        editor.putString(PREF_IP,ipAddress); // set the ip address value to save
        editor.putString(PREF_PORT,portNumber); // set the port number to save
        editor.commit(); // save the IP and PORT

        // get the pin number from the button that was clicked
        if(view.getId()==buttonPin11.getId())
        {
            parameterValue = "2";
        }
        else if(view.getId()==buttonPin12.getId())
        {
            parameterValue = "3";
        }
        else
        {
            parameterValue = "4";
        }

        // execute HTTP request
        if(ipAddress.length()>0 && portNumber.length()>0) {
            new HttpRequestAsyncTask(
                    view.getContext(), parameterValue, ipAddress, portNumber, "pin"
            ).execute();
        }
    }

    /**
     * Description: Send an HTTP Get request to a specified ip address and port.
     * Also send a parameter "parameterName" with the value of "parameterValue".
     * @param parameterValue the pin number to toggle
     * @param ipAddress the ip address to send the request to
     * @param portNumber the port number of the ip address
     * @param parameterName
     * @return The ip address' reply text, or an ERROR message is it fails to receive one
     */
    public String sendRequest(String parameterValue, String ipAddress, String portNumber, String parameterName) {
        String serverResponse = "ERROR";

        try {

            HttpClient httpclient = new DefaultHttpClient(); // create an HTTP client
            // define the URL e.g. http://myIpaddress:myport/?pin=13 (to toggle pin 13 for example)
            URI website = new URI("http://"+ipAddress+":"+portNumber+"/?"+parameterName+"="+parameterValue);
            HttpGet getRequest = new HttpGet(); // create an HTTP GET object
            getRequest.setURI(website); // set the URL of the GET request
            HttpResponse response = httpclient.execute(getRequest); // execute the request
            // get the ip address server's reply
            InputStream content = null;
            content = response.getEntity().getContent();
            BufferedReader in = new BufferedReader(new InputStreamReader(
                    content
            ));
            serverResponse = in.readLine();
            // Close the connection
            content.close();
        } catch (ClientProtocolException e) {
            // HTTP error
            serverResponse = e.getMessage();
            e.printStackTrace();
        } catch (IOException e) {
            // IO error
            serverResponse = e.getMessage();
            e.printStackTrace();
        } catch (URISyntaxException e) {
            // URL syntax error
            serverResponse = e.getMessage();
            e.printStackTrace();
        }
        // return the server's reply/response text
        return serverResponse;
    }

    /**
     * An AsyncTask is needed to execute HTTP requests in the background so that they do not
     * block the user interface.
     */
    private class HttpRequestAsyncTask extends AsyncTask<Void, Void, Void> {

        // declare variables needed
        private String requestReply,ipAddress, portNumber;
        private Context context;
        private AlertDialog alertDialog;
        private String parameter;
        private String parameterValue;

        /**
         * Description: The asyncTask class constructor. Assigns the values used in its other methods.
         * @param context the application context, needed to create the dialog
         * @param parameterValue the pin number to toggle
         * @param ipAddress the ip address to send the request to
         * @param portNumber the port number of the ip address
         */
        public HttpRequestAsyncTask(Context context, String parameterValue, String ipAddress, String portNumber, String parameter)
        {
            this.context = context;

            alertDialog = new AlertDialog.Builder(this.context)
                    .setTitle("HTTP Response From IP Address:")
                    .setCancelable(true)
                    .create();

            this.ipAddress = ipAddress;
            this.parameterValue = parameterValue;
            this.portNumber = portNumber;
            this.parameter = parameter;
        }

        /**
         * Name: doInBackground
         * Description: Sends the request to the ip address
         * @param voids
         * @return
         */
        @Override
        protected Void doInBackground(Void... voids) {
            alertDialog.setMessage("Data sent, waiting for reply from server...");
            if(!alertDialog.isShowing())
            {
                alertDialog.show();
            }
            requestReply = sendRequest(parameterValue,ipAddress,portNumber, parameter);
            return null;
        }

        /**
         * Name: onPostExecute
         * Description: This function is executed after the HTTP request returns from the ip address.
         * The function sets the dialog's message with the reply text from the server and display the dialog
         * if it's not displayed already (in case it was closed by accident);
         * @param aVoid void parameter
         */
        @Override
        protected void onPostExecute(Void aVoid) {
            alertDialog.setMessage(requestReply);
            if(!alertDialog.isShowing())
            {
                alertDialog.show(); // show dialog
            }
        }

        /**
         * Name: onPreExecute
         * Description: This function is executed before the HTTP request is sent to ip address.
         * The function will set the dialog's message and display the dialog.
         */
        @Override
        protected void onPreExecute() {
            alertDialog.setMessage("Sending data to server, please wait...");
            if(!alertDialog.isShowing())
            {
                alertDialog.show();
            }
        }

    }
}

Layout file:

<?xml version="1.0" encoding="utf-8"?>
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
     >

    <LinearLayout
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:orientation="vertical">

        <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="20dp"
        android:text="IP Address:"
        android:id="@+id/textView" />

    <EditText
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:hint="e.g. 192.168.0.10"
        android:id="@+id/editTextIPAddress" />

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Port Number:"
        android:id="@+id/textView2" />

    <EditText
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:inputType="number"
        android:ems="10"
        android:hint="e.g. 80"
        android:id="@+id/editTextPortNumber" />

        <Button
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Pin 11"
        android:id="@+id/buttonPin11" />

    <Button
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Pin 12"
        android:id="@+id/buttonPin12" />

    <Button
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Pin 13"
        android:id="@+id/buttonPin13" />
    </LinearLayout>

</ScrollView>

These are the serial monitor images.

When the response is not gibberish the program works. when its gibberish there is a problem

please forgive me if the post is lacking any information.
i also apologize for any mistakes in the post as it is my first


问:
Changing Xamarin Themes,styles per client approach
what approach would you use if you have a mobile app build using xamarin and this app is like a vanilla app.

Each client should be able to apply their own style to labels etc.. theme

Basically all the views/pages are the same for all the clients but the style per page will change for each individual client.

If this wasn't a mobile app I would have plugins within a folder and depending on the client i would drop the relative plugin in the pluginFolder eg:pluginClientA etc.. and this would be discovered at runtime usin mef.

Any suggestions

答:
Set you styles up as dynamicresources as seen here https://developer.xamarin.com/guides/xamarin-forms/user-interface/styles/dynamic/

I only have 2 themes so I have them specified in xaml

```<code><ResourceDictionary>
        <Color x:Key="Primary">#337ab7</Color>
        <Color x:Key="Accent">#96d1ff</Color>
        <Color x:Key="BackgroundColor">#C0C0C0</Color>
        <Color x:Key="TextColor">White</Color>

        <!-- Buttons -->
        <Style x:Key="buttonStyle" TargetType="Button">
            <Setter Property="BorderRadius" Value="4" />
            <Setter Property="FontSize" Value="48" />
            <Setter Property="FontAttributes" Value="Bold" ></Setter>
                <Setter Property="HeightRequest">
                <Setter.Value>
                    <OnPlatform x:TypeArguments="x:Double" iOS="80" Android="80" />
                </Setter.Value>
            </Setter>
            <Setter Property="WidthRequest">
                <Setter.Value>
                    <OnPlatform x:TypeArguments="x:Double" iOS="150" Android="150" />
                </Setter.Value>
            </Setter>
        </Style>
        <Style x:Key="btnPrimary" TargetType="Button" BasedOn="{StaticResource buttonStyle}">
            <Setter Property="TextColor" Value="{DynamicResource TextColor}" />
            <Setter Property="BackgroundColor" Value="{DynamicResource Primary}" />
        </Style>

        <!--Light Theme-->
        <Color x:Key="Primary-Light">#2196F3</Color>
        <Color x:Key="BackgroundColor-Light">#FAFAFA</Color>
        <Color x:Key="TextColor-Light">White</Color>

        <!--Dark Theme-->
        <Color x:Key="Primary-Dark">#1976D2</Color>
        <Color x:Key="BackgroundColor-Dark">#C0C0C0</Color>
        <Color x:Key="TextColor-Dark">Black</Color>

    </ResourceDictionary>
</code>```

So in the theme change event you can change the assigned colours

```<code>Resources ["Primary"] = Resources ["Primary-Dark"];
</code>```

Body:
Set you styles up as dynamicresources as seen here https://developer.xamarin.com/guides/xamarin-forms/user-interface/styles/dynamic/

I only have 2 themes so I have them specified in xaml

<ResourceDictionary>
        <Color x:Key="Primary">#337ab7</Color>
        <Color x:Key="Accent">#96d1ff</Color>
        <Color x:Key="BackgroundColor">#C0C0C0</Color>
        <Color x:Key="TextColor">White</Color>

        <!-- Buttons -->
        <Style x:Key="buttonStyle" TargetType="Button">
            <Setter Property="BorderRadius" Value="4" />
            <Setter Property="FontSize" Value="48" />
            <Setter Property="FontAttributes" Value="Bold" ></Setter>
                <Setter Property="HeightRequest">
                <Setter.Value>
                    <OnPlatform x:TypeArguments="x:Double" iOS="80" Android="80" />
                </Setter.Value>
            </Setter>
            <Setter Property="WidthRequest">
                <Setter.Value>
                    <OnPlatform x:TypeArguments="x:Double" iOS="150" Android="150" />
                </Setter.Value>
            </Setter>
        </Style>
        <Style x:Key="btnPrimary" TargetType="Button" BasedOn="{StaticResource buttonStyle}">
            <Setter Property="TextColor" Value="{DynamicResource TextColor}" />
            <Setter Property="BackgroundColor" Value="{DynamicResource Primary}" />
        </Style>

        <!--Light Theme-->
        <Color x:Key="Primary-Light">#2196F3</Color>
        <Color x:Key="BackgroundColor-Light">#FAFAFA</Color>
        <Color x:Key="TextColor-Light">White</Color>

        <!--Dark Theme-->
        <Color x:Key="Primary-Dark">#1976D2</Color>
        <Color x:Key="BackgroundColor-Dark">#C0C0C0</Color>
        <Color x:Key="TextColor-Dark">Black</Color>

    </ResourceDictionary>

So in the theme change event you can change the assigned colours

Resources ["Primary"] = Resources ["Primary-Dark"];


答:
Your query string need to encode ampersand(&) as percent-encode as %26. Your url will be like :</p>

```<code>index.php?a=orange%26apple
</code>```

Title: Ampersand doesn't load in Query String - PHP

Body:
Your query string need to encode ampersand(&) as percent-encode as %26. Your url will be like :

index.php?a=orange%26apple


问:
detect when challenge window is closed for Google recaptcha
I am using Google invisible recaptcha. Is there a way to detect when the challenge window is closed? By challenge window I mean window where you have to pick some images for verification.

I currently put a spinner on the button that rendered the recaptcha challenge, once the button is clicked. There is no way for the user to be prompted with another challenge window.

I am calling render function programmatically:

```<code>grecaptcha.render(htmlElement, { callback: this.verified, expiredCallback: this.resetRecaptcha, sitekey: this.siteKey, theme: "light", size: "invisible" });
</code>```

I have 2 callback functions wired up the verified and the resetRecaptcha functions which look like:

```<code>function resetRecaptcha() {
        grecaptcha.reset();
    }

function verified(recaptchaResponse)
{
/*
which calls the server to validate
*/
}
</code>```

I would have expected that grecaptcha.render has another callback that is called when the challenge screen is closed without the user verifying himself by selecting the images.

答:
As you mention, the API doesn't support this feature.

However, you can add this feature yourself. You may use the following code with caution, Google might change its reCaptcha and by doing so break this custom code. The solution relies on two characteristics of reCaptcha, so if the code doesn't work, look there first:

the window iframe src: contains "google.com/recaptcha/api2/bframe"

the CSS opacity property: changed to 0 when the window is closed

```<code>// to begin: we listen to the click on our submit button
// where the invisible reCaptcha has been attachtted to
// when clicked the first time, we setup the close listener
recaptchaButton.addEventListener('click', function(){
    if(!window.recaptchaCloseListener) initListener()

})

function initListener() {

    // set a global to tell that we are listening
    window.recaptchaCloseListener = true

    // find the open reCaptcha window
    HTMLCollection.prototype.find = Array.prototype.find
    var recaptchaWindow = document
        .getElementsByTagName('iframe')
        .find(x=>x.src.includes('google.com/recaptcha/api2/bframe'))
        .parentNode.parentNode

    // and now we are listening on CSS changes on it
    // when the opacity has been changed to 0 we know that
    // the window has been closed
    new MutationObserver(x => recaptchaWindow.style.opacity == 0 && onClose())
        .observe(recaptchaWindow, { attributes: true, attributeFilter: ['style'] })

}

// now do something with this information
function onClose() {
    console.log('recaptcha window has been closed')
}
</code>```

Body:
I am using Google invisible recaptcha. Is there a way to detect when the challenge window is closed? By challenge window I mean window where you have to pick some images for verification.

I currently put a spinner on the button that rendered the recaptcha challenge, once the button is clicked. There is no way for the user to be prompted with another challenge window.

I am calling render function programmatically:

grecaptcha.render(htmlElement, { callback: this.verified, expiredCallback: this.resetRecaptcha, sitekey: this.siteKey, theme: "light", size: "invisible" });

I have 2 callback functions wired up the verified and the resetRecaptcha functions which look like:

function resetRecaptcha() {
        grecaptcha.reset();
    }

function verified(recaptchaResponse)
{
/*
which calls the server to validate
*/
}

I would have expected that grecaptcha.render has another callback that is called when the challenge screen is closed without the user verifying himself by selecting the images.

Body:
As you mention, the API doesn't support this feature.

However, you can add this feature yourself. You may use the following code with caution, Google might change its reCaptcha and by doing so break this custom code. The solution relies on two characteristics of reCaptcha, so if the code doesn't work, look there first:

the window iframe src: contains "google.com/recaptcha/api2/bframe"

the CSS opacity property: changed to 0 when the window is closed

// to begin: we listen to the click on our submit button
// where the invisible reCaptcha has been attachtted to
// when clicked the first time, we setup the close listener
recaptchaButton.addEventListener('click', function(){
    if(!window.recaptchaCloseListener) initListener()

})

function initListener() {

    // set a global to tell that we are listening
    window.recaptchaCloseListener = true

    // find the open reCaptcha window
    HTMLCollection.prototype.find = Array.prototype.find
    var recaptchaWindow = document
        .getElementsByTagName('iframe')
        .find(x=>x.src.includes('google.com/recaptcha/api2/bframe'))
        .parentNode.parentNode

    // and now we are listening on CSS changes on it
    // when the opacity has been changed to 0 we know that
    // the window has been closed
    new MutationObserver(x => recaptchaWindow.style.opacity == 0 && onClose())
        .observe(recaptchaWindow, { attributes: true, attributeFilter: ['style'] })

}

// now do something with this information
function onClose() {
    console.log('recaptcha window has been closed')
}


问:
Modular GWT design concerns
I have a couple of questions regarding a modular GWT based application framework. I have some ideas about them but being new to the field of web development I feel they are far from ideal. I'd appreciate a few comments and suggestions in this regard. Here are my questions:

I am developing a framework which will allow third parties to embed GWT applications into our website and do some communication with them using simple iFrame postMessage. All these third party modules are going to use our SDK which is also GWT based. The problem arises that even though all the modules will be using the same codebase there is going to be a massive overheard in the amount of duplicate Javascript code (i.e. our common SDK code base which is quite large) being downloaded on the client's machine. This is highly redundant and problematic, not only due to the sheer size of duplicate code but, also due to the fact that subsequent updates of the SDK would require the modules to be recompiled which is going to create a DLL hell kind of scenario in the long run. What is the best way of doing this kind of thing? Is there a way where I can have some static GWT code (i.e. the SDK) and the dynamic GWT module refers to it (even if lies on a different domain) and it all work happily?

The other part of the problem lies in providing robust scripting front end to the SDK. At first it appears to be trivial since Javascript itself is a scripting language. However, I do not know how to load and call a piece of pure Javascript code at runtime? I am willing to put restrictions on the target Javascript (i.e. having a function main and unique namespace or something). Furthermore the Javascript will come as a string from a database and not as a full URL. If its doable in Javascript how does one get this right in GWT i.e. forcing the compiler to emit a certain function in the generated Javascript? This I believe can be lesser of a problem by having a stub Javascript with all the right requirements which just loads up a GWT generated Javascript. Is any of this possible at all?

I generally hate to be this verbose but I hope to find a quick solution to the problem as its holding up my progress. I'd highly appreciate any comments, suggestions and experiences.

答:
Regarding modularity I would build a OSGi based solution.

See this topic for instance:
Web Application using OSGi and GWT

Title: Modular GWT design concerns


答:
Write it like this:</p>

```<code>index.php?a=orange&b=apple

// Values

$_GET['a'];
$_GET['b'];
</code>```

Body:
Write it like this:

index.php?a=orange&b=apple

// Values

$_GET['a'];
$_GET['b'];


问:
Python event has not Key attribute
I am trying to create a program for when my character moves. here is my code

```<code>while True:
   for event in pygame.event.get():
       if event.type == QUIT:
            pygame.quit()
            sys.exit()
        elif event.type == KEYDOWN:
            if(event.key == K_RIGHT):
            playerPos[0] +=1
    if (event.key == K_RIGHT) and playerPos[0] < MAPWIDTH -1:
        playerPos[0] =+ 1
</code>```

here is the error

```<code>Traceback (most recent call last):
  File "H:\python things\firstgame.py", line 90, in <module>
if (event.key == K_RIGHT) and playerPos[0] < MAPWIDTH -1:
AttributeError: 'Event' object has no attribute 'key'
</code>```

答:
In case anyone comes across this post and had same issue, I fixed my error and ended up with this. added comments to help others understand</p>

```<code>while True:
    #get all the user events
    for event in pygame.event.get():

        #if user wants to quit
        if event.type == pygame.locals.QUIT:
            #and the game close the window
            pygame.quit()
            sys.exit()

        #if a key is pressed
        elif event.type == pygame.locals.KEYDOWN:
            #if right arrow is pressed
            if event.key == K_RIGHT and playerPos[0] < MAPWIDTH - 1:
                #change player's x postion
                playerPos[0] +=1
            if event.key == K_LEFT and playerPos[0] > 0:
                #change player x position
                playerPos[0] -=1
            if event.key == K_UP and playerPos[0] > 0:
                #change players x position
                playerPos[1] -=1
            if event.key == K_DOWN and playerPos[1] < MAPHEIGHT -1:
                #change player x position
                playerPos[1] += 1
</code>```

Title: Python event has not Key attribute

Body:
I am trying to create a program for when my character moves. here is my code

while True:
   for event in pygame.event.get():
       if event.type == QUIT:
            pygame.quit()
            sys.exit()
        elif event.type == KEYDOWN:
            if(event.key == K_RIGHT):
            playerPos[0] +=1
    if (event.key == K_RIGHT) and playerPos[0] < MAPWIDTH -1:
        playerPos[0] =+ 1

here is the error

Traceback (most recent call last):
  File "H:\python things\firstgame.py", line 90, in <module>
if (event.key == K_RIGHT) and playerPos[0] < MAPWIDTH -1:
AttributeError: 'Event' object has no attribute 'key'

Body:
In case anyone comes across this post and had same issue, I fixed my error and ended up with this. added comments to help others understand

while True:
    #get all the user events
    for event in pygame.event.get():

        #if user wants to quit
        if event.type == pygame.locals.QUIT:
            #and the game close the window
            pygame.quit()
            sys.exit()

        #if a key is pressed
        elif event.type == pygame.locals.KEYDOWN:
            #if right arrow is pressed
            if event.key == K_RIGHT and playerPos[0] < MAPWIDTH - 1:
                #change player's x postion
                playerPos[0] +=1
            if event.key == K_LEFT and playerPos[0] > 0:
                #change player x position
                playerPos[0] -=1
            if event.key == K_UP and playerPos[0] > 0:
                #change players x position
                playerPos[1] -=1
            if event.key == K_DOWN and playerPos[1] < MAPHEIGHT -1:
                #change player x position
                playerPos[1] += 1


问:
PHP / AJAX not getting return
I am using AJAX to receive data from my database on to my main PHP page.
I have a piece of code that worked, but on with PHP.
When I have just tried to put it in to AJAX (receiving format), the code that I return is not being shown.

I know my AJAX method works as I'm using it to get some other database values.
It's just the Get online users individually won't work.

When I load the page, the code shows what's inside my div id - Loading Info... and then goes blank, so I know it's trying to update it but it's not getting it correctly.

Picture showing that nothing is displayed

My PHP request code is :

```<code>//Get online users individually and echo if they're online or not in a div class
$user_grab = mysqli_query($con, "SELECT * FROM users");
while($users_ = mysqli_fetch_array($user_grab)) {

$last_online = strtotime($users_['lastonline']);

if(time() - $last_online < 30) {
    $client_is_online = '
         <div class="chat-list-item -available" style="background: rgba(255,255,255,0.1); padding: 5px;">
            <img class="chat-list-avatar" src="'.$users_['profile_picture'].'" style="width: 40px; height: 40px; padding: 7px; border-radius: 20px;" /><i class="fa fa-circle chat-list-status"> </i>
            <div class="chat-list-user">'.$users_['username'].' (<font size="2">'.get_users_level_all($users_['userLevel']).'</font>)</div>
            <div class="chat-list-excerpt">Online</div>
         </div>
    ';
} else {
    $client_is_online = '
         <div class="chat-list-item -offline" style="background: rgba(255,255,255,0.1); padding: 5px;">
            <img class="chat-list-avatar" src="'.$users_['profile_picture'].'" style="width: 40px; height: 40px; padding: 7px; border-radius: 20px;" /><i class="fa fa-circle chat-list-status"> </i>
            <div class="chat-list-user">'.$users_['username'].' (<font size="2">'.get_users_level_all($users_['userLevel']).'</font>)</div>
            <div class="chat-list-excerpt">Offline</div>
         </div>
    ';
}
}

//I then echo it back to my home PHP page so it can read the values
//Ignore my other code definitions below as I know they work
//$client_is_online is the only one which doesn't
echo $totalUsers.",".$totalOnline.",".$freemode.",".$bypasses.",".$client_is_online;
</code>```

My AJAX recieve code is :

```<code><script>
    function fetchOnline() {
        $.ajax({
            url: "includes/get_dash_settings.php",
            context: document.body,
            success: function(value){
                var data = value.split(",");
                $('#totalUsers').html(data[0]);
                $('#totalOnline').html(data[1]);
                $('#freeModeStatus').html(data[2]);
                $('#bypassesStatus').html(data[3]);
                $('#isOnline').html(data[4]);
            },
            complete:function(){
               setTimeout(fetchOnline,5000);
            }
        })
    }

    $(document).ready(function() { setInterval(fetchOnline,5000); });
</script>
</code>```

I then try storing the returned data in-side my div id :

```<code>   <div class="sidebar-tab-content" id="staff">
      <div class="chat-list sidebar-content-section" id="isOnline">
      Loading Info...
      </div>
   </div>
</code>```

答:
Return the json data like this

1st : your overwriting the variable . you need to concatenate all user like this

```<code>  $client_is_online=""; //declare empty string before while loop start
 //while loop start here

 $client_is_online .= 'html here';

 // while end here
</code>```

2nd : Return the json data like this

```<code>$response = array ('totalUsers'=> $totalUsers, 'totalOnline'=> $totalOnline,'freemode'=>$freemode,'bypasses'=>$bypasses,'client_is_online'=>$client_is_online);
header('Content-Type: application/json');
echo json_encode($response);
</code>```

3rd :  Don't forgot to add dataType in ajax

```<code>dataType: "json",
</code>```

4rd : success function should be changed like this

ajax  :

```<code>success: function(value){
            var data = JSON.parse(value);
            $('#totalUsers').html(data['totalUsers']);
            $('#totalOnline').html(data['totalOnline']);
            $('#freeModeStatus').html(data['freemode']);
            $('#bypassesStatus').html(data['bypasses']);
            $('#isOnline').html(data['client_is_online']);
        },
</code>```

Title: PHP / AJAX not getting return

Body:
I am using AJAX to receive data from my database on to my main PHP page.
I have a piece of code that worked, but on with PHP.
When I have just tried to put it in to AJAX (receiving format), the code that I return is not being shown.

I know my AJAX method works as I'm using it to get some other database values.
It's just the Get online users individually won't work.

When I load the page, the code shows what's inside my div id - Loading Info... and then goes blank, so I know it's trying to update it but it's not getting it correctly.

Picture showing that nothing is displayed

My PHP request code is :

//Get online users individually and echo if they're online or not in a div class
$user_grab = mysqli_query($con, "SELECT * FROM users");
while($users_ = mysqli_fetch_array($user_grab)) {

$last_online = strtotime($users_['lastonline']);

if(time() - $last_online < 30) {
    $client_is_online = '

'.$users_['username'].' ('.get_users_level_all($users_['userLevel']).')

Online

    ';
} else {
    $client_is_online = '

'.$users_['username'].' ('.get_users_level_all($users_['userLevel']).')

Offline

    ';
}
}

//I then echo it back to my home PHP page so it can read the values
//Ignore my other code definitions below as I know they work
//$client_is_online is the only one which doesn't
echo $totalUsers.",".$totalOnline.",".$freemode.",".$bypasses.",".$client_is_online;

My AJAX recieve code is :

I then try storing the returned data in-side my div id :

      Loading Info...

Body:
Return the json data like this

1st : your overwriting the variable . you need to concatenate all user like this

  $client_is_online=""; //declare empty string before while loop start
 //while loop start here

 $client_is_online .= 'html here';

 // while end here

2nd : Return the json data like this

$response = array ('totalUsers'=> $totalUsers, 'totalOnline'=> $totalOnline,'freemode'=>$freemode,'bypasses'=>$bypasses,'client_is_online'=>$client_is_online);
header('Content-Type: application/json');
echo json_encode($response);

3rd :  Don't forgot to add dataType in ajax

dataType: "json",

4rd : success function should be changed like this

ajax  :

success: function(value){
            var data = JSON.parse(value);
            $('#totalUsers').html(data['totalUsers']);
            $('#totalOnline').html(data['totalOnline']);
            $('#freeModeStatus').html(data['freemode']);
            $('#bypassesStatus').html(data['bypasses']);
            $('#isOnline').html(data['client_is_online']);
        },


问:
Ignore a folder in search results
I'm searching for a string and getting matches in a source folder, and a build folder (file in source gets copied to build during build).

I do not need the build folder result.

Vim has wildignore which helps filter out results.

Is there something similar in intelij?

答:
In Intellij 15, to exclude a folder just do this:

in the Project window, select the folder then right click and choose "Mark Directory As" > "Excluded"

Title: Ignore a folder in search results


问:
Create parameterized VIEW in SQL Server 2008
Can we create parameterized VIEW in SQL Server 2008.

Or Any other alternative for this ?

答:
in fact there exists one trick:

```<code>create view view_test as

select
  *
from
  table
where id = (select convert(int, convert(binary(4), context_info)) from master.dbo.sysprocesses
where
spid = @@spid)
</code>```

...
in sql-query:

```<code>set context_info 2
select * from view_test
</code>```

will be the same with

```<code>select * from table where id = 2
</code>```

but using udf is more acceptable

Body:
in fact there exists one trick:

create view view_test as

select
  *
from
  table
where id = (select convert(int, convert(binary(4), context_info)) from master.dbo.sysprocesses
where
spid = @@spid)

...
in sql-query:

set context_info 2
select * from view_test

will be the same with

select * from table where id = 2

but using udf is more acceptable


问:
How to pass data from Activity to fragment inside fragment
I have an Activity. It adds Fragment A dynamically. Fragment A contains static added (by xml) child Fragment B. How can I pass data from Activity to Fragment B when i add Fragment A to Activity?

I know next approach:

Implement interface getter in Activity and call getter method from Fragment B

I'd like to know, are there another ways to do it?

I tried set arguments from Activity to Fragment A, find Fragment B by child fragment manager and set arguments from Fragment A to Fragment B.
But Fragment B created earlier than Fragment A, so i had exceptions..

答:
You can try EventBus to pass data from Activity to your Fragment B. In your activity call this EventBus.getDefault().post(new MessageEvent());

And then you just need to register EventBus in onCreateView of Fragment B

```<code>EventBus.getDefault().register(this);
</code>```

And then

```<code>@Subscribe
public void onEvent(MessageEvent event){

    // DO SOMETHING
}
</code>```

Body:
You can try EventBus to pass data from Activity to your Fragment B. In your activity call this EventBus.getDefault().post(new MessageEvent());

And then you just need to register EventBus in onCreateView of Fragment B

EventBus.getDefault().register(this);

And then

@Subscribe
public void onEvent(MessageEvent event){

    // DO SOMETHING
}


问:
Parse error in list monad's `do` notation
OK, so here's a weird one.

This works perfectly:

```<code>test = do
  x <- [1..5]
  y <- [1..5]
  [x+y, x-y]
</code>```

But this:

```<code>test = do
  x <- [1..5]
  y <- [1..5]
  [
    x+y,
    x-y
  ]
</code>```

fails miserably. GHC utterly refuses to parse this. No matter how I fidget with it, I can't seem to convince GHC to allow me to spread the list across multiple lines. Which is a problem, because if you replace x+y and x-y with really big expressions, it quickly becomes hard to read...

Does anybody know why isn't this working, and how can I force it to work? (Or at least do something that looks legible?)

答:
Here are a couple of possible ways to write this legally:</p>

```<code>test = do
  [x,y] <- replicateM 2 [1..5]
  [
    x+y
   ,x-y
   ]

test = do
  [x,y] <- replicateM 2 [1..5]
  [ x+y
   ,x-y ]

test = do
  [x,y] <- replicateM 2 [1..5]
  [ x+y ,
    x-y ]

test = do
  [x,y] <- replicateM 2 [1..5]
  id [ x+y
     , x-y ]

test = do
  [x,y] <- replicateM 2 [1..5]
  id [
       x+y,
       x-y
     ]

test = do
  [x,y] <- replicateM 2 [1..5]
  ([
     x+y,
     x-y
   ])
</code>```

Body:
OK, so here's a weird one.

This works perfectly:

test = do
  x <- [1..5]
  y <- [1..5]
  [x+y, x-y]

But this:

test = do
  x <- [1..5]
  y <- [1..5]
  [
    x+y,
    x-y
  ]

fails miserably. GHC utterly refuses to parse this. No matter how I fidget with it, I can't seem to convince GHC to allow me to spread the list across multiple lines. Which is a problem, because if you replace x+y and x-y with really big expressions, it quickly becomes hard to read...

Does anybody know why isn't this working, and how can I force it to work? (Or at least do something that looks legible?)

Body:
Here are a couple of possible ways to write this legally:

test = do
  [x,y] <- replicateM 2 [1..5]
  [
    x+y
   ,x-y
   ]

test = do
  [x,y] <- replicateM 2 [1..5]
  [ x+y
   ,x-y ]

test = do
  [x,y] <- replicateM 2 [1..5]
  [ x+y ,
    x-y ]

test = do
  [x,y] <- replicateM 2 [1..5]
  id [ x+y
     , x-y ]

test = do
  [x,y] <- replicateM 2 [1..5]
  id [
       x+y,
       x-y
     ]

test = do
  [x,y] <- replicateM 2 [1..5]
  ([
     x+y,
     x-y
   ])


问:
Generate one PDF using multiple FO objects using apache fop in java
Can anyone suggest me how to create one pdf using multiple Apache fo objects?

We know that Apache fop generates pdf using FO(formatting objects). FO is created from xml by applying xsl.

My requirement is, I will be generating multi page pdf files. Each page template will be different, so I would need multiple xml and xsl files for one pdf. I thought of merging them and creating one FO but some PDF size would go till 2000 pages which leads to OutOfMemoryError.

I went through the Apache FOP reference example files for creating one pdf using multiple fop but I could not find one.

答:
An FO file you can contain as many fo:page-sequence elements as you want or need, each one with its master-reference property pointing to a page master.

So, you can have a single FO file with

several fo:page-sequence elements with the same page layout (think of the different chapters in a book)

several fo:page-sequence each one with a different layout

a combination of the previous cases

Besides, FOP processes the content of each page fo:page-sequence independently, so having many smaller page sequences instead of a giant one (if possible) also helps avoiding out-of-memory errors.


问:
Disable mousewheel on HTML and exclude a specific div using jquery
I want to disable mousewheel on HTML, and exclude a specific element from this rule.

I am using the following code:

```<code>$('html').bind("mousewheel, touchmove", function(e) {
    e.stopPropagation();
    return false;
});

$('.exclude').unbind("mousewheel, touchmove");
</code>```

Mouse Wheel does not work on the exclude element either.

答:
Try to use off() method of jQuery

Like this

```<code>$(".exclude").off("mousewheel, touchmove");
</code>```

The unbind() method was deprecated in version 3.0. Use the off() method instead.

Body:
I want to disable mousewheel on HTML, and exclude a specific element from this rule.

I am using the following code:

$('html').bind("mousewheel, touchmove", function(e) {
    e.stopPropagation();
    return false;
});

$('.exclude').unbind("mousewheel, touchmove");

Mouse Wheel does not work on the exclude element either.

Body:
Try to use off() method of jQuery

Like this

$(".exclude").off("mousewheel, touchmove");

The unbind() method was deprecated in version 3.0. Use the off() method instead.


问:
EF - InvalidOperationException Error when Saving after Adding Item to Virtual ICollection
Model :

```<code>public class UserProfile
{
    public int Id { get; set; }

    public virtual ApplicationUser ApplicationUser { get; set; }

    public string Name { get; set; }

    public virtual ICollection<UserProfile> Followers { get; set; }
 }
</code>```

Method :

```<code>public void Follow(int id)
    {
        if (id != AppUser.UserProfile.Id)
        {
            UserProfile profile = db.UserProfile.Find(id);
            if (profile != null)
            {
                if (profile.Followers.Contains(AppUser.UserProfile))
                {
                     profile.Followers.Remove(AppUser.UserProfile);
                }
                else
                {
                    profile.Followers.Add(AppUser.UserProfile);
                }
                db.Entry(profile).State = EntityState.Modified; //error here
                db.SaveChanges();

            }
        }
    }
</code>```

When a user follows another user, the user gets added to the Followers ICollection. If the user is already following, then the user gets removed from Followers.

When I am attempting to update the database, I get this error :

System.InvalidOperationException: 'The relationship between the two objects cannot be defined because they are attached to different ObjectContext objects.'

How can fix this?

答:
The problem is that AppUser.UserProfile is not in db context.

You can attach AppUser.UserProfile to the context you need or you can read a UserProfile from db context ( Find(AppUser.UserProfile.Id) ).

Just in case, don't clone AppUser.UserProfile without attaching it to context otherwise EF will add e new UserProfile.

Body:
Model :

public class UserProfile
{
    public int Id { get; set; }

    public virtual ApplicationUser ApplicationUser { get; set; }

    public string Name { get; set; }

    public virtual ICollection<UserProfile> Followers { get; set; }
 }

Method :

public void Follow(int id)
    {
        if (id != AppUser.UserProfile.Id)
        {
            UserProfile profile = db.UserProfile.Find(id);
            if (profile != null)
            {
                if (profile.Followers.Contains(AppUser.UserProfile))
                {
                     profile.Followers.Remove(AppUser.UserProfile);
                }
                else
                {
                    profile.Followers.Add(AppUser.UserProfile);
                }
                db.Entry(profile).State = EntityState.Modified; //error here
                db.SaveChanges();

            }
        }
    }

When a user follows another user, the user gets added to the Followers ICollection. If the user is already following, then the user gets removed from Followers.

When I am attempting to update the database, I get this error :

System.InvalidOperationException: 'The relationship between the two objects cannot be defined because they are attached to different ObjectContext objects.'

How can fix this?


问:
Magento - How to translate the module mini-form search
I want to translate the default input text of the mini-form (search) to german. The original text is "Search entire store here..." and it is situated in "default/default/template/cataloguesearch/form.mini.phtml"

Thanks.

答:
hi this grep will help you out and you can always use inline translation tool that Magento offers.

You are looking the following file app/locale/en_US/Mage_CatalogSearch.csv

```<code>$ grep 'Search' app/locale/ -rsn

app/locale/en_US/Mage_Adminhtml.csv:360:"Global Record Search","Global Record Search"
app/locale/en_US/Mage_Adminhtml.csv:361:"Global Search","Global Search"
app/locale/en_US/Mage_Adminhtml.csv:433:"Last 5 Search Terms","Last 5 Search Terms"
app/locale/en_US/Mage_Adminhtml.csv:533:"New Search","New Search"
app/locale/en_US/Mage_Adminhtml.csv:778:"Search","Search"
app/locale/en_US/Mage_Adminhtml.csv:779:"Search Index","Search Index"
app/locale/en_US/Mage_Adminhtml.csv:780:"Search Term","Search Term"
app/locale/en_US/Mage_Adminhtml.csv:781:"Search Terms","Search Terms"
app/locale/en_US/Mage_Adminhtml.csv:957:"Top 5 Search Terms","Top 5 Search Terms"
app/locale/en_US/Mage_Catalog.csv:27:"Add New Search Term","Add New Search Term"
app/locale/en_US/Mage_Catalog.csv:131:"Catalog Seo Popular Search Terms","Catalog Seo Popular Search Terms"
app/locale/en_US/Mage_Catalog.csv:137:"Catalog, Search","Catalog, Search"
app/locale/en_US/Mage_Catalog.csv:208:"Delete Search","Delete Search"
app/locale/en_US/Mage_Catalog.csv:228:"Edit Search","Edit Search"
app/locale/en_US/Mage_Catalog.csv:229:"Edit Search '%s'","Edit Search '%s'"
app/locale/en_US/Mage_Catalog.csv:355:"New Search","New Search"
app/locale/en_US/Mage_Catalog.csv:510:"Save Search","Save Search"
app/locale/en_US/Mage_Catalog.csv:514:"Search","Search"
app/locale/en_US/Mage_Catalog.csv:515:"Search Engine Optimizations","Search Engine Optimizations"
app/locale/en_US/Mage_Catalog.csv:516:"Search Information","Search Information"
app/locale/en_US/Mage_Catalog.csv:517:"Search Query","Search Query"
app/locale/en_US/Mage_Catalog.csv:518:"Search Term with such search query already exists.","Search Term with such search query already exists."
app/locale/en_US/Mage_Catalog.csv:519:"Searchable","Searchable"
app/locale/en_US/Mage_Catalog.csv:656:"Use In Search Results Layered Navigation","Use In Search Results Layered Navigation"
app/locale/en_US/Mage_Catalog.csv:664:"Use in Advanced Search","Use in Advanced Search"
app/locale/en_US/Mage_Catalog.csv:667:"Use in Quick Search","Use in Quick Search"
app/locale/en_US/Mage_Reports.csv:129:"Search Query","Search Query"
app/locale/en_US/Mage_Reports.csv:130:"Search Terms","Search Terms"
app/locale/en_US/Mage_Core.csv:209:"Search Engines Optimization","Search Engines Optimization"
app/locale/en_US/Mage_Api.csv:119:"Global Record Search","Global Record Search"
app/locale/en_US/Mage_Api.csv:144:"Last 5 Search Terms","Last 5 Search Terms"
app/locale/en_US/Mage_Api.csv:287:"Top 5 Search Terms","Top 5 Search Terms"
app/locale/en_US/Mage_CatalogSearch.csv:3:"Advanced Search","Advanced Search"
app/locale/en_US/Mage_CatalogSearch.csv:4:"Advanced Search Form","Advanced Search Form"
app/locale/en_US/Mage_CatalogSearch.csv:5:"Advanced Search Result","Advanced Search Result"
app/locale/en_US/Mage_CatalogSearch.csv:8:"Apply Layered Navigation if Search Results are Less Than","Apply Layered Navigation if Search Results are Less Than"
app/locale/en_US/Mage_CatalogSearch.csv:9:"Attribute setting change related with Search Index. Please run <a href=""%s"">Rebuild Search Index</a> process.","Attribute setting change related with Search Index. Please run <a href=""%s"">Rebuild Search Index</a> process."
app/locale/en_US/Mage_CatalogSearch.csv:11:"Catalog Advanced Search","Catalog Advanced Search"
app/locale/en_US/Mage_CatalogSearch.csv:12:"Catalog Search","Catalog Search"
app/locale/en_US/Mage_CatalogSearch.csv:13:"Catalog Search Index","Catalog Search Index"
app/locale/en_US/Mage_CatalogSearch.csv:23:"Maximum Search query  length is %s. Your query was cut.","Maximum Search query  length is %s. Your query was cut."
app/locale/en_US/Mage_CatalogSearch.csv:25:"Minimum Search query length is %s","Minimum Search query length is %s"
app/locale/en_US/Mage_CatalogSearch.csv:30:"Popular Search Terms","Popular Search Terms"
app/locale/en_US/Mage_CatalogSearch.csv:31:"Quick Search Form","Quick Search Form"
app/locale/en_US/Mage_CatalogSearch.csv:35:"Search","Search"
app/locale/en_US/Mage_CatalogSearch.csv:36:"Search Settings","Search Settings"
app/locale/en_US/Mage_CatalogSearch.csv:37:"Search Terms","Search Terms"
app/locale/en_US/Mage_CatalogSearch.csv:38:"Search Type","Search Type"
app/locale/en_US/Mage_CatalogSearch.csv:39:"Search entire store here...","Search entire store here..."
app/locale/en_US/Mage_CatalogSearch.csv:40:"Search results for '%s'","Search results for '%s'"
app/locale/en_US/Mage_CatalogSearch.csv:41:"Search results for: '%s'","Search results for: '%s'"
app/locale/en_US/Mage_CatalogSearch.csv:42:"Search:","Search:"
</code>```

Body:
hi this grep will help you out and you can always use inline translation tool that Magento offers.

You are looking the following file app/locale/en_US/Mage_CatalogSearch.csv

$ grep 'Search' app/locale/ -rsn

app/locale/en_US/Mage_Adminhtml.csv:360:"Global Record Search","Global Record Search"
app/locale/en_US/Mage_Adminhtml.csv:361:"Global Search","Global Search"
app/locale/en_US/Mage_Adminhtml.csv:433:"Last 5 Search Terms","Last 5 Search Terms"
app/locale/en_US/Mage_Adminhtml.csv:533:"New Search","New Search"
app/locale/en_US/Mage_Adminhtml.csv:778:"Search","Search"
app/locale/en_US/Mage_Adminhtml.csv:779:"Search Index","Search Index"
app/locale/en_US/Mage_Adminhtml.csv:780:"Search Term","Search Term"
app/locale/en_US/Mage_Adminhtml.csv:781:"Search Terms","Search Terms"
app/locale/en_US/Mage_Adminhtml.csv:957:"Top 5 Search Terms","Top 5 Search Terms"
app/locale/en_US/Mage_Catalog.csv:27:"Add New Search Term","Add New Search Term"
app/locale/en_US/Mage_Catalog.csv:131:"Catalog Seo Popular Search Terms","Catalog Seo Popular Search Terms"
app/locale/en_US/Mage_Catalog.csv:137:"Catalog, Search","Catalog, Search"
app/locale/en_US/Mage_Catalog.csv:208:"Delete Search","Delete Search"
app/locale/en_US/Mage_Catalog.csv:228:"Edit Search","Edit Search"
app/locale/en_US/Mage_Catalog.csv:229:"Edit Search '%s'","Edit Search '%s'"
app/locale/en_US/Mage_Catalog.csv:355:"New Search","New Search"
app/locale/en_US/Mage_Catalog.csv:510:"Save Search","Save Search"
app/locale/en_US/Mage_Catalog.csv:514:"Search","Search"
app/locale/en_US/Mage_Catalog.csv:515:"Search Engine Optimizations","Search Engine Optimizations"
app/locale/en_US/Mage_Catalog.csv:516:"Search Information","Search Information"
app/locale/en_US/Mage_Catalog.csv:517:"Search Query","Search Query"
app/locale/en_US/Mage_Catalog.csv:518:"Search Term with such search query already exists.","Search Term with such search query already exists."
app/locale/en_US/Mage_Catalog.csv:519:"Searchable","Searchable"
app/locale/en_US/Mage_Catalog.csv:656:"Use In Search Results Layered Navigation","Use In Search Results Layered Navigation"
app/locale/en_US/Mage_Catalog.csv:664:"Use in Advanced Search","Use in Advanced Search"
app/locale/en_US/Mage_Catalog.csv:667:"Use in Quick Search","Use in Quick Search"
app/locale/en_US/Mage_Reports.csv:129:"Search Query","Search Query"
app/locale/en_US/Mage_Reports.csv:130:"Search Terms","Search Terms"
app/locale/en_US/Mage_Core.csv:209:"Search Engines Optimization","Search Engines Optimization"
app/locale/en_US/Mage_Api.csv:119:"Global Record Search","Global Record Search"
app/locale/en_US/Mage_Api.csv:144:"Last 5 Search Terms","Last 5 Search Terms"
app/locale/en_US/Mage_Api.csv:287:"Top 5 Search Terms","Top 5 Search Terms"
app/locale/en_US/Mage_CatalogSearch.csv:3:"Advanced Search","Advanced Search"
app/locale/en_US/Mage_CatalogSearch.csv:4:"Advanced Search Form","Advanced Search Form"
app/locale/en_US/Mage_CatalogSearch.csv:5:"Advanced Search Result","Advanced Search Result"
app/locale/en_US/Mage_CatalogSearch.csv:8:"Apply Layered Navigation if Search Results are Less Than","Apply Layered Navigation if Search Results are Less Than"
app/locale/en_US/Mage_CatalogSearch.csv:9:"Attribute setting change related with Search Index. Please run <a href=""%s"">Rebuild Search Index</a> process.","Attribute setting change related with Search Index. Please run <a href=""%s"">Rebuild Search Index</a> process."
app/locale/en_US/Mage_CatalogSearch.csv:11:"Catalog Advanced Search","Catalog Advanced Search"
app/locale/en_US/Mage_CatalogSearch.csv:12:"Catalog Search","Catalog Search"
app/locale/en_US/Mage_CatalogSearch.csv:13:"Catalog Search Index","Catalog Search Index"
app/locale/en_US/Mage_CatalogSearch.csv:23:"Maximum Search query  length is %s. Your query was cut.","Maximum Search query  length is %s. Your query was cut."
app/locale/en_US/Mage_CatalogSearch.csv:25:"Minimum Search query length is %s","Minimum Search query length is %s"
app/locale/en_US/Mage_CatalogSearch.csv:30:"Popular Search Terms","Popular Search Terms"
app/locale/en_US/Mage_CatalogSearch.csv:31:"Quick Search Form","Quick Search Form"
app/locale/en_US/Mage_CatalogSearch.csv:35:"Search","Search"
app/locale/en_US/Mage_CatalogSearch.csv:36:"Search Settings","Search Settings"
app/locale/en_US/Mage_CatalogSearch.csv:37:"Search Terms","Search Terms"
app/locale/en_US/Mage_CatalogSearch.csv:38:"Search Type","Search Type"
app/locale/en_US/Mage_CatalogSearch.csv:39:"Search entire store here...","Search entire store here..."
app/locale/en_US/Mage_CatalogSearch.csv:40:"Search results for '%s'","Search results for '%s'"
app/locale/en_US/Mage_CatalogSearch.csv:41:"Search results for: '%s'","Search results for: '%s'"
app/locale/en_US/Mage_CatalogSearch.csv:42:"Search:","Search:"


问:
Swift async load image
I am working on show image from url async. I have tried to create a new thread for download image and then refresh on main thread.

```<code>func asyncLoadImg(product:Product,imageView:UIImageView){
    let downloadQueue = dispatch_queue_create("com.myApp.processdownload", nil)
    dispatch_async(downloadQueue){
        let data = NSData(contentsOfURL: NSURL(string: product.productImage)!)
        var image:UIImage?
        if data != nil{
            image = UIImage(data: data!)
        }
        dispatch_async(dispatch_get_main_queue()){
            imageView.image = image
        }

    }
}
</code>```

When I was trying to debug that, when it comes to dispatch_async(downloadQueue), it jumps out the func. Any suggestion? Thx

答:
This solution make scrolling really fast without unnecessary image updates.
You have to add the url property to our cell class:

```<code>class OfferItemCell: UITableViewCell {
    @IBOutlet weak var itemImageView: UIImageView!
    @IBOutlet weak var titleLabel: UILabel!
    var imageUrl: String?
}
</code>```

And add extension:

```<code>import Foundation
import UIKit

let imageCache = NSCache<AnyObject, AnyObject>()
let imageDownloadUtil: ImageDownloadUtil = ImageDownloadUtil()

extension OfferItemCell {
    func loadImageUsingCacheWithUrl(urlString: String  ) {
         self.itemImageView.image = nil
        if let cachedImage = imageCache.object(forKey: urlString as AnyObject) as? UIImage {
            self.itemImageView.image = cachedImage
            return
        }
        DispatchQueue.global(qos: .background).async {
            imageDownloadUtil.getImage(url: urlString, completion: {
                image in
                DispatchQueue.main.async {
                    if self.imageUrl == urlString{
                        imageCache.setObject(image, forKey: urlString as AnyObject)
                     self.itemImageView.image = image
                    }
                }
            })
        }
    }
}
</code>```

You can also improve it and extract some code to a more general cell class i.e. CustomCellWithImage to make it more reusable.

Title: Swift async load image

Body:
I am working on show image from url async. I have tried to create a new thread for download image and then refresh on main thread.

func asyncLoadImg(product:Product,imageView:UIImageView){
    let downloadQueue = dispatch_queue_create("com.myApp.processdownload", nil)
    dispatch_async(downloadQueue){
        let data = NSData(contentsOfURL: NSURL(string: product.productImage)!)
        var image:UIImage?
        if data != nil{
            image = UIImage(data: data!)
        }
        dispatch_async(dispatch_get_main_queue()){
            imageView.image = image
        }

    }
}

When I was trying to debug that, when it comes to dispatch_async(downloadQueue), it jumps out the func. Any suggestion? Thx

Body:
This solution make scrolling really fast without unnecessary image updates.
You have to add the url property to our cell class:

class OfferItemCell: UITableViewCell {
    @IBOutlet weak var itemImageView: UIImageView!
    @IBOutlet weak var titleLabel: UILabel!
    var imageUrl: String?
}

And add extension:

import Foundation
import UIKit

let imageCache = NSCache<AnyObject, AnyObject>()
let imageDownloadUtil: ImageDownloadUtil = ImageDownloadUtil()

extension OfferItemCell {
    func loadImageUsingCacheWithUrl(urlString: String  ) {
         self.itemImageView.image = nil
        if let cachedImage = imageCache.object(forKey: urlString as AnyObject) as? UIImage {
            self.itemImageView.image = cachedImage
            return
        }
        DispatchQueue.global(qos: .background).async {
            imageDownloadUtil.getImage(url: urlString, completion: {
                image in
                DispatchQueue.main.async {
                    if self.imageUrl == urlString{
                        imageCache.setObject(image, forKey: urlString as AnyObject)
                     self.itemImageView.image = image
                    }
                }
            })
        }
    }
}

You can also improve it and extract some code to a more general cell class i.e. CustomCellWithImage to make it more reusable.