问:
Cannot find symbol variable editText
I am attempting Android Developer's "Building Your First App" project. I have followed the instructions provided accordingly yet I am experiencing the error mentioned above.

```<code>public class MainActivity extends AppCompatActivity {

public static final String EXTRA_MESSAGE = "com.example.myfirstapp.MESSAGE";
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
}

/** Called when the user taps the Send button */
public void sendMessage(View view) {
    Intent intent = new Intent(this, DisplayMessageActivity.class);
    EditText editText = (EditText) findViewById(R.id.**editText**);
    String message = editText.getText().toString();
    intent.putExtra(EXTRA_MESSAGE, message);
    startActivity(intent);
}
</code>```

Upon clicking "run", the error message above was displayed. While the rest of my values can be resolved, the editText variable remains in RED font (which I placed in bold above).
According to Android Developer's website, the code block is supposed to look like this:

```<code>public class MainActivity extends AppCompatActivity {
public static final String EXTRA_MESSAGE = "com.example.myfirstapp.MESSAGE";
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
}

/** Called when the user taps the Send button */
public void sendMessage(View view) {
    Intent intent = new Intent(this, DisplayMessageActivity.class);
    EditText editText = (EditText) findViewById(R.id.editText);
    String message = editText.getText().toString();
    intent.putExtra(EXTRA_MESSAGE, message);
    startActivity(intent);
}
</code>```

Can someone please explain to me why I am not able to resolve the symbol for editText? Thanks!

答:
You need to make sure of these two things:

There is an EditText element in "activity_main.xml" with android:id="@+id/editText"

You are importing the right R class. The correct one should be <applicationPackage>.R

Title: Cannot find symbol variable editText

Body:
I am attempting Android Developer's "Building Your First App" project. I have followed the instructions provided accordingly yet I am experiencing the error mentioned above.

public class MainActivity extends AppCompatActivity {

public static final String EXTRA_MESSAGE = "com.example.myfirstapp.MESSAGE";
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
}

/** Called when the user taps the Send button */
public void sendMessage(View view) {
    Intent intent = new Intent(this, DisplayMessageActivity.class);
    EditText editText = (EditText) findViewById(R.id.**editText**);
    String message = editText.getText().toString();
    intent.putExtra(EXTRA_MESSAGE, message);
    startActivity(intent);
}

Upon clicking "run", the error message above was displayed. While the rest of my values can be resolved, the editText variable remains in RED font (which I placed in bold above).
According to Android Developer's website, the code block is supposed to look like this:

public class MainActivity extends AppCompatActivity {
public static final String EXTRA_MESSAGE = "com.example.myfirstapp.MESSAGE";
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
}

/** Called when the user taps the Send button */
public void sendMessage(View view) {
    Intent intent = new Intent(this, DisplayMessageActivity.class);
    EditText editText = (EditText) findViewById(R.id.editText);
    String message = editText.getText().toString();
    intent.putExtra(EXTRA_MESSAGE, message);
    startActivity(intent);
}

Can someone please explain to me why I am not able to resolve the symbol for editText? Thanks!


来源: stackexchange

问:
bs4 max result length
I am currently writing a python script to scrape a news site with bs4 and I want to have the results on my 16x2 lcd screen. Is it possible to have something like a maximum length of soup.find_all results?

```<code>from bs4 import BeautifulSoup
from urllib.request import Request, urlopen
import re

r=urlopen("https://derstandard.at")
url = "https://derstandard.at"

soup = BeautifulSoup(r, "html.parser")

for a in soup.find_all("h2", limit=5):
    print(a.text)
</code>```

This is the current script

答:
I doubt there is a special way to do this in BeatifulSoup and you really don't need one.</p>

```<code>for a in soup.find_all("h2"):
    if len(a.text) <= 5:
        print(a.text)
</code>```

ContentLicense: CC BY-SA 3.0

Title: bs4 max result length

Body:
I am currently writing a python script to scrape a news site with bs4 and I want to have the results on my 16x2 lcd screen. Is it possible to have something like a maximum length of soup.find_all results?

from bs4 import BeautifulSoup
from urllib.request import Request, urlopen
import re

r=urlopen("https://derstandard.at")
url = "https://derstandard.at"

soup = BeautifulSoup(r, "html.parser")

for a in soup.find_all("h2", limit=5):
    print(a.text)

This is the current script

Body:
I doubt there is a special way to do this in BeatifulSoup and you really don't need one.

for a in soup.find_all("h2"):
    if len(a.text) <= 5:
        print(a.text)


答:
That means you have not created resource with id edit_text.
Iniside your XML make sure you have created id

```<code>  <EditText
                        android:id="@+id/edit_text"
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:textColor="@color/colorBlack"
                        android:textSize="14sp"
                        android:textStyle="normal"/>
</code>```

if you have created xml with id please check Imported package for R

Title: Cannot find symbol variable editText

Body:
That means you have not created resource with id edit_text.
Iniside your XML make sure you have created id

  <EditText
                        android:id="@+id/edit_text"
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:textColor="@color/colorBlack"
                        android:textSize="14sp"
                        android:textStyle="normal"/>

if you have created xml with id please check Imported package for R


问:
core -java Exception Handling
The Below is a class Question which is propagating Exception handling mechanism,the desired output is Exception.Can anybody explain why the output is Exception ,Thanks in advance.</p>

```<code> Class Question {

  public void m1() throws Exception {

   try {

    m2();

   } finally {

    m3();

   }
  }
  public void m2() throws RuntimeException {

   throw new RuntimeException();

  }

  public void m3() throws Exception {

   throw new Exception();

  }
  public static void main(String[] args) throws Exception {

   Question q = new Question();

   try {

    q.m1();

   } catch (RuntimeException re) {

    System.out.println("RuntimeException");

   } catch (Exception e) {

    System.out.println("Exception");
   }
  }
</code>```

答:
Because when the finally statement is executed, m3() is invoked and it throws Exception.

So, even if a RuntimeException was risen before the reach of the finally statement, RuntimeException is not considered if the finally clause throws also another exception.

From the 14.18. The throw Statement JLS :

If there are any enclosing try statements (§14.20) whose try blocks
  contain the throw statement, then any finally clauses of those try
  statements are executed as control is transferred outward, until the
  thrown value is caught. Note that abrupt completion of a finally
  clause can disrupt the transfer of control initiated by a throw
  statement.

Title: core -java Exception Handling

Body:
The Below is a class Question which is propagating Exception handling mechanism,the desired output is Exception.Can anybody explain why the output is Exception ,Thanks in advance.

 Class Question {

  public void m1() throws Exception {

   try {

    m2();

   } finally {

    m3();

   }
  }
  public void m2() throws RuntimeException {

   throw new RuntimeException();

  }

  public void m3() throws Exception {

   throw new Exception();

  }
  public static void main(String[] args) throws Exception {

   Question q = new Question();

   try {

    q.m1();

   } catch (RuntimeException re) {

    System.out.println("RuntimeException");

   } catch (Exception e) {

    System.out.println("Exception");
   }
  }


问:
connect to SQL hosted on a local machine from my laptop (using an IP)
I set up an SQL server on my Windows 7 PC.

I have a laptop, from which I want to connect to the SQL server (using visual studio 2010).
I need to fill in a "server name" when creating a database connection.

I tried "My.IP.Address/SQLEXPRESS,custom-port", but that doesn't work. All examples talk about using server names which are formatted like so "TOM-PC/SQLEXPRESS", but I have an important requirement:

I want to be able to connect from anywhere (not only when in the same local network), therefore I'm trying to use the IP address (the port isn't simply 1433 since my ISP blocks it).

The custom port is open, and reachable in tests.

I've been Googling this all day long, but can't find a solution. Please help!

Thank you,

Tom

答: Is it possible you overlooked turning on TCP/IP fro SQLExpress in the configuration manager?

ContentLicense: CC BY-SA 2.5


问:
2 foreach loops tripling submitted data
I have 3 hidden fields and 3 text fields. I need to loop through both to UPDATE database records. If I use the foreach loops separately, it posts 3 values correctly. If I try use them together it seems to triple the text input value which is a date. So instead of looking like this:

1 - 2017-04-05

2 - 2017-04-06

3 - 2017-04-07

It looks like this:

1 - 2017-04-05

2 - 2017-04-05

3 - 2017-04-05

1 - 2017-04-06

2 - 2017-04-06

3 - 2017-04-06

1 - 2017-04-07

2 - 2017-04-07

3 - 2017-04-07

```<code>        foreach($_POST['commit_date'] as $commitdate) {
            foreach($_POST['unit'] as $units) {

                echo $units .= $commitdate . "<br/>";

            }
        }
</code>```

答:
If I use the foreach loops separately, it posts 3 values correctly. If I try use them together it seems to triple the text input value which is a date.

That's because you're using nested foreach loops, which means for each outer loop, inner loop will be executed thrice. And that's why you're getting 9 values.

Instead, use a simple for loop like this,

```<code>$count = count($_POST['unit']);
for($i = 0; $i < $count; ++$i){
    echo $_POST['unit'][$i] .= $_POST['commit_date'][$i] . "<br/>";
}
</code>```

Title: 2 foreach loops tripling submitted data

Body:
I have 3 hidden fields and 3 text fields. I need to loop through both to UPDATE database records. If I use the foreach loops separately, it posts 3 values correctly. If I try use them together it seems to triple the text input value which is a date. So instead of looking like this:

1 - 2017-04-05

2 - 2017-04-06

3 - 2017-04-07

It looks like this:

1 - 2017-04-05

2 - 2017-04-05

3 - 2017-04-05

1 - 2017-04-06

2 - 2017-04-06

3 - 2017-04-06

1 - 2017-04-07

2 - 2017-04-07

3 - 2017-04-07

        foreach($_POST['commit_date'] as $commitdate) {
            foreach($_POST['unit'] as $units) {

                echo $units .= $commitdate . "
";

            }
        }

Body:
If I use the foreach loops separately, it posts 3 values correctly. If I try use them together it seems to triple the text input value which is a date.

That's because you're using nested foreach loops, which means for each outer loop, inner loop will be executed thrice. And that's why you're getting 9 values.

Instead, use a simple for loop like this,

$count = count($_POST['unit']);
for($i = 0; $i < $count; ++$i){
    echo $_POST['unit'][$i] .= $_POST['commit_date'][$i] . "<br/>";
}


问:
C# Server-Client App(One Server-Multi Client)
I want to develop a client-server application. I started the project but I encountered the some problems. When I want to connect to server with one client, everything is done. Program is working. But when I want to connect with two or three etc. PC to server, clients of them is working but others is not working. How can I fix this problem?

Here is the my code;

```<code>    using System;
    using System.Collections.Generic;
    using System.ComponentModel;
    using System.Data;
    using System.Drawing;
    using System.Linq;
    using System.Text;
    using System.Threading;
    using System.Threading.Tasks;
    using System.Windows.Forms;
    using System.Net;
    using System.Net.Sockets;
    using System.IO;
    using System.Timers;
    using ClientServer;
    namespace ClientServer
    {
        public partial class Form1 : Form
        {
            private TcpClient Client;
            private StreamReader STR;
            public StreamWriter STW;
            public string receive;
            public string text_to_send;
            //int zaman;
            public Form1()
            {
                    InitializeComponent();
-                   Client = new TcpClient();
                    Control.CheckForIllegalCrossThreadCalls = false; //cross threading problem
                    IPAddress[] LocalIP = Dns.GetHostAddresses(Dns.GetHostName()); // my IP Adress
            foreach (IPAddress adress in LocalIP)
            {
                if(adress.AddressFamily== AddressFamily.InterNetwork)
                {
                    textBox3.Text = adress.ToString();

                }
            }
        }

        private void button2_Click(object sender, EventArgs e) //Start server
        {
            TcpListener listener = new TcpListener(IPAddress.Any, int.Parse(textBox4.Text));
            listener.Start();
            Client = listener.AcceptTcpClient();
            STR = new StreamReader(Client.GetStream());
            STW = new StreamWriter(Client.GetStream());
            STW.AutoFlush = true;

            backgroundWorker1.RunWorkerAsync();  //receive data background
            backgroundWorker2.WorkerSupportsCancellation = true; //ability cancel this thread

        }

        private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e) //receive data
        {
            while(Client.Connected)
            {
                try
                {
                    receive = STR.ReadLine();
                    if(receive=="soru1")
                    {
                        label7.Text = "Merhaba bu bir denemedir :)";
                        //zaman = 45;
                        timer1.Enabled = true;

                    }
                    this.textBox2.Invoke(new MethodInvoker(delegate() { textBox2.AppendText("Sen:" + receive + "\n"); }));

                    receive = "";
                }
                catch(Exception x)
                {
                    MessageBox.Show(x.Message.ToString());
                }
            }
        }

        private void backgroundWorker2_DoWork(object sender, DoWorkEventArgs e)  //veri gönder
        {
            if(Client.Connected)
            {
                STW.WriteLine(text_to_send);
                this.textBox2.Invoke(new MethodInvoker(delegate() { textBox2.AppendText("Ben:" + text_to_send + "\n"); }));

            }
            else
            {
                MessageBox.Show("Gönderim başarısız!");
            }
            backgroundWorker2.CancelAsync();

        }

        private void button3_Click(object sender, EventArgs e) //Connect Server
        {
            Client = new TcpClient();
            IPEndPoint IP_End = new IPEndPoint(IPAddress.Parse(textBox5.Text), int.Parse(textBox6.Text));

            try
            {
                Client.Connect(IP_End);
                if(Client.Connected)
                {
                    textBox2.AppendText("Server'a bağlantı sağlandı" + "\n");
                    STW = new StreamWriter(Client.GetStream());
                    STR = new StreamReader(Client.GetStream());
                    STW.AutoFlush = true;

                    backgroundWorker1.RunWorkerAsync();  //receive data in background
                    backgroundWorker2.WorkerSupportsCancellation = true; //

                }
            }
            catch(Exception x)
            {
                MessageBox.Show(x.Message.ToString());
            }
        }

        private void button1_Click(object sender, EventArgs e) //Send Button
        {
            if(textBox1.Text != "")
            {
                text_to_send = textBox1.Text;
                backgroundWorker2.RunWorkerAsync();
            }

            textBox1.Text = "";

        }

        //private void timer1_Tick(object sender, System.EventArgs e) //
        //{
        //    zaman--; //timer her saniyede sayıyı 1 azaltacak
        //    label9.Text = zaman.ToString();
        //    if (zaman == 0)
        //    {
        //        timer1.Enabled = false;
        //    }
        //}

    }
}
</code>```

答:
Here a good links:

http://www.mikeadev.net/2012/07/multi-threaded-tcp-server-in-csharp/

https://www.codeproject.com/Articles/511814/Multi-client-per-one-server-socket-programming-in

```<code>tcpListener.Start();
Console.WriteLine("************This is Server program************");
Console.WriteLine("Hoe many clients are going to connect to this server?:");
int numberOfClientsYouNeedToConnect =int.Parse( Console.ReadLine());

for (int i = 0; i < numberOfClientsYouNeedToConnect; i++)
{
    Thread newThread = new Thread(new ThreadStart(Listeners));
    newThread.Start();
}
</code>```

Body:
I want to develop a client-server application. I started the project but I encountered the some problems. When I want to connect to server with one client, everything is done. Program is working. But when I want to connect with two or three etc. PC to server, clients of them is working but others is not working. How can I fix this problem?

Here is the my code;

    using System;
    using System.Collections.Generic;
    using System.ComponentModel;
    using System.Data;
    using System.Drawing;
    using System.Linq;
    using System.Text;
    using System.Threading;
    using System.Threading.Tasks;
    using System.Windows.Forms;
    using System.Net;
    using System.Net.Sockets;
    using System.IO;
    using System.Timers;
    using ClientServer;
    namespace ClientServer
    {
        public partial class Form1 : Form
        {
            private TcpClient Client;
            private StreamReader STR;
            public StreamWriter STW;
            public string receive;
            public string text_to_send;
            //int zaman;
            public Form1()
            {
                    InitializeComponent();
-                   Client = new TcpClient();
                    Control.CheckForIllegalCrossThreadCalls = false; //cross threading problem
                    IPAddress[] LocalIP = Dns.GetHostAddresses(Dns.GetHostName()); // my IP Adress
            foreach (IPAddress adress in LocalIP)
            {
                if(adress.AddressFamily== AddressFamily.InterNetwork)
                {
                    textBox3.Text = adress.ToString();

                }
            }
        }

        private void button2_Click(object sender, EventArgs e) //Start server
        {
            TcpListener listener = new TcpListener(IPAddress.Any, int.Parse(textBox4.Text));
            listener.Start();
            Client = listener.AcceptTcpClient();
            STR = new StreamReader(Client.GetStream());
            STW = new StreamWriter(Client.GetStream());
            STW.AutoFlush = true;

            backgroundWorker1.RunWorkerAsync();  //receive data background
            backgroundWorker2.WorkerSupportsCancellation = true; //ability cancel this thread

        }

        private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e) //receive data
        {
            while(Client.Connected)
            {
                try
                {
                    receive = STR.ReadLine();
                    if(receive=="soru1")
                    {
                        label7.Text = "Merhaba bu bir denemedir :)";
                        //zaman = 45;
                        timer1.Enabled = true;

                    }
                    this.textBox2.Invoke(new MethodInvoker(delegate() { textBox2.AppendText("Sen:" + receive + "\n"); }));

                    receive = "";
                }
                catch(Exception x)
                {
                    MessageBox.Show(x.Message.ToString());
                }
            }
        }

        private void backgroundWorker2_DoWork(object sender, DoWorkEventArgs e)  //veri gönder
        {
            if(Client.Connected)
            {
                STW.WriteLine(text_to_send);
                this.textBox2.Invoke(new MethodInvoker(delegate() { textBox2.AppendText("Ben:" + text_to_send + "\n"); }));

            }
            else
            {
                MessageBox.Show("Gönderim başarısız!");
            }
            backgroundWorker2.CancelAsync();

        }

        private void button3_Click(object sender, EventArgs e) //Connect Server
        {
            Client = new TcpClient();
            IPEndPoint IP_End = new IPEndPoint(IPAddress.Parse(textBox5.Text), int.Parse(textBox6.Text));

            try
            {
                Client.Connect(IP_End);
                if(Client.Connected)
                {
                    textBox2.AppendText("Server'a bağlantı sağlandı" + "\n");
                    STW = new StreamWriter(Client.GetStream());
                    STR = new StreamReader(Client.GetStream());
                    STW.AutoFlush = true;

                    backgroundWorker1.RunWorkerAsync();  //receive data in background
                    backgroundWorker2.WorkerSupportsCancellation = true; //

                }
            }
            catch(Exception x)
            {
                MessageBox.Show(x.Message.ToString());
            }
        }

        private void button1_Click(object sender, EventArgs e) //Send Button
        {
            if(textBox1.Text != "")
            {
                text_to_send = textBox1.Text;
                backgroundWorker2.RunWorkerAsync();
            }

            textBox1.Text = "";

        }

        //private void timer1_Tick(object sender, System.EventArgs e) //
        //{
        //    zaman--; //timer her saniyede sayıyı 1 azaltacak
        //    label9.Text = zaman.ToString();
        //    if (zaman == 0)
        //    {
        //        timer1.Enabled = false;
        //    }
        //}

    }
}

Body:
Here a good links:

http://www.mikeadev.net/2012/07/multi-threaded-tcp-server-in-csharp/

https://www.codeproject.com/Articles/511814/Multi-client-per-one-server-socket-programming-in

tcpListener.Start();
Console.WriteLine("************This is Server program************");
Console.WriteLine("Hoe many clients are going to connect to this server?:");
int numberOfClientsYouNeedToConnect =int.Parse( Console.ReadLine());

for (int i = 0; i < numberOfClientsYouNeedToConnect; i++)
{
    Thread newThread = new Thread(new ThreadStart(Listeners));
    newThread.Start();
}


问:
Abit stuck why i cant get this working :/
```<code>public class Robot
{
    public static void main(String []args){

        ArrayList<String> list = new ArrayList<String>();
        String path = "";
        int N = 2;
        int ol1_right = 1;
        int ol1_down = 1;
        int ol2_right = 1;
        int ol2_down = 1;
        buildPath (right, down, path, allPaths, N);
        System.out.println (allPath(grid));

    }

    public void BuildPath (int right, int down, String path,
        ArrayList<String> allPaths, int N){
            path += "(" + down "," + right + ")->";
            if (right == N-1 && down == N-1){
                allPaths.add(path);
                return;
            }
            else if (right +1 == ol1_right && down == ol1_down) && (right +1 ==
            ol2_right && down == ol2_down);{
            return;
            }
            if (right +1 == ol1_right && down == N-1) || (right +1 == ol2_right
            && down == N-1);{
            return;
            }
            if (right == N-1 && down +1 == ol1_down) || (right == N-1 && down +1
            == ol2_right);{
            return;
            }
            if (right == N-1 || right +1 == ol1_right && down == N-1 ||
            right +1 == ol2_right && down == N-1){
                BuildPath (right, down + 1, path, allPaths, N);
            }
            else if (down == N-1 || right +1 == ol1_right && down == ol1_down && right +1 ==
            ol2_right && down == ol2_down ){
                BuildPath (right + 1, down, path, allPaths, N);
            }
            else
            BuildPath (right + 1, down, path, allPaths, N);
            BuildPath (right, down + 1, path, allPaths, N);
    }
}
</code>```

Sorry im still new to this sort of thing and im stuck on trying to get this program to work but sort of stuck on where to go to next. I get errors such as "illegal start of expression" ( thrown when using || and &&) or "not a statement" (path += "(" + down "," + right + ")->";) All im trying to do is get the (robot) to move along the grid while only moving down and right but also have the ability to mark certain parts of the gird as off limits. any help would be much appreciated, i know it all looks terrible but just trying to get the hang of this so sorry for any rookie errors or dumb mistakes still very new :)

答:
There's a number of problems, for starters in Main() you have

```<code>int ol1_right = 1;
int ol1_down = 1;
int ol2_right = 1;
int ol2_down = 1;
</code>```

which you declare and initialize but then try to access from BuildPath() without passing them as parameters. You can't do that, because in Java the scope of a variable is limited to the block it is defined in unless you specify otherwise.

In your case you would probably need to move those four variables to BuildPath() itself. Then again, you don't seem to ever change them, so I would make one single constant out of all of them.

Also, list doesn't seem like it is used, so it's probably redundant.

Not a Java guy, and I don't have a compiler handy to tell you exactly what's wrong. Try making a new file and adding code back a little at a time and see what the compiler complains about.

If I may, it looks to me like you're getting ahead of yourself if you're doing recursion without really knowing Java's syntax. I would concentrate on learning at least the basics of that first.

Body:
public class Robot
{
    public static void main(String []args){

        ArrayList<String> list = new ArrayList<String>();
        String path = "";
        int N = 2;
        int ol1_right = 1;
        int ol1_down = 1;
        int ol2_right = 1;
        int ol2_down = 1;
        buildPath (right, down, path, allPaths, N);
        System.out.println (allPath(grid));

    }

    public void BuildPath (int right, int down, String path,
        ArrayList<String> allPaths, int N){
            path += "(" + down "," + right + ")->";
            if (right == N-1 && down == N-1){
                allPaths.add(path);
                return;
            }
            else if (right +1 == ol1_right && down == ol1_down) && (right +1 ==
            ol2_right && down == ol2_down);{
            return;
            }
            if (right +1 == ol1_right && down == N-1) || (right +1 == ol2_right
            && down == N-1);{
            return;
            }
            if (right == N-1 && down +1 == ol1_down) || (right == N-1 && down +1
            == ol2_right);{
            return;
            }
            if (right == N-1 || right +1 == ol1_right && down == N-1 ||
            right +1 == ol2_right && down == N-1){
                BuildPath (right, down + 1, path, allPaths, N);
            }
            else if (down == N-1 || right +1 == ol1_right && down == ol1_down && right +1 ==
            ol2_right && down == ol2_down ){
                BuildPath (right + 1, down, path, allPaths, N);
            }
            else
            BuildPath (right + 1, down, path, allPaths, N);
            BuildPath (right, down + 1, path, allPaths, N);
    }
}

Sorry im still new to this sort of thing and im stuck on trying to get this program to work but sort of stuck on where to go to next. I get errors such as "illegal start of expression" ( thrown when using || and &&) or "not a statement" (path += "(" + down "," + right + ")->";) All im trying to do is get the (robot) to move along the grid while only moving down and right but also have the ability to mark certain parts of the gird as off limits. any help would be much appreciated, i know it all looks terrible but just trying to get the hang of this so sorry for any rookie errors or dumb mistakes still very new :)

Body:
There's a number of problems, for starters in Main() you have

int ol1_right = 1;
int ol1_down = 1;
int ol2_right = 1;
int ol2_down = 1;

which you declare and initialize but then try to access from BuildPath() without passing them as parameters. You can't do that, because in Java the scope of a variable is limited to the block it is defined in unless you specify otherwise.

In your case you would probably need to move those four variables to BuildPath() itself. Then again, you don't seem to ever change them, so I would make one single constant out of all of them.

Also, list doesn't seem like it is used, so it's probably redundant.

Not a Java guy, and I don't have a compiler handy to tell you exactly what's wrong. Try making a new file and adding code back a little at a time and see what the compiler complains about.

If I may, it looks to me like you're getting ahead of yourself if you're doing recursion without really knowing Java's syntax. I would concentrate on learning at least the basics of that first.


问:
Zend Framework Doctrine\DBAL\Exception\InvalidFieldNameException
I have this issue since I have moved my website to an other server. The configuration is the same, any hint?

File:

```<code>/var/www/page/vendor/doctrine/dbal/lib/Doctrine/DBAL/Driver/AbstractMySQLDriver.php:71
</code>```

Message:

```<code>An exception occurred while executing 'SELECT s0_.id AS id_0, s0_.answer AS answer_1, s0_.users_usrId AS users_usrId_2, s0_.question AS question_3 FROM secret_answer s0_ WHERE s0_.users_usrId = ?' with params [83440]:
</code>```

SQLSTATE[42S22]: Column not found: 1054 Unknown column 's0_.users_usrId' in 'field list'

Stack Trace:

```<code>#0 /var/www/page/vendor/doctrine/dbal/lib/Doctrine/DBAL/DBALException.php(128): Doctrine\DBAL\Driver\AbstractMySQLDriver->convertException('An exception oc...', Object(Doctrine\DBAL\Driver\PDOException))
#1 /var/www/page/vendor/doctrine/dbal/lib/Doctrine/DBAL/Connection.php(855): Doctrine\DBAL\DBALException::driverExceptionDuringQuery(Object(Doctrine\DBAL\Driver\PDOMySql\Driver), Object(Doctrine\DBAL\Driver\PDOException), 'SELECT s0_.id A...', Array)
#2 /var/www/page/vendor/doctrine/orm/lib/Doctrine/ORM/Query/Exec/SingleSelectExecutor.php(50): Doctrine\DBAL\Connection->executeQuery('SELECT s0_.id A...', Array, Array, NULL)
#3 /var/www/page/vendor/doctrine/orm/lib/Doctrine/ORM/Query.php(321): Doctrine\ORM\Query\Exec\SingleSelectExecutor->execute(Object(Doctrine\DBAL\Connection), Array, Array)
#4 /var/www/page/vendor/doctrine/orm/lib/Doctrine/ORM/AbstractQuery.php(969): Doctrine\ORM\Query->_doExecute()
#5 /var/www/page/vendor/doctrine/orm/lib/Doctrine/ORM/AbstractQuery.php(924): Doctrine\ORM\AbstractQuery->executeIgnoreQueryCache(NULL, NULL)
#6 /var/www/page/vendor/doctrine/orm/lib/Doctrine/ORM/AbstractQuery.php(766): Doctrine\ORM\AbstractQuery->execute(NULL, NULL)
#7 /var/www/page/vendor/custom/p-server-core/src/PServerCore/Entity/Repository/SecretAnswer.php(23): Doctrine\ORM\AbstractQuery->getOneOrNullResult()
#8 /var/www/page/vendor/custom/p-server-core/src/PServerCore/Form/Password.php(85): PServerCore\Entity\Repository\SecretAnswer->getAnswer4UserId(83440)
#9 /var/www/page/vendor/custom/p-server-core/src/PServerCore/Controller/AuthController.php(188): PServerCore\Form\Password->addSecretQuestion(Object(DoctrineORMModule\Proxy\__CG__\PServerCore\Entity\User))
#10 /var/www/page/vendor/zendframework/zend-mvc/src/Controller/AbstractActionController.php(78): PServerCore\Controller\AuthController->pwLostConfirmAction()
#11 /var/www/page/vendor/zendframework/zend-eventmanager/src/EventManager.php(322): Zend\Mvc\Controller\AbstractActionController->onDispatch(Object(Zend\Mvc\MvcEvent))
#12 /var/www/page/vendor/zendframework/zend-eventmanager/src/EventManager.php(179): Zend\EventManager\EventManager->triggerListeners(Object(Zend\Mvc\MvcEvent), Object(Closure))
#13 /var/www/page/vendor/zendframework/zend-mvc/src/Controller/AbstractController.php(105): Zend\EventManager\EventManager->triggerEventUntil(Object(Closure), Object(Zend\Mvc\MvcEvent))
#14 /var/www/page/vendor/zendframework/zend-mvc/src/DispatchListener.php(119): Zend\Mvc\Controller\AbstractController->dispatch(Object(Zend\Http\PhpEnvironment\Request), Object(Zend\Http\PhpEnvironment\Response))
#15 /var/www/page/vendor/zendframework/zend-eventmanager/src/EventManager.php(322): Zend\Mvc\DispatchListener->onDispatch(Object(Zend\Mvc\MvcEvent))
#16 /var/www/page/vendor/zendframework/zend-eventmanager/src/EventManager.php(179): Zend\EventManager\EventManager->triggerListeners(Object(Zend\Mvc\MvcEvent), Object(Closure))
#17 /var/www/page/vendor/zendframework/zend-mvc/src/Application.php(332): Zend\EventManager\EventManager->triggerEventUntil(Object(Closure), Object(Zend\Mvc\MvcEvent))
#18 /var/www/page/public/index.php(18): Zend\Mvc\Application->run()
#19 {main}
</code>```

Thanks and kind regards.

答:
It looks like the field is missing. You might have to update your database schema or adjust the orm-configuration for the entity.

Assuming you use annotations, you can specify the table name in the @Table and the field name to the @Column annotation. To make sure the entity maps to the right table and the property to the right field.

Body:
I have this issue since I have moved my website to an other server. The configuration is the same, any hint?

File:

/var/www/page/vendor/doctrine/dbal/lib/Doctrine/DBAL/Driver/AbstractMySQLDriver.php:71

Message:

An exception occurred while executing 'SELECT s0_.id AS id_0, s0_.answer AS answer_1, s0_.users_usrId AS users_usrId_2, s0_.question AS question_3 FROM secret_answer s0_ WHERE s0_.users_usrId = ?' with params [83440]:

SQLSTATE[42S22]: Column not found: 1054 Unknown column 's0_.users_usrId' in 'field list'

Stack Trace:

#0 /var/www/page/vendor/doctrine/dbal/lib/Doctrine/DBAL/DBALException.php(128): Doctrine\DBAL\Driver\AbstractMySQLDriver->convertException('An exception oc...', Object(Doctrine\DBAL\Driver\PDOException))
#1 /var/www/page/vendor/doctrine/dbal/lib/Doctrine/DBAL/Connection.php(855): Doctrine\DBAL\DBALException::driverExceptionDuringQuery(Object(Doctrine\DBAL\Driver\PDOMySql\Driver), Object(Doctrine\DBAL\Driver\PDOException), 'SELECT s0_.id A...', Array)
#2 /var/www/page/vendor/doctrine/orm/lib/Doctrine/ORM/Query/Exec/SingleSelectExecutor.php(50): Doctrine\DBAL\Connection->executeQuery('SELECT s0_.id A...', Array, Array, NULL)
#3 /var/www/page/vendor/doctrine/orm/lib/Doctrine/ORM/Query.php(321): Doctrine\ORM\Query\Exec\SingleSelectExecutor->execute(Object(Doctrine\DBAL\Connection), Array, Array)
#4 /var/www/page/vendor/doctrine/orm/lib/Doctrine/ORM/AbstractQuery.php(969): Doctrine\ORM\Query->_doExecute()
#5 /var/www/page/vendor/doctrine/orm/lib/Doctrine/ORM/AbstractQuery.php(924): Doctrine\ORM\AbstractQuery->executeIgnoreQueryCache(NULL, NULL)
#6 /var/www/page/vendor/doctrine/orm/lib/Doctrine/ORM/AbstractQuery.php(766): Doctrine\ORM\AbstractQuery->execute(NULL, NULL)
#7 /var/www/page/vendor/custom/p-server-core/src/PServerCore/Entity/Repository/SecretAnswer.php(23): Doctrine\ORM\AbstractQuery->getOneOrNullResult()
#8 /var/www/page/vendor/custom/p-server-core/src/PServerCore/Form/Password.php(85): PServerCore\Entity\Repository\SecretAnswer->getAnswer4UserId(83440)
#9 /var/www/page/vendor/custom/p-server-core/src/PServerCore/Controller/AuthController.php(188): PServerCore\Form\Password->addSecretQuestion(Object(DoctrineORMModule\Proxy\__CG__\PServerCore\Entity\User))
#10 /var/www/page/vendor/zendframework/zend-mvc/src/Controller/AbstractActionController.php(78): PServerCore\Controller\AuthController->pwLostConfirmAction()
#11 /var/www/page/vendor/zendframework/zend-eventmanager/src/EventManager.php(322): Zend\Mvc\Controller\AbstractActionController->onDispatch(Object(Zend\Mvc\MvcEvent))
#12 /var/www/page/vendor/zendframework/zend-eventmanager/src/EventManager.php(179): Zend\EventManager\EventManager->triggerListeners(Object(Zend\Mvc\MvcEvent), Object(Closure))
#13 /var/www/page/vendor/zendframework/zend-mvc/src/Controller/AbstractController.php(105): Zend\EventManager\EventManager->triggerEventUntil(Object(Closure), Object(Zend\Mvc\MvcEvent))
#14 /var/www/page/vendor/zendframework/zend-mvc/src/DispatchListener.php(119): Zend\Mvc\Controller\AbstractController->dispatch(Object(Zend\Http\PhpEnvironment\Request), Object(Zend\Http\PhpEnvironment\Response))
#15 /var/www/page/vendor/zendframework/zend-eventmanager/src/EventManager.php(322): Zend\Mvc\DispatchListener->onDispatch(Object(Zend\Mvc\MvcEvent))
#16 /var/www/page/vendor/zendframework/zend-eventmanager/src/EventManager.php(179): Zend\EventManager\EventManager->triggerListeners(Object(Zend\Mvc\MvcEvent), Object(Closure))
#17 /var/www/page/vendor/zendframework/zend-mvc/src/Application.php(332): Zend\EventManager\EventManager->triggerEventUntil(Object(Closure), Object(Zend\Mvc\MvcEvent))
#18 /var/www/page/public/index.php(18): Zend\Mvc\Application->run()
#19 {main}

Thanks and kind regards.


问:
Build problem: APK not produced, "Nothing to pre compile!"
I compiled my application, and it used to work fine. When I build normally it creates an APK file in the bin folder. Now, nothing.

```<code>[2010-11-30 12:06:58 - MyProject] Removing generated java classes.
[2010-11-30 12:06:58 - MyProject] Refreshing resource folders.
[2010-11-30 12:06:58 - MyProject] Starting full Pre Compiler.
[2010-11-30 12:06:58 - MyProject] Removing generated java classes.
[2010-11-30 12:06:58 - MyProject] Preparing generated java files for update/creation.
[2010-11-30 12:06:58 - MyProject] C:\dev\android-sdk-windows\platforms\android-4\tools\aapt.exe package -m -v -J C:\svn\MyProject\gen -M C:\svn\MyProject\AndroidManifest.xml -S C:\svn\MyProject\res -I C:\dev\android-sdk-windows\platforms\android-4\android.jar
[2010-11-30 12:06:58 - MyProject] Locale/Vendor pairs:
[2010-11-30 12:06:58 - MyProject]    /
[2010-11-30 12:06:58 - MyProject]    /
[2010-11-30 12:06:58 - MyProject]    /
[2010-11-30 12:06:58 - MyProject]    /
[2010-11-30 12:06:58 - MyProject]
[2010-11-30 12:06:58 - MyProject] Files:
... truncated ...
[2010-11-30 12:06:58 - MyProject]       Src: C:\svn\MyProject\res\values\strings.xml
[2010-11-30 12:06:58 - MyProject]   xml\settings.xml
[2010-11-30 12:06:58 - MyProject]       Src: C:\svn\MyProject\res\xml\settings.xml
[2010-11-30 12:06:58 - MyProject]   AndroidManifest.xml
[2010-11-30 12:06:58 - MyProject]       Src: C:\svn\MyProject\AndroidManifest.xml
[2010-11-30 12:06:58 - MyProject] Including resources from package: C:\dev\android-sdk-windows\platforms\android-4\android.jar
[2010-11-30 12:06:58 - MyProject] applyFileOverlay for drawable
[2010-11-30 12:06:58 - MyProject] applyFileOverlay for layout
[2010-11-30 12:06:58 - MyProject] applyFileOverlay for anim
[2010-11-30 12:06:58 - MyProject] applyFileOverlay for xml
[2010-11-30 12:06:58 - MyProject] applyFileOverlay for raw
[2010-11-30 12:06:58 - MyProject] applyFileOverlay for color
[2010-11-30 12:06:58 - MyProject] applyFileOverlay for menu
... truncated ...
[2010-11-30 12:06:58 - MyProject]   Writing symbols for class R.
[2010-11-30 12:06:58 - MyProject] Nothing to pre compile!
[2010-11-30 12:07:00 - MyProject] Refreshing resource folders.
[2010-11-30 12:07:00 - MyProject] Starting incremental Pre Compiler: Checking resource changes.
[2010-11-30 12:07:00 - MyProject] Nothing to pre compile!
</code>```

Everything seems fine until the last line. Verbose is turned on.

Any idea what's wrong??

Thanks.

答: Deleting the project then cleaning, and reimporting it, fixed the problem.</p>

Body:
I compiled my application, and it used to work fine. When I build normally it creates an APK file in the bin folder. Now, nothing.

[2010-11-30 12:06:58 - MyProject] Removing generated java classes.
[2010-11-30 12:06:58 - MyProject] Refreshing resource folders.
[2010-11-30 12:06:58 - MyProject] Starting full Pre Compiler.
[2010-11-30 12:06:58 - MyProject] Removing generated java classes.
[2010-11-30 12:06:58 - MyProject] Preparing generated java files for update/creation.
[2010-11-30 12:06:58 - MyProject] C:\dev\android-sdk-windows\platforms\android-4\tools\aapt.exe package -m -v -J C:\svn\MyProject\gen -M C:\svn\MyProject\AndroidManifest.xml -S C:\svn\MyProject\res -I C:\dev\android-sdk-windows\platforms\android-4\android.jar
[2010-11-30 12:06:58 - MyProject] Locale/Vendor pairs:
[2010-11-30 12:06:58 - MyProject]    /
[2010-11-30 12:06:58 - MyProject]    /
[2010-11-30 12:06:58 - MyProject]    /
[2010-11-30 12:06:58 - MyProject]    /
[2010-11-30 12:06:58 - MyProject]
[2010-11-30 12:06:58 - MyProject] Files:
... truncated ...
[2010-11-30 12:06:58 - MyProject]       Src: C:\svn\MyProject\res\values\strings.xml
[2010-11-30 12:06:58 - MyProject]   xml\settings.xml
[2010-11-30 12:06:58 - MyProject]       Src: C:\svn\MyProject\res\xml\settings.xml
[2010-11-30 12:06:58 - MyProject]   AndroidManifest.xml
[2010-11-30 12:06:58 - MyProject]       Src: C:\svn\MyProject\AndroidManifest.xml
[2010-11-30 12:06:58 - MyProject] Including resources from package: C:\dev\android-sdk-windows\platforms\android-4\android.jar
[2010-11-30 12:06:58 - MyProject] applyFileOverlay for drawable
[2010-11-30 12:06:58 - MyProject] applyFileOverlay for layout
[2010-11-30 12:06:58 - MyProject] applyFileOverlay for anim
[2010-11-30 12:06:58 - MyProject] applyFileOverlay for xml
[2010-11-30 12:06:58 - MyProject] applyFileOverlay for raw
[2010-11-30 12:06:58 - MyProject] applyFileOverlay for color
[2010-11-30 12:06:58 - MyProject] applyFileOverlay for menu
... truncated ...
[2010-11-30 12:06:58 - MyProject]   Writing symbols for class R.
[2010-11-30 12:06:58 - MyProject] Nothing to pre compile!
[2010-11-30 12:07:00 - MyProject] Refreshing resource folders.
[2010-11-30 12:07:00 - MyProject] Starting incremental Pre Compiler: Checking resource changes.
[2010-11-30 12:07:00 - MyProject] Nothing to pre compile!

Everything seems fine until the last line. Verbose is turned on.

Any idea what's wrong??

Thanks.


问:
PHP SQL update using variables posted into form
I have a form that takes variables from another form like so:

```<code>$employeeid = $_POST['modifyid'];
$fname = $_POST['modifyfn'];
$lname = $_POST['modifyln'];
$staffno = $_POST['modifysn'];
$empusername = $_POST['modifyeu'];

</br>
<td><form action="empmodify.php" method="post">
     <?php echo
     "<div class='form-group'>
            <tr><td>ID:</td><td>
                <input type='text' class='form-control' name='modid' value='" . $employeeid . "'/>
            </td></tr>
        </div>

     <div class='form-group'>
            <tr><td>First Name:</td><td>
                <input type='text' class='form-control' name='modfn' value='" . $fname . "'/>
            </td></tr>
        </div>

        <div class='form-group'>
            <tr><td>Surname Name:</td><td>
                <input type='text' class='form-control' name='modln' value='" . $lname . "'/>
            </td></tr>
        </div>

        <div class='form-group'>
            <tr><td>Staff number:</td><td>
                <input type='text' class='form-control' name='modsn' value='" . $staffno . "'/>
            </td></tr>
        </div>

        <div class='form-group'>
            <tr><td>Username:</td><td>
                <input type='text' class='form-control' name='modeu' value='" . $empusername . "'/>
            </td></tr>
        </div>

     <button type='submit' class='btn btn-default'>Modify this Employee</button>"?>
            </form></td>

  </div>
</code>```

These variables are already in the database - This part is working.  What I would like is that when the user clicks submit it updates the record with anything they have changed in this form.  Here is my empmodify.php:

```<code>$employeeid = $_POST['modid'];
    $fname = $_POST['modfn'];
    $lname = $_POST['modln'];
    $staffno = $_POST['modsn'];
    $empusername = $_POST['modeu'];

   $result = mysql_query("UPDATE employee SET fname = '$fname', lname = '$lname', staffno = '$staffno', empusername = '$empusername' WHERE employeeid = '$employeeid'");
</code>```

I have tried so many things with my variables but the update statement just doesn't seem to be working.  I tried single quotes, double quotes, post, and concatenating them but nothing.. any ideas? :)

答:
Try with something like this:</p>

```<code>$result = mysql_query('UPDATE employee SET fname = "'.$fname.'", lname = "'.$lname.'", staffno = "'.$staffno.'", empusername = "'.$empusername.'" WHERE employeeid = "'.$employeeid.'"');
</code>```

Body:
I have a form that takes variables from another form like so:

$employeeid = $_POST['modifyid'];
$fname = $_POST['modifyfn'];
$lname = $_POST['modifyln'];
$staffno = $_POST['modifysn'];
$empusername = $_POST['modifyeu'];

<form action="empmodify.php" method="post">
     <?php echo
     "

ID:
                <input type='text' class='form-control' name='modid' value='" . $employeeid . "'/>

First Name:
                <input type='text' class='form-control' name='modfn' value='" . $fname . "'/>

Surname Name:
                <input type='text' class='form-control' name='modln' value='" . $lname . "'/>

Staff number:
                <input type='text' class='form-control' name='modsn' value='" . $staffno . "'/>

Username:
                <input type='text' class='form-control' name='modeu' value='" . $empusername . "'/>

     <button type='submit' class='btn btn-default'>Modify this Employee</button>"?>
            </form>

These variables are already in the database - This part is working.  What I would like is that when the user clicks submit it updates the record with anything they have changed in this form.  Here is my empmodify.php:

$employeeid = $_POST['modid'];
    $fname = $_POST['modfn'];
    $lname = $_POST['modln'];
    $staffno = $_POST['modsn'];
    $empusername = $_POST['modeu'];

   $result = mysql_query("UPDATE employee SET fname = '$fname', lname = '$lname', staffno = '$staffno', empusername = '$empusername' WHERE employeeid = '$employeeid'");

I have tried so many things with my variables but the update statement just doesn't seem to be working.  I tried single quotes, double quotes, post, and concatenating them but nothing.. any ideas? :)

Body:
Try with something like this:

$result = mysql_query('UPDATE employee SET fname = "'.$fname.'", lname = "'.$lname.'", staffno = "'.$staffno.'", empusername = "'.$empusername.'" WHERE employeeid = "'.$employeeid.'"');


问:
How to automate git commit without calling the "-m" option, to handle inner quotes?
Here is my problem. I have a C++ script which takes strings as messages which will be used for the commit messages.

This works for almost all cases, however the problem arises when <msg> contains either escaped single quotes or double quotes, so the command looks like:

```<code>git commit -m 'A new message \' with many escaped \" \' quotes \"'
</code>```

And so git will get confused.

I don't want to think of how to escape these quotes within the commit message so I think the best way is to avoid using the -m flag, that is to just do a plain git commit and pass <msg> to vi or ed somehow, then quit and save.

My attempt using ed:

```<code>git commit | ed << <msg>
</code>```

vi:

```<code>git commit | vi << I << <msg> << :wq
</code>```

As you can see I am really new to linux and I haven't found anything on the web to describe what I am trying to do. So the question again is: what is the correct sequence of shell commands to commit to git a specific message without invoking the -m flag. What am I doing wrong here?

答:
If you’re just running Git, don’t spawn a shell at all; spawn git directly and pass ["git", "commit", "-m", message] as its argv. In C++:

```<code>#include <string>

extern "C" {
    #include <sys/wait.h>
    #include <unistd.h>
}

struct child_process {
    FILE* file;
    pid_t pid;

    child_process(FILE* file_, pid_t pid_) :
        file(file_),
        pid(pid_) {}
};

template<std::size_t n> static child_process popenv(std::string const& path, std::string const (&args)[n]) {
    char const* const c_path = path.c_str();
    char const* c_argv[n + 2];

    c_argv[0] = c_path;
    c_argv[n + 1] = NULL;

    std::size_t i = 1;

    for (std::string const& arg : args) {
        c_argv[i++] = arg.c_str();
    }

    int fds[2];
    pipe(fds);
    pid_t const pid = fork();

    if (pid == -1) {
        throw std::system_error(errno, std::system_category());
    }

    if (pid == 0) {
        dup2(fds[1], 1);
        execvp(c_path, const_cast<char* const*>(c_argv));
        _exit(EXIT_FAILURE);
    }

    return child_process(fdopen(fds[0], "r"), pid);
}

static int pclosev(child_process const& process) {
    int status;

    fclose(process.file);

    if (waitpid(process.pid, &status, 0) == -1) {
        throw std::system_error(errno, std::system_category());
    }

    return status;
}
</code>```

```<code>std::string const message = "A new message ' with many escaped \" ' quotes \"";
child_process p = popenv("git", {"commit", "-m", message});

// read from p.file; use pclosev() instead of pclose()
</code>```

If you really do need a shell for some reason, pass the message in its argv and run git commit -m "$1".

If you really need to have git commit read its message from standard input for some reason, run git commit -F -. (- can be replaced with any file to read that file.)

Body:
Here is my problem. I have a C++ script which takes strings as messages which will be used for the commit messages.

This works for almost all cases, however the problem arises when <msg> contains either escaped single quotes or double quotes, so the command looks like:

git commit -m 'A new message \' with many escaped \" \' quotes \"'

And so git will get confused.

I don't want to think of how to escape these quotes within the commit message so I think the best way is to avoid using the -m flag, that is to just do a plain git commit and pass <msg> to vi or ed somehow, then quit and save.

My attempt using ed:

git commit | ed << <msg>

vi:

git commit | vi << I << <msg> << :wq

As you can see I am really new to linux and I haven't found anything on the web to describe what I am trying to do. So the question again is: what is the correct sequence of shell commands to commit to git a specific message without invoking the -m flag. What am I doing wrong here?

Body:
If you’re just running Git, don’t spawn a shell at all; spawn git directly and pass ["git", "commit", "-m", message] as its argv. In C++:

#include <string>

extern "C" {
    #include <sys/wait.h>
    #include <unistd.h>
}

struct child_process {
    FILE* file;
    pid_t pid;

    child_process(FILE* file_, pid_t pid_) :
        file(file_),
        pid(pid_) {}
};

template<std::size_t n> static child_process popenv(std::string const& path, std::string const (&args)[n]) {
    char const* const c_path = path.c_str();
    char const* c_argv[n + 2];

    c_argv[0] = c_path;
    c_argv[n + 1] = NULL;

    std::size_t i = 1;

    for (std::string const& arg : args) {
        c_argv[i++] = arg.c_str();
    }

    int fds[2];
    pipe(fds);
    pid_t const pid = fork();

    if (pid == -1) {
        throw std::system_error(errno, std::system_category());
    }

    if (pid == 0) {
        dup2(fds[1], 1);
        execvp(c_path, const_cast<char* const*>(c_argv));
        _exit(EXIT_FAILURE);
    }

    return child_process(fdopen(fds[0], "r"), pid);
}

static int pclosev(child_process const& process) {
    int status;

    fclose(process.file);

    if (waitpid(process.pid, &status, 0) == -1) {
        throw std::system_error(errno, std::system_category());
    }

    return status;
}

std::string const message = "A new message ' with many escaped \" ' quotes \"";
child_process p = popenv("git", {"commit", "-m", message});

// read from p.file; use pclosev() instead of pclose()

If you really do need a shell for some reason, pass the message in its argv and run git commit -m "$1".

If you really need to have git commit read its message from standard input for some reason, run git commit -F -. (- can be replaced with any file to read that file.)


问:
unsigned char value in a function
This is taken from: https://exploreembedded.com/wiki/AVR_C_Library DS1307_GetTime() method, im trying to understand how this function works. So i made a simplified example below.

Can you explain what is happening in the  GetTime() function and what kid of value should  I pass into it?

My goal is to obtain b value inside int main() function.

My understanding so far is:

pointer * a = I2C_Read(); points to unsigned char, but a pointer can not point to a value, why isnt it erroring?

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

unsigned char I2C_Read()
{
    unsigned char b = 0b11111111;
    return b;
}

void GetTime(unsigned char *a)
{
    *a = I2C_Read();
}

int main()
{
    unsigned char *a = 0;
    GetTime(a);                        // ?

    printf("Value of b is: %d\n" , b); // ?
}
</code>```

答:
Aa I get it now, thank you</p>

```<code>1) GetTime(&a);                    // pass  in address of a.
2) GetTime(unsigned char *a)       // takes in contents of a, at the moment = 0
3) *a = read();                    // set contents of a to unsigned char 0b11111111
4) printf("Value of b: %d\n" , a); // call this from main func results in returned value b = 255
</code>```

Title: unsigned char value in a function

Body:
This is taken from: https://exploreembedded.com/wiki/AVR_C_Library DS1307_GetTime() method, im trying to understand how this function works. So i made a simplified example below.

Can you explain what is happening in the  GetTime() function and what kid of value should  I pass into it?

My goal is to obtain b value inside int main() function.

My understanding so far is:

pointer * a = I2C_Read(); points to unsigned char, but a pointer can not point to a value, why isnt it erroring?

#include <stdio.h>
#include <stdlib.h>

unsigned char I2C_Read()
{
    unsigned char b = 0b11111111;
    return b;
}

void GetTime(unsigned char *a)
{
    *a = I2C_Read();
}

int main()
{
    unsigned char *a = 0;
    GetTime(a);                        // ?

    printf("Value of b is: %d\n" , b); // ?
}

Body:
Aa I get it now, thank you

1) GetTime(&a);                    // pass  in address of a.
2) GetTime(unsigned char *a)       // takes in contents of a, at the moment = 0
3) *a = read();                    // set contents of a to unsigned char 0b11111111
4) printf("Value of b: %d\n" , a); // call this from main func results in returned value b = 255


问:
Returning unique_ptr from functions
unique_ptr<T> does not allow copy construction, instead it supports move semantics. Yet, I can return a unique_ptr<T> from a function and assign the returned value to a variable.

```<code>#include <iostream>
#include <memory>

using namespace std;

unique_ptr<int> foo()
{
  unique_ptr<int> p( new int(10) );

  return p;                   // 1
  //return move( p );         // 2
}

int main()
{
  unique_ptr<int> p = foo();

  cout << *p << endl;
  return 0;
}
</code>```

The code above compiles and works as intended. So how is it that line 1 doesn't invoke the copy constructor and result in compiler errors? If I had to use line 2 instead it'd make sense (using line 2 works as well, but we're not required to do so).

I know C++0x allows this exception to unique_ptr since the return value is a temporary object that will be destroyed as soon as the function exits, thus guaranteeing the uniqueness of the returned pointer. I'm curious about how this is implemented, is it special cased in the compiler or is there some other clause in the language specification that this exploits?

答:
This is in no way specific to std::unique_ptr, but applies to any class that is movable. It's guaranteed by the language rules since you are returning by value. The compiler tries to elide copies, invokes a move constructor if it can't remove copies, calls a copy constructor if it can't move, and fails to compile if it can't copy.

If you had a function that accepts std::unique_ptr as an argument you wouldn't be able to pass p to it. You would have to explicitly invoke move constructor, but in this case you shouldn't use variable p after the call to bar().

```<code>void bar(std::unique_ptr<int> p)
{
    // ...
}

int main()
{
    unique_ptr<int> p = foo();
    bar(p); // error, can't implicitly invoke move constructor on lvalue
    bar(std::move(p)); // OK but don't use p afterwards
    return 0;
}
</code>```

Title: Returning unique_ptr from functions

Body:
unique_ptr<T> does not allow copy construction, instead it supports move semantics. Yet, I can return a unique_ptr<T> from a function and assign the returned value to a variable.

#include <iostream>
#include <memory>

using namespace std;

unique_ptr<int> foo()
{
  unique_ptr<int> p( new int(10) );

  return p;                   // 1
  //return move( p );         // 2
}

int main()
{
  unique_ptr<int> p = foo();

  cout << *p << endl;
  return 0;
}

The code above compiles and works as intended. So how is it that line 1 doesn't invoke the copy constructor and result in compiler errors? If I had to use line 2 instead it'd make sense (using line 2 works as well, but we're not required to do so).

I know C++0x allows this exception to unique_ptr since the return value is a temporary object that will be destroyed as soon as the function exits, thus guaranteeing the uniqueness of the returned pointer. I'm curious about how this is implemented, is it special cased in the compiler or is there some other clause in the language specification that this exploits?

Body:
This is in no way specific to std::unique_ptr, but applies to any class that is movable. It's guaranteed by the language rules since you are returning by value. The compiler tries to elide copies, invokes a move constructor if it can't remove copies, calls a copy constructor if it can't move, and fails to compile if it can't copy.

If you had a function that accepts std::unique_ptr as an argument you wouldn't be able to pass p to it. You would have to explicitly invoke move constructor, but in this case you shouldn't use variable p after the call to bar().

void bar(std::unique_ptr<int> p)
{
    // ...
}

int main()
{
    unique_ptr<int> p = foo();
    bar(p); // error, can't implicitly invoke move constructor on lvalue
    bar(std::move(p)); // OK but don't use p afterwards
    return 0;
}


问:
How do I use external JavaScript libraries with Elm?
I've been testing Elm lately for a project but encountered a few problems - one of them is using external JS libraries with Elm (e.g. Moment.js, i18n, firebase etc). I've tried the example below but it doesn't exactly answer what I want:

https://gist.github.com/evancz/e69723b23958e69b63d5b5502b0edf90

According to the example, I have to create individual programs just to port the module out and generate a static .js files for each of them. Is it possible to just write all the ports in one single file and what are the best practices for using port?

答:
According to the example, I have to create individual programs just to port the module out and generate a static .js files for each of them.

I don't believe this is true.  The spelling example you link to is only intended to be an example of how to use ports.  You don't have to compile each part of your program that uses a port into its own separate .js file.

You could put all the ports in one module, but I would hesitate to do this.  In my opinion a better approach would be to have one port module for each external JS library you want to use, and put all the ports you use for communicating with that library in that module.  That way, the responsibility of each such module is clear.  Then, compile you whole Elm application, port modules and all, into one .js file.

what are the best practices for using port?

Well, this is a bit open-ended.  Nonetheless, from my somewhat limited experience:

Keep port-handling in separate modules, and don't declare a module as a port module if it doesn't need to be.

Ensure you test the integration with the third-party libraries thoroughly, in particular with error cases.  Elm will throw an exception if the type of data coming through a port from an external library back into Elm isn't as you've declared it to be.

If you can find an Elm package that does the same as an external JS library, consider using that instead.


答:
From what I see (and from the errors my IDE gave to this code),
you have some basic compilation issues.

In the method main(String[]), referring to this line:

```<code>buildPath (right, down, path, allPaths, N);
</code>```

You have not defined the vars "right", "down", "allPaths" in main. These are the internal names of the arguments in BuildPath(int, int, String,   ArrayList, int) and you cannot use their names from outside.

The same goes for what is happening in BuildPath(int, int, String,   ArrayList, int), you cannot use "ol1_right", "ol1_down" as they are defined only in main(String[]).

Another separate issue is in this line:

```<code>path += "(" + down "," + right + ")->";
</code>```

Add a + after down.

Yet another issue is with semi-colons in if statements:

```<code>else if (right +1 == ol1_right && down == ol1_down) && (right +1 ==
    ol2_right && down == ol2_down);{
</code>```

Should be (remove ; and add outer ( )):

```<code>else if ((right +1 == ol1_right && down == ol1_down) && (right +1 ==
    ol2_right && down == ol2_down)) {
</code>```

Title: Abit stuck why i cant get this working :/

Body:
From what I see (and from the errors my IDE gave to this code),
you have some basic compilation issues.

In the method main(String[]), referring to this line:

buildPath (right, down, path, allPaths, N);

You have not defined the vars "right", "down", "allPaths" in main. These are the internal names of the arguments in BuildPath(int, int, String,   ArrayList, int) and you cannot use their names from outside.

The same goes for what is happening in BuildPath(int, int, String,   ArrayList, int), you cannot use "ol1_right", "ol1_down" as they are defined only in main(String[]).

Another separate issue is in this line:

path += "(" + down "," + right + ")->";

Add a + after down.

Yet another issue is with semi-colons in if statements:

else if (right +1 == ol1_right && down == ol1_down) && (right +1 ==
    ol2_right && down == ol2_down);{

Should be (remove ; and add outer ( )):

else if ((right +1 == ol1_right && down == ol1_down) && (right +1 ==
    ol2_right && down == ol2_down)) {


问:
error when recreating sentence
So I have a program that looks at a sentence in a .txt file. The program then finds the position of each word in the sentence as well as the unique words in the sentence. These two lists are outputted in the program and then the program tries to recreate the original sentence in the .txt file based on the unique words in the sentence and position of words in the sentence, which then should be outputted in the program. The code I have so far is shown below:

```<code>import json
import os.path

def InputFile():
    global compfilename
    compfilename = input("Please enter an existing compressed file to be decompressed: ")

def Validation2():
    if compfilename == (""):
        print ("Nothing was entered for the filename. Please re-enter a valid filename.")
        Error()
    if os.path.exists(compfilename + ".txt") == False:
        print ("No such file exists. Please enter a valid existing file.")
        Error()

def OutputDecompressed():
    global words
    global orgsentence
    newfile = open((compfilename)+'.txt', 'r')
    saveddata = json.load(newfile)
    orgsentence = saveddata
    words = orgsentence.split(' ')
    print ("Words in the sentence: " + str(words))

def Uniquewords():
    for i in range(len(words)):
        if words[i] not in unilist:
            unilist.append(words[i])
    print ("Unique words: " + str(unilist))

def PosText():
    global pos
    find = dict((sentence, words.index(sentence)+1) for sentence in list(words))
    pos = (list(map(lambda sentence: find [sentence], words)))
    return (pos)

def Error():
    MainCompression()

def OutputDecompressed2():
    for number in pos:
    decompression.append(orgsentence[int(number)-1])
    finalsentence = (" ".join(decompression))
    print ("Original sentence from file: " + finalsentence)

def OutputText():
    print ("The positions of the word(s) in the sentence are: " + str(pos))

def MainCompression():
    global decompression
    decompression = []
    global unilist
    unilist = []
    InputFile()
    Validation2()
    OutputDecompressed()
    Uniquewords()
    PosText()
    OutputText()
    OutputDecompressed2()

MainCompression()
</code>```

An example test is described now. Say there is a .txt file called 'ohdear' and contains the sentence: "hello hello hello hello"

Now the program is shown below:

```<code>Please enter an existing compressed file to be decompressed: ohdear
Words in the sentence: ['hello', 'hello', 'hello', 'hello']
Unique words: ['hello']
The positions of the word(s) in the sentence are: [1, 1, 1, 1]
Original sentence from file: h h h h
</code>```

As you can see, the original sentence was not recreated from the unique words and position of words in the sentence - strangely 4 h's were displayed. Can someone help with this error as I have no idea how to recreate the original sentence from just the unique words and position of words in the sentence. The problem is in the OutputDecompressed2() function. Thanks for any help in advance. I have been stuck on this for a while...

答:
```<code>words = orgsentence.split(' ')
</code>```

This means that words is a list of strings and orgsentence is just one big string. But later you get:

```<code>orgsentence[int(number)-1]
</code>```

Which is just going to be a character. Rather get words[int(number)-1].

Also:

```<code>find = dict((sentence, words.index(sentence)+1) for sentence in list(words))
</code>```

just gives you the first occurrence of each 'sentence' since that's what .index does, hence you have the output:

```<code>The positions of the word(s) in the sentence are: [1, 1, 1, 1]
</code>```

which is obviously wrong.

And by the way, sentence is a terrible variable name at that point, why not word?

Title: error when recreating sentence

Body:
So I have a program that looks at a sentence in a .txt file. The program then finds the position of each word in the sentence as well as the unique words in the sentence. These two lists are outputted in the program and then the program tries to recreate the original sentence in the .txt file based on the unique words in the sentence and position of words in the sentence, which then should be outputted in the program. The code I have so far is shown below:

import json
import os.path

def InputFile():
    global compfilename
    compfilename = input("Please enter an existing compressed file to be decompressed: ")

def Validation2():
    if compfilename == (""):
        print ("Nothing was entered for the filename. Please re-enter a valid filename.")
        Error()
    if os.path.exists(compfilename + ".txt") == False:
        print ("No such file exists. Please enter a valid existing file.")
        Error()

def OutputDecompressed():
    global words
    global orgsentence
    newfile = open((compfilename)+'.txt', 'r')
    saveddata = json.load(newfile)
    orgsentence = saveddata
    words = orgsentence.split(' ')
    print ("Words in the sentence: " + str(words))

def Uniquewords():
    for i in range(len(words)):
        if words[i] not in unilist:
            unilist.append(words[i])
    print ("Unique words: " + str(unilist))

def PosText():
    global pos
    find = dict((sentence, words.index(sentence)+1) for sentence in list(words))
    pos = (list(map(lambda sentence: find [sentence], words)))
    return (pos)

def Error():
    MainCompression()

def OutputDecompressed2():
    for number in pos:
    decompression.append(orgsentence[int(number)-1])
    finalsentence = (" ".join(decompression))
    print ("Original sentence from file: " + finalsentence)

def OutputText():
    print ("The positions of the word(s) in the sentence are: " + str(pos))

def MainCompression():
    global decompression
    decompression = []
    global unilist
    unilist = []
    InputFile()
    Validation2()
    OutputDecompressed()
    Uniquewords()
    PosText()
    OutputText()
    OutputDecompressed2()

MainCompression()

An example test is described now. Say there is a .txt file called 'ohdear' and contains the sentence: "hello hello hello hello"

Now the program is shown below:

Please enter an existing compressed file to be decompressed: ohdear
Words in the sentence: ['hello', 'hello', 'hello', 'hello']
Unique words: ['hello']
The positions of the word(s) in the sentence are: [1, 1, 1, 1]
Original sentence from file: h h h h

As you can see, the original sentence was not recreated from the unique words and position of words in the sentence - strangely 4 h's were displayed. Can someone help with this error as I have no idea how to recreate the original sentence from just the unique words and position of words in the sentence. The problem is in the OutputDecompressed2() function. Thanks for any help in advance. I have been stuck on this for a while...

Body:
words = orgsentence.split(' ')

This means that words is a list of strings and orgsentence is just one big string. But later you get:

orgsentence[int(number)-1]

Which is just going to be a character. Rather get words[int(number)-1].

Also:

find = dict((sentence, words.index(sentence)+1) for sentence in list(words))

just gives you the first occurrence of each 'sentence' since that's what .index does, hence you have the output:

The positions of the word(s) in the sentence are: [1, 1, 1, 1]

which is obviously wrong.

And by the way, sentence is a terrible variable name at that point, why not word?


问:
How to add a default value to EditText: android
I have an EditText which returns an empty string on calling edittext.getText().toString(). Instead of returning an empty string, I want to set a default value for this result and i don't want that value to be shown in EditText. Is it possible to do so? If yes then how can i do that?

答:
Is it possible to do so?

No, sorry, EditText does not offer that feature.


问:
Pandas Dataframe: Split a column into multiple columns
I have a pandas dataframe with columns names as: (columns type as Object)

```<code>1. x_id
2. y_id
3. Sentence1
4. Sentences2
5. Label
</code>```

I want to separate sentences1 and sentence2 into multiple columns in same dataframe.

Here is an example: dataframe names as df

```<code>x_id     y_id     Sentence1          Sentence2          Label
0        2        This is a ball     I hate you         0
1        5        I am a boy         Ahmed Ali          1
2        1        Apple is red       Rose is red        1
3        9        I love you so much Me too             1
</code>```

After splitting the columns[Sentence1,Sentence2] by ' ' Space, dataframe looks like:

```<code>x_id     y_id     1     2     3    4     5      6      7     8      Label
0        2        This  is    a    ball  NONE   I      hate  you    0
1        5        I     am    a    boy   NONE   Ahmed  Ali   NONE   1
2        1        Apple is    red  NONE  NONE   Rose   is    red    1
3        9        I     love  you  so    much   Me     too   NONE   1
</code>```

How to split the columns like this in python? How to do this using pandas dataframe?

答:
One-hot-encoding labeling solution:

```<code>In [14]: df.Sentence1 += ' ' + df.pop('Sentence2')

In [15]: df
Out[15]:
   x_id  y_id                  Sentence1  Label
0     0     2  This is a ball I hate you      0
1     1     5       I am a boy Ahmed Ali      1
2     2     1   Apple is red Rose is red      1
3     3     9  I love you so much Me too      1

In [16]: from sklearn.feature_extraction.text import CountVectorizer

In [17]: vect = CountVectorizer()

In [18]: X = vect.fit_transform(df.Sentence1.fillna(''))
</code>```

X - is a sparsed (memory saving) matrix:

```<code>In [23]: X
Out[23]:
<4x17 sparse matrix of type '<class 'numpy.int64'>'
        with 19 stored elements in Compressed Sparse Row format>

In [24]: type(X)
Out[24]: scipy.sparse.csr.csr_matrix

In [19]: X.toarray()
Out[19]:
array([[0, 0, 0, 0, 1, 0, 1, 1, 0, 0, 0, 0, 0, 0, 1, 0, 1],
       [1, 1, 1, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
       [0, 0, 0, 1, 0, 0, 0, 2, 0, 0, 0, 2, 1, 0, 0, 0, 0],
       [0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 0, 0, 1, 0, 1, 1]], dtype=int64)
</code>```

Most of sklearn methods accept sparsed matrixes.

If you want to "unpack" it:

```<code>In [21]: r = pd.DataFrame(X.toarray(), columns=vect.get_feature_names())

In [22]: r
Out[22]:
   ahmed  ali  am  apple  ball  boy  hate  is  love  me  much  red  rose  so  this  too  you
0      0    0   0      0     1    0     1   1     0   0     0    0     0   0     1    0    1
1      1    1   1      0     0    1     0   0     0   0     0    0     0   0     0    0    0
2      0    0   0      1     0    0     0   2     0   0     0    2     1   0     0    0    0
3      0    0   0      0     0    0     0   0     1   1     1    0     0   1     0    1    1
</code>```

Body:
I have a pandas dataframe with columns names as: (columns type as Object)

1. x_id
2. y_id
3. Sentence1
4. Sentences2
5. Label

I want to separate sentences1 and sentence2 into multiple columns in same dataframe.

Here is an example: dataframe names as df

x_id     y_id     Sentence1          Sentence2          Label
0        2        This is a ball     I hate you         0
1        5        I am a boy         Ahmed Ali          1
2        1        Apple is red       Rose is red        1
3        9        I love you so much Me too             1

After splitting the columns[Sentence1,Sentence2] by ' ' Space, dataframe looks like:

x_id     y_id     1     2     3    4     5      6      7     8      Label
0        2        This  is    a    ball  NONE   I      hate  you    0
1        5        I     am    a    boy   NONE   Ahmed  Ali   NONE   1
2        1        Apple is    red  NONE  NONE   Rose   is    red    1
3        9        I     love  you  so    much   Me     too   NONE   1

How to split the columns like this in python? How to do this using pandas dataframe?

Body:
One-hot-encoding labeling solution:

In [14]: df.Sentence1 += ' ' + df.pop('Sentence2')

In [15]: df
Out[15]:
   x_id  y_id                  Sentence1  Label
0     0     2  This is a ball I hate you      0
1     1     5       I am a boy Ahmed Ali      1
2     2     1   Apple is red Rose is red      1
3     3     9  I love you so much Me too      1

In [16]: from sklearn.feature_extraction.text import CountVectorizer

In [17]: vect = CountVectorizer()

In [18]: X = vect.fit_transform(df.Sentence1.fillna(''))

X - is a sparsed (memory saving) matrix:

In [23]: X
Out[23]:
<4x17 sparse matrix of type '<class 'numpy.int64'>'
        with 19 stored elements in Compressed Sparse Row format>

In [24]: type(X)
Out[24]: scipy.sparse.csr.csr_matrix

In [19]: X.toarray()
Out[19]:
array([[0, 0, 0, 0, 1, 0, 1, 1, 0, 0, 0, 0, 0, 0, 1, 0, 1],
       [1, 1, 1, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
       [0, 0, 0, 1, 0, 0, 0, 2, 0, 0, 0, 2, 1, 0, 0, 0, 0],
       [0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 0, 0, 1, 0, 1, 1]], dtype=int64)

Most of sklearn methods accept sparsed matrixes.

If you want to "unpack" it:

In [21]: r = pd.DataFrame(X.toarray(), columns=vect.get_feature_names())

In [22]: r
Out[22]:
   ahmed  ali  am  apple  ball  boy  hate  is  love  me  much  red  rose  so  this  too  you
0      0    0   0      0     1    0     1   1     0   0     0    0     0   0     1    0    1
1      1    1   1      0     0    1     0   0     0   0     0    0     0   0     0    0    0
2      0    0   0      1     0    0     0   2     0   0     0    2     1   0     0    0    0
3      0    0   0      0     0    0     0   0     1   1     1    0     0   1     0    1    1


问:
XAML Custom GridViewColumn Data
I am trying to create an application that shows a list of 'Characters' with the properties Sleep, Hunger, Boredom and Health. I want to show the current characters and their status (status depends on which of the values is the biggest (Sleep, Hunger and Boredom)). Since status isnt a property in the character class I am not able to do it as I did with the name and health:

```<code> <ListView x:Name="TamagochiList" Margin="10,34,10,118" ItemsSource="{Binding TamagochiList}">
            <ListView.View>
                <GridView>
                    <GridViewColumn Header="Name" Width="100" DisplayMemberBinding="{Binding Path=Name}" />
                    <GridViewColumn Header="Health" Width="200" DisplayMemberBinding="{Binding Path=Health}" />
                </GridView>
            </ListView.View>
        </ListView>
</code>```

I tried adding this in the viewmodel but I currently have no idea how to use it:

```<code>   public string TamagochiStatus(Tamagochi t)
        {
            if(t.Boredom >= t.Hunger && t.Boredom >= t.Sleep)
            {
                return "Bored";
            }
            if(t.Hunger >= t.Boredom && t.Hunger >= t.Sleep)
            {
                return "Hungry";
            }
            if(t.Sleep >= t.Boredom && t.Sleep >= t.Hunger)
            {
                return "Sleepy";
            }
            return "Geen status";
        }
</code>```

Tried my best to find it but I was not sure about which keywords to choose.

答:
Since Status is a property of the data itself, and not just an artifact for the UI, move the calculation into a property in your model class.

```<code>public class Character
{
     public string Name {get; set;}
     public int Health {get; set;}
     public int Boredom {get; set;}
     public int Sleep {get; set;}
     public int Hunger {get; set;}
     public string Status
     {
          get
          {
               if(Boredom >= Hunger && Boredom >= Sleep)
               {
                    return "Bored";
               }
               if(Hunger >= Boredom && t.Hunger >= Sleep)
               {
                    return "Hungry";
               }
               if(Sleep >= Boredom && Sleep >= Hunger)
               {
                    return "Sleepy";
               }
               return "Geen status";
          }
}
</code>```

Then bind directly to that property via

```<code><GridViewColumn Header="Status" Width="200" DisplayMemberBinding="{Binding Path=Status}" />
</code>```

Title: XAML Custom GridViewColumn Data

Body:
I am trying to create an application that shows a list of 'Characters' with the properties Sleep, Hunger, Boredom and Health. I want to show the current characters and their status (status depends on which of the values is the biggest (Sleep, Hunger and Boredom)). Since status isnt a property in the character class I am not able to do it as I did with the name and health:

 <ListView x:Name="TamagochiList" Margin="10,34,10,118" ItemsSource="{Binding TamagochiList}">
            <ListView.View>
                <GridView>
                    <GridViewColumn Header="Name" Width="100" DisplayMemberBinding="{Binding Path=Name}" />
                    <GridViewColumn Header="Health" Width="200" DisplayMemberBinding="{Binding Path=Health}" />
                </GridView>
            </ListView.View>
        </ListView>

I tried adding this in the viewmodel but I currently have no idea how to use it:

   public string TamagochiStatus(Tamagochi t)
        {
            if(t.Boredom >= t.Hunger && t.Boredom >= t.Sleep)
            {
                return "Bored";
            }
            if(t.Hunger >= t.Boredom && t.Hunger >= t.Sleep)
            {
                return "Hungry";
            }
            if(t.Sleep >= t.Boredom && t.Sleep >= t.Hunger)
            {
                return "Sleepy";
            }
            return "Geen status";
        }

Tried my best to find it but I was not sure about which keywords to choose.

Body:
Since Status is a property of the data itself, and not just an artifact for the UI, move the calculation into a property in your model class.

public class Character
{
     public string Name {get; set;}
     public int Health {get; set;}
     public int Boredom {get; set;}
     public int Sleep {get; set;}
     public int Hunger {get; set;}
     public string Status
     {
          get
          {
               if(Boredom >= Hunger && Boredom >= Sleep)
               {
                    return "Bored";
               }
               if(Hunger >= Boredom && t.Hunger >= Sleep)
               {
                    return "Hungry";
               }
               if(Sleep >= Boredom && Sleep >= Hunger)
               {
                    return "Sleepy";
               }
               return "Geen status";
          }
}

Then bind directly to that property via

<GridViewColumn Header="Status" Width="200" DisplayMemberBinding="{Binding Path=Status}" />