问:
C Array change causing variable modification
I am trying to modify a value in an array using the C programming language and I seem to be hitting a blank wall with this seemingly easy operation. Please see code snippet below:

```<code>while(1) {
        printf("Current prime candidate is %i\n",nextPrimeCandidate);
        int innerSieve;//=2;
        int currentPrimeCandidate=0;

        for (innerSieve=2;innerSieve<SIEVELIMIT;innerSieve++) {
            currentPrimeCandidate = nextPrimeCandidate * innerSieve;
            //printf("Inner Sieve  is b4 funny place %i,%i\n",innerSieve,currentPrimeCandidate);

            //initArray[currentPrimeCandidate]=5;
            //VERY UNIQUE LINE
            myArray[currentPrimeCandidate] = 0;

            //printf("Inner Sieve after funny place is %i,%i \n",innerSieve,currentPrimeCandidate);

        }
        nextPrimeCandidate=getNextPrimeCandidate(myArray,++nextPrimeCandidate);
        if ((nextPrimeCandidate^2) > SIEVELIMIT ) break;

    }
</code>```

The problem is with the line highlighted with the VERY UNIQUE LINE comment. For some reason, when the innerSieve variable reaches 33 and gets to that line, it sets the contents of the innerSieve variable to the value of that line ( which currently is 0) and basically forces the loop into an infinite loop( the SIEVELIMIT variable is set at 50). It seems that there is some funny stuff going on in the registers when I checked using the Eclipse Debug facility but I am not too sure what I should be looking for.

If you need the whole code listing, this can be provided.( with a particular variable which is not yet initialised in the code being initialised at the precise point that the innerSieve variable hits 32)

Any help will be greatly appreciated.

答:
@ruslik hit on it in the comment.  The problem is this line:

```<code>if ((nextPrimeCandidate^2) > SIEVELIMIT ) break;
</code>```

In C, the ^ operator is not the power operator, it is the bitwise xor operator.  You're iterating far too many times than you intend, which is resulting in an array-index-out-of-bounds error, so you're overwriting random memory and getting strange results.

There is no power operator in C (though there is the pow function).  Since you're just squaring a number, the simplest fix is to multiply the number by itself:

```<code>if ((nextPrimeCandidate * nextPrimeCandidate) > SIEVELIMIT ) break;
</code>```

Body:
I am trying to modify a value in an array using the C programming language and I seem to be hitting a blank wall with this seemingly easy operation. Please see code snippet below:

while(1) {
        printf("Current prime candidate is %i\n",nextPrimeCandidate);
        int innerSieve;//=2;
        int currentPrimeCandidate=0;

        for (innerSieve=2;innerSieve<SIEVELIMIT;innerSieve++) {
            currentPrimeCandidate = nextPrimeCandidate * innerSieve;
            //printf("Inner Sieve  is b4 funny place %i,%i\n",innerSieve,currentPrimeCandidate);

            //initArray[currentPrimeCandidate]=5;
            //VERY UNIQUE LINE
            myArray[currentPrimeCandidate] = 0;

            //printf("Inner Sieve after funny place is %i,%i \n",innerSieve,currentPrimeCandidate);

        }
        nextPrimeCandidate=getNextPrimeCandidate(myArray,++nextPrimeCandidate);
        if ((nextPrimeCandidate^2) > SIEVELIMIT ) break;

    }

The problem is with the line highlighted with the VERY UNIQUE LINE comment. For some reason, when the innerSieve variable reaches 33 and gets to that line, it sets the contents of the innerSieve variable to the value of that line ( which currently is 0) and basically forces the loop into an infinite loop( the SIEVELIMIT variable is set at 50). It seems that there is some funny stuff going on in the registers when I checked using the Eclipse Debug facility but I am not too sure what I should be looking for.

If you need the whole code listing, this can be provided.( with a particular variable which is not yet initialised in the code being initialised at the precise point that the innerSieve variable hits 32)

Any help will be greatly appreciated.

Body:
@ruslik hit on it in the comment.  The problem is this line:

if ((nextPrimeCandidate^2) > SIEVELIMIT ) break;

In C, the ^ operator is not the power operator, it is the bitwise xor operator.  You're iterating far too many times than you intend, which is resulting in an array-index-out-of-bounds error, so you're overwriting random memory and getting strange results.

There is no power operator in C (though there is the pow function).  Since you're just squaring a number, the simplest fix is to multiply the number by itself:

if ((nextPrimeCandidate * nextPrimeCandidate) > SIEVELIMIT ) break;


来源: stackexchange

问:
Symfony 3: GroupSequence validation groups ignored in validation of form
I would like to validate a form using group validation and therefore I defined two validation groups. The second group should only be validated if the first group does not already cause violations. So I did this:

```<code>        $form = $this->createFormBuilder(null,array('validation_groups' => new GroupSequence(array('group1','group2'))))
        ->add('email', EmailType::class,array('constraints' => array(
            new Assert\Email(array('groups' => array('group1'))),
            new Assert\NotBlank(array('groups' => array('group1'))),
            new CustomAssert\AlreadyRegistered(array('groups' => array('group2'))))))
        ->add('submit',SubmitType::class,array())
        ->getForm();
</code>```

But apparently none of the constraints are validated, the form is valid no matter what I enter in the email field.

What's wrong?

答:
According to the 3.2 documentation you don't need to initiate a new GroupSequence object under the validation_groups. Try this:

```<code>    $form = $this->createFormBuilder(null, array(
        'validation_groups' => array('group1','group2')
    ))
    ->add(
        'email',
        EmailType::class,
        array(
            'constraints' => array(
                new Assert\Email(array('groups' => array('group1'))),
                new Assert\NotBlank(array('groups' => array('group1'))),
                new CustomAssert\AlreadyRegistered(array('groups' => array('group2')))
    )))
    ->add(
        'submit',
        SubmitType::class
    )
    ->getForm();
</code>```

Reference: http://symfony.com/doc/current/form/validation_groups.html

ContentLicense: CC BY-SA 3.0

Body:
I would like to validate a form using group validation and therefore I defined two validation groups. The second group should only be validated if the first group does not already cause violations. So I did this:

        $form = $this->createFormBuilder(null,array('validation_groups' => new GroupSequence(array('group1','group2'))))
        ->add('email', EmailType::class,array('constraints' => array(
            new Assert\Email(array('groups' => array('group1'))),
            new Assert\NotBlank(array('groups' => array('group1'))),
            new CustomAssert\AlreadyRegistered(array('groups' => array('group2'))))))
        ->add('submit',SubmitType::class,array())
        ->getForm();

But apparently none of the constraints are validated, the form is valid no matter what I enter in the email field.

What's wrong?

Body:
According to the 3.2 documentation you don't need to initiate a new GroupSequence object under the validation_groups. Try this:

    $form = $this->createFormBuilder(null, array(
        'validation_groups' => array('group1','group2')
    ))
    ->add(
        'email',
        EmailType::class,
        array(
            'constraints' => array(
                new Assert\Email(array('groups' => array('group1'))),
                new Assert\NotBlank(array('groups' => array('group1'))),
                new CustomAssert\AlreadyRegistered(array('groups' => array('group2')))
    )))
    ->add(
        'submit',
        SubmitType::class
    )
    ->getForm();

Reference: http://symfony.com/doc/current/form/validation_groups.html


问:
How to soap call a service in android studio without using ksoap
i have this code running on android studio:

MainActivity.java

```<code>package myname.company.com.soap__03;

import android.net.Uri;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.ProtocolException;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;

public class MainActivity extends AppCompatActivity {

    private static HashMap<String, String> mHeaders = new HashMap<>();

    static {
        mHeaders.put("Accept-Encoding", "gzip,deflate");
        mHeaders.put("Content-Type", "application/soap+xml");
        mHeaders.put("Host", "server:port");
        mHeaders.put("Connection", "Keep-Alive");
        mHeaders.put("User-Agent", "AndroidApp");
        // mHeaders.put("Authorization", "Basic Q2xpZW50NTkzMzppMjR3s2U="); // optional
    }

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

        try {
            Button openButton = (Button) findViewById(R.id.open);

            openButton.setOnClickListener(new View.OnClickListener() {
                public void onClick(View v) {
                    try {
                        receiveCurrentShipments("WSDL URL");

                    } catch (Exception ex) {
                        ex.printStackTrace();
                    }
                }
            });
        }catch(Exception e) {
            e.printStackTrace();
        }
    }

    public final static InputStream receiveCurrentShipments(String stringUrlShipments) {
        int status = 0;
        String xmlstring = "<soapenv:Envelope xmlns:soapenv=\"http://someurl\" "+
                "xmlns:soap=\"someurl\" "+
                "xmlns:gen=\"http://someurl\"> "+
        "<soapenv:Header> "+
        "<auth:EventID xmlns:auth='http://someurl'>3000</auth:EventID> "+
        "</soapenv:Header> "+
        "<soapenv:Body> "+
        "<gen:getGenericResult> "+
        "<Request> "+
        "<dataItem> "+
        "<name>Username</name> "+
        "<type>String</type> "+
        "<value>usernamehere</value> "+
        "</dataItem> "+
        "<dataItem> "+
        "<name>Password</name> "+
        "<type>String</type> "+
        "<value>passwordhere</value> "+
        "</dataItem> "+
        "</Request> "+
        "</gen:getGenericResult> "+
        "</soapenv:Body> "+
        "</soapenv:Envelope>";

       // StringBuffer chaine = new StringBuffer("");

        HttpURLConnection connection = null;

        try {
            URL url = new URL(stringUrlShipments);
            connection = (HttpURLConnection) url.openConnection();
            connection.setRequestProperty("Content-Length", xmlstring.getBytes().length + "");
            connection.setRequestProperty("SOAPAction", "http://NAMESPACE\METHOD_NAME");

            for (Map.Entry<String, String> entry : mHeaders.entrySet()) {
                String key = entry.getKey();
                String value = entry.getValue();
                connection.setRequestProperty(key, value);

            }

            connection.setRequestMethod("POST");
            connection.setDoInput(true);

            OutputStream outputStream = connection.getOutputStream();
            outputStream.write(xmlstring.getBytes("UTF-8"));
            outputStream.close();

            connection.connect();
            status = connection.getResponseCode();
        } catch (ProtocolException e) {
            e.printStackTrace();
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {

            Log.i("HTTP Client", "HTTP status code : " + status);
        }

        InputStream inputStream = null;
        try {
            inputStream = connection.getInputStream();
        } catch (IOException e) {
            e.printStackTrace();
        }

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

Activity_main.xml

```<code><?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="#ffffff"
    android:orientation="vertical"
    android:padding="16dp">

    <Button
        android:id="@+id/open"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center_horizontal"
        android:background="@color/colorPrimaryDark"

        android:elevation="4dp"
        android:paddingLeft="70dp"
        android:paddingRight="70dp"
        android:text="Soap Call"
        android:textColor="#fff" />
</LinearLayout>
</code>```

below is my output:

02/28 14:33:49: Launching app
Cold swapped changes.
$ adb shell am start -n "mokhethea.vodacom.com.soap__03/myname.company.com.soap__03.MainActivity" -a android.intent.action.MAIN -c android.intent.category.LAUNCHER
Connected to process 30654 on device vodafone-vfd_500-TK8HFQ7PYHNNNBCE
I/InstantRun: Instant Run Runtime started. Android package is myname.company.com.soap__03, real application class is null.
E/MultiWindowProxy: getServiceInstance failed!
D/libc-netbsd: [getaddrinfo]: hostname="WSDL URL and Port"; servname=(null); netid=0; mark=0
D/libc-netbsd: [getaddrinfo]: ai_addrlen=0; ai_canonname=(null); ai_flags=4; ai_family=0
D/libc-netbsd: [getaddrinfo]: hostname="WSDL URL and Port"; servname=(null); netid=0; mark=0
D/libc-netbsd: [getaddrinfo]: ai_addrlen=0; ai_canonname=(null); ai_flags=4; ai_family=0
I/HTTP Client: HTTP status code : 0

sample code was extracted from: Владимир Лапенков article: How to call a SOAP web service on Android

anyone can tell where i am getting wrong/ rather provide a working example..?

答:
Glad you asked this question, i faced the same problem when i started out with soap webservice. The key here is to avoid using soap libraries and go for the classes that java has provided to make the request and parse it i.e http,DOM parser or SAX parser. This is how you make your request without using ksoap or any other libraries.

Now on to the androiod code :

We will create a class named runTask which extends async task and use http to send the request body and get request response :

```<code>private class runTask extends AsyncTask<String, String, String> {

            private String response;
            String string = "your string parameter"
            String SOAP_ACTION = "your soap action here";

            String stringUrl = "http://your_url_here";
            //if you experience a problem with url remove the '?wsdl' ending

            @Override
            protected String doInBackground(String... params) {

                try {

                            //paste your request structure here as the String body.

                    String body = "<soapenv:Envelope xmlns:soapenv=\"http://someurl\" "+
            "xmlns:soap=\"someurl\" "+
            "xmlns:gen=\"http://someurl\"> "+
    "<soapenv:Header> "+
    "<auth:EventID xmlns:auth='http://someurl'>3000</auth:EventID> "+
    "</soapenv:Header> "+
    "<soapenv:Body> "+
    "<gen:getGenericResult> "+
    "<Request> "+
    "<dataItem> "+
    "<name>Username</name> "+
    "<type>String</type> "+
    "<value>usernamehere</value> "+
    "</dataItem> "+
    "<dataItem> "+
    "<name>Password</name> "+
    "<type>String</type> "+
    "<value>passwordhere</value> "+
    "</dataItem> "+
    "</Request> "+
    "</gen:getGenericResult> "+
    "</soapenv:Body> "+
    "</soapenv:Envelope>";

                    try {
                        URL url = new URL(stringUrl);
                        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
                        conn.setRequestMethod("POST");
                        conn.setDoOutput(true);
                        conn.setDefaultUseCaches(false);
                        conn.setRequestProperty("Accept", "text/xml");
                        conn.setRequestProperty("SOAPAction", SOAP_ACTION);
                        //you can pass all your request parameters here usong .setRequestProperty() method

                        //push the request to the server address

                        OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());
                        wr.write(body);
                        wr.flush();

                        //get the server response

                        BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
                        StringBuilder builder = new StringBuilder();
                        String line = null;

                        while ((line = reader.readLine()) != null) {

                            builder.append(line);
                            response = builder.toString();//this is the response, parse it in onPostExecute

                        }

                    } catch (Exception e) {

                        e.printStackTrace();
                    } finally {

                        try {

                            reader.close();
                        } catch (Exception e) {

                            e.printStackTrace();
                        }
                    }

                } catch (Exception e) {

                    e.printStackTrace();
                }

                return response;
            }

            /**
             * @see AsyncTask#onPostExecute(Object)
             */
            @Override
            protected void onPostExecute(String result) {

               try {

                  Toast.makeText(this,"Response "+ result,Toast.LENGTH_LONG).show();

                  //Go ahead and parse the response now

                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
</code>```

Now in your onCreate just go ahead and execute this class using the following code

```<code>runTask task = new runTask();
task.execute();
</code>```

If the url and request body is correctly fed,you will get your response in your onPostExecute, format and parse it from here.
The main advantages of using this libraryless way is that it is flexible, you can format the request in any way the webservice requires as compared to the libraries which you only use the provided request formats. This solution works seamlessly in my code, feel free to ask for any further clarification.

Body:
i have this code running on android studio:

MainActivity.java

package myname.company.com.soap__03;

import android.net.Uri;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.ProtocolException;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;

public class MainActivity extends AppCompatActivity {

    private static HashMap<String, String> mHeaders = new HashMap<>();

    static {
        mHeaders.put("Accept-Encoding", "gzip,deflate");
        mHeaders.put("Content-Type", "application/soap+xml");
        mHeaders.put("Host", "server:port");
        mHeaders.put("Connection", "Keep-Alive");
        mHeaders.put("User-Agent", "AndroidApp");
        // mHeaders.put("Authorization", "Basic Q2xpZW50NTkzMzppMjR3s2U="); // optional
    }

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

        try {
            Button openButton = (Button) findViewById(R.id.open);

            openButton.setOnClickListener(new View.OnClickListener() {
                public void onClick(View v) {
                    try {
                        receiveCurrentShipments("WSDL URL");

                    } catch (Exception ex) {
                        ex.printStackTrace();
                    }
                }
            });
        }catch(Exception e) {
            e.printStackTrace();
        }
    }

    public final static InputStream receiveCurrentShipments(String stringUrlShipments) {
        int status = 0;
        String xmlstring = "<soapenv:Envelope xmlns:soapenv=\"http://someurl\" "+
                "xmlns:soap=\"someurl\" "+
                "xmlns:gen=\"http://someurl\"> "+
        "<soapenv:Header> "+
        "<auth:EventID xmlns:auth='http://someurl'>3000</auth:EventID> "+
        "</soapenv:Header> "+
        "<soapenv:Body> "+
        "<gen:getGenericResult> "+
        "<Request> "+
        "<dataItem> "+
        "<name>Username</name> "+
        "<type>String</type> "+
        "<value>usernamehere</value> "+
        "</dataItem> "+
        "<dataItem> "+
        "<name>Password</name> "+
        "<type>String</type> "+
        "<value>passwordhere</value> "+
        "</dataItem> "+
        "</Request> "+
        "</gen:getGenericResult> "+
        "</soapenv:Body> "+
        "</soapenv:Envelope>";

       // StringBuffer chaine = new StringBuffer("");

        HttpURLConnection connection = null;

        try {
            URL url = new URL(stringUrlShipments);
            connection = (HttpURLConnection) url.openConnection();
            connection.setRequestProperty("Content-Length", xmlstring.getBytes().length + "");
            connection.setRequestProperty("SOAPAction", "http://NAMESPACE\METHOD_NAME");

            for (Map.Entry<String, String> entry : mHeaders.entrySet()) {
                String key = entry.getKey();
                String value = entry.getValue();
                connection.setRequestProperty(key, value);

            }

            connection.setRequestMethod("POST");
            connection.setDoInput(true);

            OutputStream outputStream = connection.getOutputStream();
            outputStream.write(xmlstring.getBytes("UTF-8"));
            outputStream.close();

            connection.connect();
            status = connection.getResponseCode();
        } catch (ProtocolException e) {
            e.printStackTrace();
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {

            Log.i("HTTP Client", "HTTP status code : " + status);
        }

        InputStream inputStream = null;
        try {
            inputStream = connection.getInputStream();
        } catch (IOException e) {
            e.printStackTrace();
        }

        return inputStream;
    }
}

Activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="#ffffff"
    android:orientation="vertical"
    android:padding="16dp">

    <Button
        android:id="@+id/open"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center_horizontal"
        android:background="@color/colorPrimaryDark"

        android:elevation="4dp"
        android:paddingLeft="70dp"
        android:paddingRight="70dp"
        android:text="Soap Call"
        android:textColor="#fff" />
</LinearLayout>

below is my output:

02/28 14:33:49: Launching app
Cold swapped changes.
$ adb shell am start -n "mokhethea.vodacom.com.soap__03/myname.company.com.soap__03.MainActivity" -a android.intent.action.MAIN -c android.intent.category.LAUNCHER
Connected to process 30654 on device vodafone-vfd_500-TK8HFQ7PYHNNNBCE
I/InstantRun: Instant Run Runtime started. Android package is myname.company.com.soap__03, real application class is null.
E/MultiWindowProxy: getServiceInstance failed!
D/libc-netbsd: [getaddrinfo]: hostname="WSDL URL and Port"; servname=(null); netid=0; mark=0
D/libc-netbsd: [getaddrinfo]: ai_addrlen=0; ai_canonname=(null); ai_flags=4; ai_family=0
D/libc-netbsd: [getaddrinfo]: hostname="WSDL URL and Port"; servname=(null); netid=0; mark=0
D/libc-netbsd: [getaddrinfo]: ai_addrlen=0; ai_canonname=(null); ai_flags=4; ai_family=0
I/HTTP Client: HTTP status code : 0

sample code was extracted from: Владимир Лапенков article: How to call a SOAP web service on Android

anyone can tell where i am getting wrong/ rather provide a working example..?

Body:
Glad you asked this question, i faced the same problem when i started out with soap webservice. The key here is to avoid using soap libraries and go for the classes that java has provided to make the request and parse it i.e http,DOM parser or SAX parser. This is how you make your request without using ksoap or any other libraries.

Now on to the androiod code :

We will create a class named runTask which extends async task and use http to send the request body and get request response :

private class runTask extends AsyncTask<String, String, String> {

            private String response;
            String string = "your string parameter"
            String SOAP_ACTION = "your soap action here";

            String stringUrl = "http://your_url_here";
            //if you experience a problem with url remove the '?wsdl' ending

            @Override
            protected String doInBackground(String... params) {

                try {

                            //paste your request structure here as the String body.

                    String body = "<soapenv:Envelope xmlns:soapenv=\"http://someurl\" "+
            "xmlns:soap=\"someurl\" "+
            "xmlns:gen=\"http://someurl\"> "+
    "<soapenv:Header> "+
    "<auth:EventID xmlns:auth='http://someurl'>3000</auth:EventID> "+
    "</soapenv:Header> "+
    "<soapenv:Body> "+
    "<gen:getGenericResult> "+
    "<Request> "+
    "<dataItem> "+
    "<name>Username</name> "+
    "<type>String</type> "+
    "<value>usernamehere</value> "+
    "</dataItem> "+
    "<dataItem> "+
    "<name>Password</name> "+
    "<type>String</type> "+
    "<value>passwordhere</value> "+
    "</dataItem> "+
    "</Request> "+
    "</gen:getGenericResult> "+
    "</soapenv:Body> "+
    "</soapenv:Envelope>";

                    try {
                        URL url = new URL(stringUrl);
                        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
                        conn.setRequestMethod("POST");
                        conn.setDoOutput(true);
                        conn.setDefaultUseCaches(false);
                        conn.setRequestProperty("Accept", "text/xml");
                        conn.setRequestProperty("SOAPAction", SOAP_ACTION);
                        //you can pass all your request parameters here usong .setRequestProperty() method

                        //push the request to the server address

                        OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());
                        wr.write(body);
                        wr.flush();

                        //get the server response

                        BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
                        StringBuilder builder = new StringBuilder();
                        String line = null;

                        while ((line = reader.readLine()) != null) {

                            builder.append(line);
                            response = builder.toString();//this is the response, parse it in onPostExecute

                        }

                    } catch (Exception e) {

                        e.printStackTrace();
                    } finally {

                        try {

                            reader.close();
                        } catch (Exception e) {

                            e.printStackTrace();
                        }
                    }

                } catch (Exception e) {

                    e.printStackTrace();
                }

                return response;
            }

            /**
             * @see AsyncTask#onPostExecute(Object)
             */
            @Override
            protected void onPostExecute(String result) {

               try {

                  Toast.makeText(this,"Response "+ result,Toast.LENGTH_LONG).show();

                  //Go ahead and parse the response now

                } catch (Exception e) {
                    e.printStackTrace();
                }
            }

Now in your onCreate just go ahead and execute this class using the following code

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

If the url and request body is correctly fed,you will get your response in your onPostExecute, format and parse it from here.
The main advantages of using this libraryless way is that it is flexible, you can format the request in any way the webservice requires as compared to the libraries which you only use the provided request formats. This solution works seamlessly in my code, feel free to ask for any further clarification.


问:
RuntimeError: main thread is not in main loop; when I click the Exit button
I am building a simple GUI application to count time from a certain event. Anyway, everything works fine but when I click the Exit button, it starts to give me exceptions every second like this one:

```<code>Exception in thread Thread-10: Traceback (most recent call last):   File "/usr/lib/python3.5/threading.py", line 914, in _bootstrap_inner
    self.run()   File "/usr/lib/python3.5/threading.py", line 1180, in run
    self.function(*self.args, **self.kwargs)   File "/home/cali/PycharmProjects/str8/str8", line 83, in printit
    display()   File "/home/cali/PycharmProjects/str8/str8", line 23, in display
    font="Verdana 8 bold").grid(row=0, sticky=W)   File "/usr/lib/python3.5/tkinter/__init__.py", line 2609, in __init__
    Widget.__init__(self, master, 'label', cnf, kw)   File "/usr/lib/python3.5/tkinter/__init__.py", line 2142, in __init__
    (widgetName, self._w) + extra + self._options(cnf)) RuntimeError: main thread is not in main loop
</code>```

Here is what I have done:

```<code># str8.py
#   Program to count time from a certain event

from tkinter import *
from datetime import *
from threading import *

root = Tk()
root.title("STR8")
root.resizable(width=False, height=False)

def main():
    printit()

def exit():
    root.destroy()

def display():
    event, tday, str8, seconds, minutes, hours, days, weeks, years = calculate()

    thelabel = Label(root,
                         text="You have been STR8 for:\n",
                         font="Verdana 8 bold").grid(row=0, sticky=W)

    labelYears = Label(root,
                           text="Years: "
                                + str(round(years, 2)),
                           font="Verdana 8").grid(row=1, sticky=W)

    labelWeeks = Label(root,
                           text="Weeks: "
                                + str(round(weeks, 2)),
                           font="Verdana 8").grid(row=2, sticky=W)

    labelDays = Label(root,
                          text="Days: "
                               + str(round(days, 2)),
                          font="Verdana 8").grid(row=3, sticky=W)

    labelHours = Label(root,
                           text="Hours: "
                                + str(round(hours, 2)),
                           font="Verdana 8").grid(row=4, sticky=W)

    labelMinutes = Label(root,
                             text="Minutes: "
                                  + str(round(minutes, 2)),
                             font="Verdana 8").grid(row=5, sticky=W)

    labelSeconds = Label(root,
                             text="Seconds: "
                                  + str(round(str8.total_seconds())),
                             font="Verdana 8").grid(row=6, sticky=W)

    buttonRefresh = Button(root,
                               text="EXIT",
                               font="Verdana 8",
                               height=1,
                               width=19,
                               command=exit).grid(row=7)

def calculate():
    event = datetime(2017, 3, 29, 13, 45, 0)
    tday = datetime.now()

    str8 = tday - event

    seconds = str8.total_seconds()
    minutes = str8.total_seconds() / 60
    hours = minutes / 60
    days = hours / 24
    weeks = days / 7
    years = weeks / 52

    return event, tday, str8, seconds, minutes, hours, days, weeks, years

def printit():
  Timer(1.0, printit).start()
  calculate()
  display()

main()
root.mainloop()
</code>```

I'm using Python 3.6.

答:
The following program appears to resolve your problem. The call to display in print_it is wrapped in a try block. If it succeeds without an exception, the timer is started to be run later on.

```<code># str8.py
#   Program to count time from a certain event

from tkinter import *
from datetime import *
from threading import *

root = Tk()
root.title("STR8")
root.resizable(width=False, height=False)

def main():
    print_it()

def stop():
    root.destroy()

def display():
    event, today, str8, seconds, minutes, hours, days, weeks, years = calc()
    Label(root,
          text="You have been STR8 for:\n",
          font="Verdana 8 bold").grid(row=0, sticky=W)
    Label(root,
          text="Years: "
               + str(round(years, 2)),
          font="Verdana 8").grid(row=1, sticky=W)
    Label(root,
          text="Weeks: "
               + str(round(weeks, 2)),
          font="Verdana 8").grid(row=2, sticky=W)
    Label(root,
          text="Days: "
               + str(round(days, 2)),
          font="Verdana 8").grid(row=3, sticky=W)
    Label(root,
          text="Hours: "
               + str(round(hours, 2)),
          font="Verdana 8").grid(row=4, sticky=W)
    Label(root,
          text="Minutes: "
               + str(round(minutes, 2)),
          font="Verdana 8").grid(row=5, sticky=W)
    Label(root,
          text="Seconds: "
               + str(round(str8.total_seconds())),
          font="Verdana 8").grid(row=6, sticky=W)
    Button(root,
           text="EXIT",
           font="Verdana 8",
           height=1,
           width=19,
           command=stop).grid(row=7)

def calc():
    event = datetime(2017, 3, 29, 13, 45, 0)
    today = datetime.now()

    str8 = today - event

    seconds = str8.total_seconds()
    minutes = str8.total_seconds() / 60
    hours = minutes / 60
    days = hours / 24
    weeks = days / 7
    years = weeks / 52

    return event, today, str8, seconds, minutes, hours, days, weeks, years

def print_it():
    t = Timer(1.0, print_it)
    calc()
    try:
        display()
    except RuntimeError:
        pass
    else:
        t.start()

main()
root.mainloop()
</code>```

Body:
I am building a simple GUI application to count time from a certain event. Anyway, everything works fine but when I click the Exit button, it starts to give me exceptions every second like this one:

Exception in thread Thread-10: Traceback (most recent call last):   File "/usr/lib/python3.5/threading.py", line 914, in _bootstrap_inner
    self.run()   File "/usr/lib/python3.5/threading.py", line 1180, in run
    self.function(*self.args, **self.kwargs)   File "/home/cali/PycharmProjects/str8/str8", line 83, in printit
    display()   File "/home/cali/PycharmProjects/str8/str8", line 23, in display
    font="Verdana 8 bold").grid(row=0, sticky=W)   File "/usr/lib/python3.5/tkinter/__init__.py", line 2609, in __init__
    Widget.__init__(self, master, 'label', cnf, kw)   File "/usr/lib/python3.5/tkinter/__init__.py", line 2142, in __init__
    (widgetName, self._w) + extra + self._options(cnf)) RuntimeError: main thread is not in main loop

Here is what I have done:

# str8.py
#   Program to count time from a certain event

from tkinter import *
from datetime import *
from threading import *

root = Tk()
root.title("STR8")
root.resizable(width=False, height=False)

def main():
    printit()

def exit():
    root.destroy()

def display():
    event, tday, str8, seconds, minutes, hours, days, weeks, years = calculate()

    thelabel = Label(root,
                         text="You have been STR8 for:\n",
                         font="Verdana 8 bold").grid(row=0, sticky=W)

    labelYears = Label(root,
                           text="Years: "
                                + str(round(years, 2)),
                           font="Verdana 8").grid(row=1, sticky=W)

    labelWeeks = Label(root,
                           text="Weeks: "
                                + str(round(weeks, 2)),
                           font="Verdana 8").grid(row=2, sticky=W)

    labelDays = Label(root,
                          text="Days: "
                               + str(round(days, 2)),
                          font="Verdana 8").grid(row=3, sticky=W)

    labelHours = Label(root,
                           text="Hours: "
                                + str(round(hours, 2)),
                           font="Verdana 8").grid(row=4, sticky=W)

    labelMinutes = Label(root,
                             text="Minutes: "
                                  + str(round(minutes, 2)),
                             font="Verdana 8").grid(row=5, sticky=W)

    labelSeconds = Label(root,
                             text="Seconds: "
                                  + str(round(str8.total_seconds())),
                             font="Verdana 8").grid(row=6, sticky=W)

    buttonRefresh = Button(root,
                               text="EXIT",
                               font="Verdana 8",
                               height=1,
                               width=19,
                               command=exit).grid(row=7)

def calculate():
    event = datetime(2017, 3, 29, 13, 45, 0)
    tday = datetime.now()

    str8 = tday - event

    seconds = str8.total_seconds()
    minutes = str8.total_seconds() / 60
    hours = minutes / 60
    days = hours / 24
    weeks = days / 7
    years = weeks / 52

    return event, tday, str8, seconds, minutes, hours, days, weeks, years

def printit():
  Timer(1.0, printit).start()
  calculate()
  display()

main()
root.mainloop()

I'm using Python 3.6.

Body:
The following program appears to resolve your problem. The call to display in print_it is wrapped in a try block. If it succeeds without an exception, the timer is started to be run later on.

# str8.py
#   Program to count time from a certain event

from tkinter import *
from datetime import *
from threading import *

root = Tk()
root.title("STR8")
root.resizable(width=False, height=False)

def main():
    print_it()

def stop():
    root.destroy()

def display():
    event, today, str8, seconds, minutes, hours, days, weeks, years = calc()
    Label(root,
          text="You have been STR8 for:\n",
          font="Verdana 8 bold").grid(row=0, sticky=W)
    Label(root,
          text="Years: "
               + str(round(years, 2)),
          font="Verdana 8").grid(row=1, sticky=W)
    Label(root,
          text="Weeks: "
               + str(round(weeks, 2)),
          font="Verdana 8").grid(row=2, sticky=W)
    Label(root,
          text="Days: "
               + str(round(days, 2)),
          font="Verdana 8").grid(row=3, sticky=W)
    Label(root,
          text="Hours: "
               + str(round(hours, 2)),
          font="Verdana 8").grid(row=4, sticky=W)
    Label(root,
          text="Minutes: "
               + str(round(minutes, 2)),
          font="Verdana 8").grid(row=5, sticky=W)
    Label(root,
          text="Seconds: "
               + str(round(str8.total_seconds())),
          font="Verdana 8").grid(row=6, sticky=W)
    Button(root,
           text="EXIT",
           font="Verdana 8",
           height=1,
           width=19,
           command=stop).grid(row=7)

def calc():
    event = datetime(2017, 3, 29, 13, 45, 0)
    today = datetime.now()

    str8 = today - event

    seconds = str8.total_seconds()
    minutes = str8.total_seconds() / 60
    hours = minutes / 60
    days = hours / 24
    weeks = days / 7
    years = weeks / 52

    return event, today, str8, seconds, minutes, hours, days, weeks, years

def print_it():
    t = Timer(1.0, print_it)
    calc()
    try:
        display()
    except RuntimeError:
        pass
    else:
        t.start()

main()
root.mainloop()


问:
How to make accurate timer on Android?
I have tried Handler, got no accuracy at all,

CountDownTimer, accurate most of time and

TimerTask, always accurate but on first call.

Scenario:

I'm trying to stop sound playing after specific amount of time.

Calling code

```<code>TimeTask task = new TimeTask();
Timer timer = new Timer();
task.setMediaPlayer(mediaPlayer);
timer.schedule(task, 400);
mediaPlayer.start();
</code>```

I have created MediaPlayer that I'm giving to class that extends TimerTask. It will release MediaPlayer after specific amount of time.

class that extends TimerTask

```<code>private MediaPlayer mMediaPlayer = new MediaPlayer();

public void setMediaPlayer(MediaPlayer mediaPlayer) {
    this.mMediaPlayer = mediaPlayer;
    mMediaPlayer.start();
}

@Override
public void run() {
ListIterator<MediaPlayer> iterator = SoundboardMenu.mMediaPlayerList.listIterator();

        while (iterator.hasNext()) {
            MediaPlayer iteratedPlayer = iterator.next();
            if (iteratedPlayer.equals(mMediaPlayer)) {
                iteratedPlayer.release();
                iterator.remove();
                break;
            }
        }
}
</code>```

It works fine but it's not always accurate enough.

If we wait over 5 seconds after calling class that extends TimerTask and call it again, then there will be slightly more delay and sound plays longer. If we call it repeatedly then we always get slightly shorter delay.

答:
Handler is quite accurate, though it is dependent on the thread it is associated with actually running its message loop.  If you are doing the Handler on your main thread, and your main thread goes out to lunch for 200ms...  well, then of course the Handler can't fire during that time.

Of course, you don't say what you actually mean by "accurate" so it is hard to determine what you are expecting.

ContentLicense: CC BY-SA 2.5

Title: How to make accurate timer on Android?

Body:
I have tried Handler, got no accuracy at all,

CountDownTimer, accurate most of time and

TimerTask, always accurate but on first call.

Scenario:

I'm trying to stop sound playing after specific amount of time.

Calling code

TimeTask task = new TimeTask();
Timer timer = new Timer();
task.setMediaPlayer(mediaPlayer);
timer.schedule(task, 400);
mediaPlayer.start();

I have created MediaPlayer that I'm giving to class that extends TimerTask. It will release MediaPlayer after specific amount of time.

class that extends TimerTask

private MediaPlayer mMediaPlayer = new MediaPlayer();

public void setMediaPlayer(MediaPlayer mediaPlayer) {
    this.mMediaPlayer = mediaPlayer;
    mMediaPlayer.start();
}

@Override
public void run() {
ListIterator<MediaPlayer> iterator = SoundboardMenu.mMediaPlayerList.listIterator();

        while (iterator.hasNext()) {
            MediaPlayer iteratedPlayer = iterator.next();
            if (iteratedPlayer.equals(mMediaPlayer)) {
                iteratedPlayer.release();
                iterator.remove();
                break;
            }
        }
}

It works fine but it's not always accurate enough.

If we wait over 5 seconds after calling class that extends TimerTask and call it again, then there will be slightly more delay and sound plays longer. If we call it repeatedly then we always get slightly shorter delay.


问:
Change font encoding in itextsharp
My main purpose is displaying chinese font in a pdf.

The code i have to modify is

```<code>BackgroundColor = FontHelper.GetPdfColor(0, 0, 255),
FontColor = FontHelper.GetPdfColor(0, 255, 0),
FontStyle = FontStyle.NORMAL,
FontEncoding = FontEncodings.CP1252,
FontName = FontNames.TIMES_ROMAN
</code>```

It seems that the issue is from FontEncodings.CP1252 or/and FontNames.TIMES_ROMAN, and i read all related post i think, but i can't find a simple solution.

I don't know enough the code i'm working on, so i would like to modify it the less possible.
I saw some solution with some FontSelector or something else and it's really different from what i have in my code, and hos to integrate it into my code.
Pretty much solution are also old, and potentially not up to date.

So, does exist a simple way to modify the font ?

答:
Finally one of the simpliest way i found is

```<code>string ARIALUNI_TFF = @".\SimSun.ttf"  ;
bf=BaseFont.CreateFont(ARIALUNI_TFF,BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);
</code>```

A little adaptation of the joris answer.

Title: Change font encoding in itextsharp

Body:
My main purpose is displaying chinese font in a pdf.

The code i have to modify is

BackgroundColor = FontHelper.GetPdfColor(0, 0, 255),
FontColor = FontHelper.GetPdfColor(0, 255, 0),
FontStyle = FontStyle.NORMAL,
FontEncoding = FontEncodings.CP1252,
FontName = FontNames.TIMES_ROMAN

It seems that the issue is from FontEncodings.CP1252 or/and FontNames.TIMES_ROMAN, and i read all related post i think, but i can't find a simple solution.

I don't know enough the code i'm working on, so i would like to modify it the less possible.
I saw some solution with some FontSelector or something else and it's really different from what i have in my code, and hos to integrate it into my code.
Pretty much solution are also old, and potentially not up to date.

So, does exist a simple way to modify the font ?

Body:
Finally one of the simpliest way i found is

string ARIALUNI_TFF = @".\SimSun.ttf"  ;
bf=BaseFont.CreateFont(ARIALUNI_TFF,BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);

A little adaptation of the joris answer.


问:
Using a table to parametrize column/table names in PDO
It is not possible to use parameters to describe column or table names in PDO.

For instance:

```<code>CREATE TABLE ? (id INT(6) PRIMARY KEY AUTO_INCREMENT, ...)
</code>```

How about using a temporary table to handle malicious data and then feeding it back into the statement ?

```<code>$hex = bin2hex(random_bytes(8));
$stmt = $db->prepare('INSERT INTO tmpdata (value,hex) VALUES (:val,:hex)');
$stmt->execute(array(
  ":val" => $_POST['catname'],
  ":hex" => $hex
));
$stmt = $db->prepare('SELECT value FROM tmpdata WHERE hex=?');
$stmt->execute(array($hex));
$row = $stmt->fetchAll(PDO::FETCH_ASSOC);
$cleaned_value = $row[0]['value'];
</code>```

Is this an acceptable and more importantly safe way to feed parameters into PDO for column and table names ?

答:
Not a slightest.

If you take a flask with poison and drink it you'll die.

What makes you think that storing it in a cupboard before drinking will make it harmless?

Aiming your question more directly, you should never ever create a table based on user input. Not because of whatever dangers but because of sanity. Your database design should be solid and static, made once for all and altered only on occasion, by admin only.

So your foremost concern for now is to learn the database design basics.

Body:
It is not possible to use parameters to describe column or table names in PDO.

For instance:

CREATE TABLE ? (id INT(6) PRIMARY KEY AUTO_INCREMENT, ...)

How about using a temporary table to handle malicious data and then feeding it back into the statement ?

$hex = bin2hex(random_bytes(8));
$stmt = $db->prepare('INSERT INTO tmpdata (value,hex) VALUES (:val,:hex)');
$stmt->execute(array(
  ":val" => $_POST['catname'],
  ":hex" => $hex
));
$stmt = $db->prepare('SELECT value FROM tmpdata WHERE hex=?');
$stmt->execute(array($hex));
$row = $stmt->fetchAll(PDO::FETCH_ASSOC);
$cleaned_value = $row[0]['value'];

Is this an acceptable and more importantly safe way to feed parameters into PDO for column and table names ?


问:
How can I disable error logging in console for a Dojo's JsonRest query?
My project uses a JsonRest store to access it's data. It'l all working fine. The problem is that when the server returns an error, even if the correct part of the code is called, and the functionality works as it should, the object logs an ugly error to the console.

My code:

```<code>function loadData() {
    self.storeItem.query({
        'id_metric' : self.selectMetrics.value,
        'id_client' : self.selectClients.value
    }).then(
        (res) => populateResults(res),
        ()=>{
            // this is called correctly...
            query('.res').forEach(domConstruct.destroy);
            domConstruct.place('<tr class="sem res"><td>No results</td></tr>', "tableLines", 'first');
        }
    );
}
</code>```

.

```<code>// ..but this is logged in console:
Object { message: "Unable to load http://localhost:300…", stack: ".cache["dojo/errors/create"]/</</_3…", response: Object, status: 404, responseText: "{"errors":["Not found…",
xhr: XMLHttpRequest }
</code>```

How can I make the store not show the error ?

I know I could change server behavior to return a code 200 result instead of 404. But what I want is just to make it not send the error to the console.

答:
The error is logged by dojo/_base/xhr, which is used internally by dojo/store/JsonRest. I don't see a clean way to suppress it, unless you are prepared to implement your own store. If you are this is what you can do:

dojo/_base/xhr has a failOk argument that does exactly what you want but dojo/store/JsonRest doesn't use it and the default is false (log the error to the console). So you can copy the source of JsonRest and add failOk: true in all xhr calls. For example in the query function:

```<code>    var results = xhr("GET", {
        url: this.target + (query || ""),
        handleAs: "json",
        headers: headers,
        failOk: true
    });
</code>```

You will still be able to handle the error in your error handler function.

Body:
My project uses a JsonRest store to access it's data. It'l all working fine. The problem is that when the server returns an error, even if the correct part of the code is called, and the functionality works as it should, the object logs an ugly error to the console.

My code:

function loadData() {
    self.storeItem.query({
        'id_metric' : self.selectMetrics.value,
        'id_client' : self.selectClients.value
    }).then(
        (res) => populateResults(res),
        ()=>{
            // this is called correctly...
            query('.res').forEach(domConstruct.destroy);
            domConstruct.place('
No results
', "tableLines", 'first');
        }
    );
}

.

// ..but this is logged in console:
Object { message: "Unable to load http://localhost:300…", stack: ".cache["dojo/errors/create"]/</</_3…", response: Object, status: 404, responseText: "{"errors":["Not found…",
xhr: XMLHttpRequest }

How can I make the store not show the error ?

I know I could change server behavior to return a code 200 result instead of 404. But what I want is just to make it not send the error to the console.

Body:
The error is logged by dojo/_base/xhr, which is used internally by dojo/store/JsonRest. I don't see a clean way to suppress it, unless you are prepared to implement your own store. If you are this is what you can do:

dojo/_base/xhr has a failOk argument that does exactly what you want but dojo/store/JsonRest doesn't use it and the default is false (log the error to the console). So you can copy the source of JsonRest and add failOk: true in all xhr calls. For example in the query function:

    var results = xhr("GET", {
        url: this.target + (query || ""),
        handleAs: "json",
        headers: headers,
        failOk: true
    });

You will still be able to handle the error in your error handler function.


问:
Autohotkey - Different commands when different programs are active
I am trying to write a script that when clicking "SHIFT+ALT+I" it sends a particular command when Microsft Word is active and another command if Microsoft PowerPoint is Active (both programs are running at the same time).

The code should be something like:

```<code>"if Microsoft Word is open"
+!i::
MouseMove, 300,50,0
MouseClick, left

"if Microsoft Powerpoint is open"
+!i::
MouseMove, 600,100,0
MouseClick, left
</code>```

Is there any (easy) way of doing that?

答:
This is the correct way of defining application-specific hotkeys

Define F1 macros conditional on active window:

```<code>SetTitleMatchMode 2     ; All #If statements match anywhere in title

#IfWinActive Microsoft Word
  F1:: MsgBox F1 pressed in Word
#IfWinActive Notepad
  F1:: MsgBox F1 pressed in Notepad
#IfWinActive
  F1:: MsgBox F1 pressed elsewhere
</code>```

Body:
I am trying to write a script that when clicking "SHIFT+ALT+I" it sends a particular command when Microsft Word is active and another command if Microsoft PowerPoint is Active (both programs are running at the same time).

The code should be something like:

"if Microsoft Word is open"
+!i::
MouseMove, 300,50,0
MouseClick, left

"if Microsoft Powerpoint is open"
+!i::
MouseMove, 600,100,0
MouseClick, left

Is there any (easy) way of doing that?

Body:
This is the correct way of defining application-specific hotkeys

Define F1 macros conditional on active window:

SetTitleMatchMode 2     ; All #If statements match anywhere in title

#IfWinActive Microsoft Word
  F1:: MsgBox F1 pressed in Word
#IfWinActive Notepad
  F1:: MsgBox F1 pressed in Notepad
#IfWinActive
  F1:: MsgBox F1 pressed elsewhere


问:
Is it possible to gzip file on server-side and ungzip it in the browser transparently?
My web application sends JSON files to client. These files can be relatively big.

Can I compress them on server-side and receive uncompressed on client side transparently?

For example, if I write

```<code>$.getJSON( "ajax/test.json", function( data ) {
...
});
</code>```

can I just have ajax/test.json gzipped and set content-encoding to gzip?

答:
You have not specified any information about your server-side setup.

If you are generating the json on the fly, then you should check if the request send by the browser contains Accept-Encoding: gzip header.
If yes, then add header Content-Encoding: gzip to the response and just sent gzip compressed data.

If the json files are static you should configure application/json mime type as compressible in your webserver configuration, or better yet, precompress it,  store both file.json and file.json.gz on your webserver and then configure conditional rewrite and headers, so the compressed file is served only to clients that supports compression.
 Search/Ask ServerFault how to do this on your webserver.

Body:
My web application sends JSON files to client. These files can be relatively big.

Can I compress them on server-side and receive uncompressed on client side transparently?

For example, if I write

$.getJSON( "ajax/test.json", function( data ) {
...
});

can I just have ajax/test.json gzipped and set content-encoding to gzip?


问:
mysql query - accessing field without affecting output
I have 2 tables in mysql: tableA and tableB

```<code>tableA: idA
tableB: idB, name
</code>```

Now i want to fire following query:

```<code>SELECT * FROM tableA WHERE idA in (1, 2, 3, 4);
</code>```

idA and idB are exactly same. I want to access "name" field of tableB in the above query.

How do i do this???

Thanks alot for help
Regards

答:
Thanks alot for help...

I just forgot the basic thing (thanks @yc you reminded me):

SELECT idA, name FROM tableA, tableB WHERE idA in (1, 2, 3, 4) and idA = idB;

Regards

Body:
I have 2 tables in mysql: tableA and tableB

tableA: idA
tableB: idB, name

Now i want to fire following query:

SELECT * FROM tableA WHERE idA in (1, 2, 3, 4);

idA and idB are exactly same. I want to access "name" field of tableB in the above query.

How do i do this???

Thanks alot for help
Regards


问:
MutationObserver in AngularJS to know when a SPA template has been loaded
I'm using MutationObserver in an AngularJS SPA to detect changes in the DOM everytime the ng-view is updated via user navigation. This is better explained here http://www.soasta.com/blog/angularjs-real-user-monitoring-single-page-applications/

This is the function which is fired with every soft navigation (within the SPA)

```<code>function initMutationObserver() {

    if (window.MutationObserver) {

        // select the target node
        var target = document.querySelector('.sport');

        // create an observer instance
        var observer = new MutationObserver(function(mutations) {
            mutations.forEach(function(mutation) {
                console.info(mutation.type);
            });
            console.info('**** DOM changes ****')
        });

        // configuration of the observer:
        var config = { attributes: true, childList: true, characterData: true, subtree: true};

        // pass in the target node, as well as the observer options
        observer.observe(target, config);
    }
};
</code>```

That is, everytime the user navigates to a new page within the SPA this observer detects changes in the DOM.

Problem is, for every navigation this observer gets fired many times and not only one, so I don´t really know when this is over. Has anyone any idea on how to do that? Is there a way with the MutationObserver that I can be sure the DOM has alredy finish updating and I can call the loading over?

Many thanks!

答:
Once your mutation has occurred, you should destroy the observer:

```<code>observer.disconnect();
</code>```

You may have your NodeList complete or something else...

Imagine it as a camera that is waiting to see when all those DOM events happen. (You may not need all of them, by the way).

But it is important to cease its activity.

Body:
I'm using MutationObserver in an AngularJS SPA to detect changes in the DOM everytime the ng-view is updated via user navigation. This is better explained here http://www.soasta.com/blog/angularjs-real-user-monitoring-single-page-applications/

This is the function which is fired with every soft navigation (within the SPA)

function initMutationObserver() {

    if (window.MutationObserver) {

        // select the target node
        var target = document.querySelector('.sport');

        // create an observer instance
        var observer = new MutationObserver(function(mutations) {
            mutations.forEach(function(mutation) {
                console.info(mutation.type);
            });
            console.info('**** DOM changes ****')
        });

        // configuration of the observer:
        var config = { attributes: true, childList: true, characterData: true, subtree: true};

        // pass in the target node, as well as the observer options
        observer.observe(target, config);
    }
};

That is, everytime the user navigates to a new page within the SPA this observer detects changes in the DOM.

Problem is, for every navigation this observer gets fired many times and not only one, so I don´t really know when this is over. Has anyone any idea on how to do that? Is there a way with the MutationObserver that I can be sure the DOM has alredy finish updating and I can call the loading over?

Many thanks!

Body:
Once your mutation has occurred, you should destroy the observer:

observer.disconnect();

You may have your NodeList complete or something else...

Imagine it as a camera that is waiting to see when all those DOM events happen. (You may not need all of them, by the way).

But it is important to cease its activity.


问:
How to get a new access token in exchange of refresh token (when the old access token expires) in Youtube Data API?
I am writing a python script to upload videos on youtube using the sample script provided by youtube itself. But I am having this one problem. When my access token is expired, what should I do with the refresh token in order to exchange it for access token (remember I am writing a python script) or how should I exchange refresh token for an access token?</p>

答:
As explained in Refreshing an access token, your application can send a POST request to Google's authorization server that specifies your client ID, your client secret, and the refresh token for the user. The request should also set the grant_type parameter value to refresh_token.

You may want to check this SO post or this thread to know how to implement it using Python.


问:
Defining builders in multiple plugins
Is it possible to add two builders to two different plugins?

My scenario is this. I had a plugin-A that defines nature-A and builder-1 and builder-2, when I created project with this nature, project would get these builders.

Later I introduced another plugin-B that defines nature-B and the same builder-1 and builder-2 as plugin-A. Now when I create project defined by plugin-B, I don't see builder-1 and builder-2 added in .project file. If I remove builders definitions from plugin-A, then project created with plugin-B gets the builders, but not project created with plugin-A.

What is the designer pattern on builder reuse between two plugins?

答:
It is probably best to define another nature and put the builders in that nature.

The other two natures can use the requires-nature element to specify that they require the nature with the builders.

Title: Defining builders in multiple plugins


问:
Error, invalid number Jasperstudio and Oracle 12c
In the following SQL:

```<code>select cast(parvalor as float) valor from parametros where parid = 26
</code>```

I want to get the data in decimal, use TO_NUMBER and CAST (XX AS FLOAT) but it does not work.

This query runs in ORACLE 12c and works normal, but when I execute it in JasperStudio 6.3, I get

error ORA-01722: invalid number.

I really have no idea where the error is, please help.

答: Ok, changing data decimal "," to ".", jasper recognized query, but in oracle no is functional, what is the problem?</p>

Body:
In the following SQL:

select cast(parvalor as float) valor from parametros where parid = 26

I want to get the data in decimal, use TO_NUMBER and CAST (XX AS FLOAT) but it does not work.

This query runs in ORACLE 12c and works normal, but when I execute it in JasperStudio 6.3, I get

error ORA-01722: invalid number.

I really have no idea where the error is, please help.


问:
Autotest, RSpec 2 and Ruby 1.9.2-p0 - no output at all
I have started the book Continuous Testing with Ruby (B2.0 printing), but am running into immediate problems. Per the first chapter, I have created an empty Gem using Jeweler 1.5.1

```$ jeweler --rspec twits```

Running the specs manually with rake gives the correct failing output

```
$ rake spec
(in /Users/mfurtak/Documents/Programming/Ruby/twits)
/Users/mfurtak/.rvm/rubies/ruby-1.9.2-p0/bin/ruby -S bundle exec rspec "spec/twits_spec.rb"
F

Failures:
  1) Twits fails
     Failure/Error: fail "Trying to get this working"
     Trying to get this working
     # ./spec/twits_spec.rb:5:in `block (2 levels) in '

Finished in 0.00176 seconds
1 example, 1 failure
rake aborted!
```

To get Autotest configured for RSpec 2, I have created ./autotest/discover.rb in the root of my project as described in the book and elsewhere with the following contents:

```<code>Autotest.add_discovery { "rspec2" }
</code>```

But when I attempt to run the RSpec (2.2.0) specs through autotest (ZenTest 4.4.0), I get no output at all.

```$ autotest```

This is all using Ruby 1.9.2-p0 through RVM (1.0.2). If I switch to Ruby 1.8.7-p302, things work as expected.

```
$ autotest
loading autotest/rspec2
bundle exec /Users/mfurtak/.rvm/rubies/ruby-1.8.7-p302/bin/ruby -S /Users/mfurtak/.rvm/gems/ruby-1.8.7-p302/gems/rspec-core-2.2.1/bin/rspec --tty '/Users/mfurtak/Documents/Programming/Ruby/twits/spec/twits_spec.rb'
F

Failures:

  1) Twits fails
     Failure/Error: fail "Trying to get this working"
     Trying to get this working
     # ./spec/twits_spec.rb:5

Finished in 0.00036 seconds
1 example, 1 failure
```

答:
Noting the italic emphasis on autotest on this wiki page, I uninstalled the ZenTest (4.4.0) gem and instead installed the autotest (4.4.5) gem. After that and a

```<code>$ bundle install
</code>```

things are working correctly in both Ruby 1.9.2-p0 and Ruby 1.8.7-p302

```
$ autotest
loading autotest/rspec2
style: Rspec2
bundle exec /Users/mfurtak/.rvm/rubies/ruby-1.9.2-p0/bin/ruby -S /Users/mfurtak/.rvm/gems/ruby-1.9.2-p0/gems/rspec-core-2.2.1/bin/rspec --tty '/Users/mfurtak/Documents/Programming/Ruby/twits/spec/twits_spec.rb'
F

Failures:

  1) Twits fails
     Failure/Error: fail "Trying to get this working"
     Trying to get this working
     # ./spec/twits_spec.rb:5:in `block (2 levels) in '

Finished in 0.00036 seconds
1 example, 1 failure
```

Body:
I have started the book Continuous Testing with Ruby (B2.0 printing), but am running into immediate problems. Per the first chapter, I have created an empty Gem using Jeweler 1.5.1

$ jeweler --rspec twits

Running the specs manually with rake gives the correct failing output

$ rake spec
(in /Users/mfurtak/Documents/Programming/Ruby/twits)
/Users/mfurtak/.rvm/rubies/ruby-1.9.2-p0/bin/ruby -S bundle exec rspec "spec/twits_spec.rb"
F

Failures:
  1) Twits fails
     Failure/Error: fail "Trying to get this working"
     Trying to get this working
     # ./spec/twits_spec.rb:5:in `block (2 levels) in '

Finished in 0.00176 seconds
1 example, 1 failure
rake aborted!

To get Autotest configured for RSpec 2, I have created ./autotest/discover.rb in the root of my project as described in the book and elsewhere with the following contents:

Autotest.add_discovery { "rspec2" }

But when I attempt to run the RSpec (2.2.0) specs through autotest (ZenTest 4.4.0), I get no output at all.

$ autotest

This is all using Ruby 1.9.2-p0 through RVM (1.0.2). If I switch to Ruby 1.8.7-p302, things work as expected.

$ autotest
loading autotest/rspec2
bundle exec /Users/mfurtak/.rvm/rubies/ruby-1.8.7-p302/bin/ruby -S /Users/mfurtak/.rvm/gems/ruby-1.8.7-p302/gems/rspec-core-2.2.1/bin/rspec --tty '/Users/mfurtak/Documents/Programming/Ruby/twits/spec/twits_spec.rb'
F

Failures:

  1) Twits fails
     Failure/Error: fail "Trying to get this working"
     Trying to get this working
     # ./spec/twits_spec.rb:5

Finished in 0.00036 seconds
1 example, 1 failure

Body:
Noting the italic emphasis on autotest on this wiki page, I uninstalled the ZenTest (4.4.0) gem and instead installed the autotest (4.4.5) gem. After that and a

$ bundle install

things are working correctly in both Ruby 1.9.2-p0 and Ruby 1.8.7-p302

$ autotest
loading autotest/rspec2
style: Rspec2
bundle exec /Users/mfurtak/.rvm/rubies/ruby-1.9.2-p0/bin/ruby -S /Users/mfurtak/.rvm/gems/ruby-1.9.2-p0/gems/rspec-core-2.2.1/bin/rspec --tty '/Users/mfurtak/Documents/Programming/Ruby/twits/spec/twits_spec.rb'
F

Failures:

  1) Twits fails
     Failure/Error: fail "Trying to get this working"
     Trying to get this working
     # ./spec/twits_spec.rb:5:in `block (2 levels) in '

Finished in 0.00036 seconds
1 example, 1 failure


问:
byte[] to file in Java
With Java:

I have a byte[] that represents a file.

How do I write this to a file (ie. C:\myfile.pdf)

I know it's done with InputStream, but I can't seem to work it out.

答:
//////////////////////////  1] File to Byte [] ///////////////////

```<code>Path path = Paths.get(p);
                    byte[] data = null;
                    try {
                        data = Files.readAllBytes(path);
                    } catch (IOException ex) {
                        Logger.getLogger(Agent1.class.getName()).log(Level.SEVERE, null, ex);
                    }
</code>```

///////////////////////   2] Byte [] to File ///////////////////////////

```<code> File f = new File(fileName);
 byte[] fileContent = msg.getByteSequenceContent();
Path path = Paths.get(f.getAbsolutePath());
                            try {
                                Files.write(path, fileContent);
                            } catch (IOException ex) {
                                Logger.getLogger(Agent2.class.getName()).log(Level.SEVERE, null, ex);
                            }
</code>```

Title: byte[] to file in Java

Body:
//////////////////////////  1] File to Byte [] ///////////////////

Path path = Paths.get(p);
                    byte[] data = null;
                    try {
                        data = Files.readAllBytes(path);
                    } catch (IOException ex) {
                        Logger.getLogger(Agent1.class.getName()).log(Level.SEVERE, null, ex);
                    }

///////////////////////   2] Byte [] to File ///////////////////////////

 File f = new File(fileName);
 byte[] fileContent = msg.getByteSequenceContent();
Path path = Paths.get(f.getAbsolutePath());
                            try {
                                Files.write(path, fileContent);
                            } catch (IOException ex) {
                                Logger.getLogger(Agent2.class.getName()).log(Level.SEVERE, null, ex);
                            }


问:
InvalidArgsError in PyLucene trying to create FSDirectory
So I am trying to implement a basic index writer in PyLucene. I am usually a java dev but due to technical constraints I am doing this in python or else this wouldn't be a problem. I am following the sample in the PyLucene Tarball but

```<code>import lucene

from java.io import File
from org.apache.lucene.analysis.standard import StandardAnalyzer
from org.apache.lucene.document import Document, Field
from org.apache.lucene.index import IndexWriter, IndexWriterConfig
from org.apache.lucene.store import SimpleFSDirectory
from org.apache.lucene.util import Version
from org.apache.lucene.store import IOContext

lucene.initVM()
fl = File('index')
indexDir = SimpleFSDirectory(fl)
writerConfig = IndexWriterConfig(Version.LUCENE_6_4_1, StandardAnalyzer())
</code>```

The problem I am having is that whenever I run this I get the following error:

```<code>Traceback (most recent call last):
 File "Indexer.py", line 40, in <module>
indexer = Indexer()
 File "Indexer.py", line 22, in __init__
indexDir = SimpleFSDirectory(fl)
lucene.InvalidArgsError: (<type 'SimpleFSDirectory'>, '__init__', (<File: index>,))
</code>```

I have checked the Java code here and it appears there is a constructor public SimpleFSDirectory(File path) and it looks like that's what I am passing in even in the traceback error. Am I missing something out of jcc?

This is using Lucene 6.4.1 and I can import lucene and jcc successfully.

答:
So some of the documentation has this

```<code>fl = File('index')
indexDir = SimpleFSDirectory(fl)
</code>```

In newer versions (I am using PyLucene based on Lucene 6.4.1) SimpleFSDirectory expects a Path Instead of a File (Such are the joys of using a java library in python: the brevity of java with the type safety of python.) In the above I also didn't realize I had to attachCurrentThread

Corrected code:

```<code>path = Paths.get('index')
self.index_directory = SimpleFSDirectory(path)
</code>```

Body:
So I am trying to implement a basic index writer in PyLucene. I am usually a java dev but due to technical constraints I am doing this in python or else this wouldn't be a problem. I am following the sample in the PyLucene Tarball but

import lucene

from java.io import File
from org.apache.lucene.analysis.standard import StandardAnalyzer
from org.apache.lucene.document import Document, Field
from org.apache.lucene.index import IndexWriter, IndexWriterConfig
from org.apache.lucene.store import SimpleFSDirectory
from org.apache.lucene.util import Version
from org.apache.lucene.store import IOContext

lucene.initVM()
fl = File('index')
indexDir = SimpleFSDirectory(fl)
writerConfig = IndexWriterConfig(Version.LUCENE_6_4_1, StandardAnalyzer())

The problem I am having is that whenever I run this I get the following error:

Traceback (most recent call last):
 File "Indexer.py", line 40, in <module>
indexer = Indexer()
 File "Indexer.py", line 22, in __init__
indexDir = SimpleFSDirectory(fl)
lucene.InvalidArgsError: (<type 'SimpleFSDirectory'>, '__init__', (<File: index>,))

I have checked the Java code here and it appears there is a constructor public SimpleFSDirectory(File path) and it looks like that's what I am passing in even in the traceback error. Am I missing something out of jcc?

This is using Lucene 6.4.1 and I can import lucene and jcc successfully.

Body:
So some of the documentation has this

fl = File('index')
indexDir = SimpleFSDirectory(fl)

In newer versions (I am using PyLucene based on Lucene 6.4.1) SimpleFSDirectory expects a Path Instead of a File (Such are the joys of using a java library in python: the brevity of java with the type safety of python.) In the above I also didn't realize I had to attachCurrentThread

Corrected code:

path = Paths.get('index')
self.index_directory = SimpleFSDirectory(path)


问:
How to define a function which returns a map
I am attempting to define a function which returns an initialized map:

```<code>package main

import "fmt"
import "os"

func defaults() map {
  m := make(map[string]string)
  m["start"] = "1"
  m["from"]  = "encrypted"
  m["to"]    = "loaded"
  return m
}

func main() {
  args := os.Args[1:]
  fmt.Println(args)
  runvals := defaults()
  fmt.Println(runvals)
}
</code>```

Errors I'm getting:

```<code>Line 6 col 21 error| expected '[', found '{'
Line 7 col 5 error| expected ']', found ':='
Line 11 col 3 error| expected declaration, found 'return'
</code>```

Can someone help me get the syntax right? Or am I trying to do something that Go doesn't do?

答:
You need to declare the whole type including key and value types.</p>

```<code>func defaults() map[string]string {
    …
}
</code>```

Body:
I am attempting to define a function which returns an initialized map:

package main

import "fmt"
import "os"

func defaults() map {
  m := make(map[string]string)
  m["start"] = "1"
  m["from"]  = "encrypted"
  m["to"]    = "loaded"
  return m
}

func main() {
  args := os.Args[1:]
  fmt.Println(args)
  runvals := defaults()
  fmt.Println(runvals)
}

Errors I'm getting:

Line 6 col 21 error| expected '[', found '{'
Line 7 col 5 error| expected ']', found ':='
Line 11 col 3 error| expected declaration, found 'return'

Can someone help me get the syntax right? Or am I trying to do something that Go doesn't do?

Body:
You need to declare the whole type including key and value types.

func defaults() map[string]string {
    …
}


问:
Default error popup with TextInputLayout
Having a problem setting a different error message to EditText inside TextInputLayout.

What I get:

What I want:

Is there anyway to achieve it while maintaining TextInputLayout?

答:
XML:

```<code><TextInputLayout
     android:layout_height="wrap_content"
     android:layout_width="match_parent">

     <EditText
          android:id="@+id/et"
          android:layout_width="match_parent"
          android:layout_height="wrap_content"/>

</TextInputLayout>
</code>```

JAVA:

```<code>EditText et = (EditText) findViewById(R.id.et);
if(et.getText().length() == 0){
    et.setError("Please Enter this Detail");
}
</code>```

Body:
XML:

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

     <EditText
          android:id="@+id/et"
          android:layout_width="match_parent"
          android:layout_height="wrap_content"/>

</TextInputLayout>

JAVA:

EditText et = (EditText) findViewById(R.id.et);
if(et.getText().length() == 0){
    et.setError("Please Enter this Detail");
}


问:
R starts up with error message
I am asking this question out of curiosity. I have noticed that whenever I boot R, the instance starts up with this error message

As you can see, R boots with the error message "object 'a' not found" Is there any reason for this?

答:
R reads and executes several files at startup, most prominently the ~/.Rprofile file (That is, the file .Rprofile in your home directory). Check these files to see if they contain anything weird.

You can quickly check whether .Rprofile is the culprit by running R with the --vanilla command line argument: this argument prevents the user profile to be read, thus the error should vanish.

Title: R starts up with error message


问:
How to increment letters in javascript to next letter?
I want a function that I can go from A to B, B to C, Z to A.

My function is currently like so:

```<code>function nextChar(c) {
    return String.fromCharCode(c.charCodeAt(0) + 1);
}
nextChar('a');
</code>```

It works for A to X, but when I use Z... it goes to [ instead of A.

答:
```<code>function nextChar(c) {
        return String.fromCharCode(((c.charCodeAt(0) + 1 - 65) % 25) + 65);
}
</code>```

where 65 stands for offset from 0 in ASCII table and 25 means that after 25th character it will start from the beginning (offset character code is divided by 25 and you get remainder that is offset back to proper ASCII code)

Body:
I want a function that I can go from A to B, B to C, Z to A.

My function is currently like so:

function nextChar(c) {
    return String.fromCharCode(c.charCodeAt(0) + 1);
}
nextChar('a');

It works for A to X, but when I use Z... it goes to [ instead of A.

Body:
function nextChar(c) {
        return String.fromCharCode(((c.charCodeAt(0) + 1 - 65) % 25) + 65);
}

where 65 stands for offset from 0 in ASCII table and 25 means that after 25th character it will start from the beginning (offset character code is divided by 25 and you get remainder that is offset back to proper ASCII code)

ContentLicense: CC BY-SA 4.0


问:
Ransacker and Arel on associations fields
I have Project::Contribution that belongs_to User, and
User has_one User::Profile.

first_name and last_name are fields contained in User::Profile

I want to create a ransacker that would allow me to filter my contributions with their user profile first_name and last_name.

How can this be achieved ?

This is what I tried so far :

```<code># admin/contribution.rb
filter :user_full_name_cont

# models/user.rb
ransacker :full_name do |parent|
  Arel::Nodes::InfixOperation.new('||', parent.table[:profile_first_name], parent.table[:profile_last_name]) # error
end
</code>```

This fails because of : parent.table[:profile_first_name] and parent.table[:profile_last_name] because I can't access the profile table like so.

答:
Finally came to a solution :</p>

```<code># models/user/profile.rb
  ransacker :full_name, formatter: proc { |v| v.mb_chars.downcase.to_s } do |parent|
    Arel::Nodes::NamedFunction.new('LOWER',
     [Arel::Nodes::NamedFunction.new('concat_ws',
      [Arel::Nodes.build_quoted(' '), parent.table[:first_name], parent.table[:last_name]])])
  end

# admin/user.rb
filter :user_profile_full_name_cont
</code>```

Body:
I have Project::Contribution that belongs_to User, and
User has_one User::Profile.

first_name and last_name are fields contained in User::Profile

I want to create a ransacker that would allow me to filter my contributions with their user profile first_name and last_name.

How can this be achieved ?

This is what I tried so far :

# admin/contribution.rb
filter :user_full_name_cont

# models/user.rb
ransacker :full_name do |parent|
  Arel::Nodes::InfixOperation.new('||', parent.table[:profile_first_name], parent.table[:profile_last_name]) # error
end

This fails because of : parent.table[:profile_first_name] and parent.table[:profile_last_name] because I can't access the profile table like so.

Body:
Finally came to a solution :

# models/user/profile.rb
  ransacker :full_name, formatter: proc { |v| v.mb_chars.downcase.to_s } do |parent|
    Arel::Nodes::NamedFunction.new('LOWER',
     [Arel::Nodes::NamedFunction.new('concat_ws',
      [Arel::Nodes.build_quoted(' '), parent.table[:first_name], parent.table[:last_name]])])
  end

# admin/user.rb
filter :user_profile_full_name_cont


问:
Impossible to find the name of a font
I am looking for the name of the font in this image:what font is it

Anyone knows that font?

Thank you :)

答:
I don't think this question belongs on SO.. but!

You can use this site to find it: https://www.myfonts.com/WhatTheFont/

Looks like <s>uni sans</s> forgotten futurist to me.

Title: Impossible to find the name of a font


问:
How to remove common objects from two lists with linq

Both lists have Objects with ID and Name properties.

List1({1, apple}, {2, orange}, {3, banana}, {4, potato}, {5, tomato})

List2({1, apple}, {2, orange}, {3, banana})

Final output List3({4, potato}, {5, tomato})

答:
This example doesn't contain objects but it should show you a way to do what you are trying to achieve </p>

```<code>var list1 = new List<string>{"apple", "orange", "banana", "potato", "tomato"};
var list2 = new List<string>{"apple", "orange", "banana"};
var result = list1.Where(f => !list2.Contains(f));
</code>```

Body:
This example doesn't contain objects but it should show you a way to do what you are trying to achieve

var list1 = new List<string>{"apple", "orange", "banana", "potato", "tomato"};
var list2 = new List<string>{"apple", "orange", "banana"};
var result = list1.Where(f => !list2.Contains(f));


问:
Flickering when updating the datacontext in background
I'm studying UWP by Windows 10 development for absolute beginners, and I meet some problems.
Reflash my ObservableCollection<> data will cause the screen to flash. How do I fix it?
The program details are in UWP beginner </p>

```<code>    //CS FILE CODE

    public sealed partial class FinancialPage : Page
    {
        ObservableCollection<NewsItem> NewsItems;
        public FinancialPage()
        {
            NewsItems = new ObservableCollection<NewsItem>();
            this.InitializeComponent();
            GetNewsItemManager.GetNewItemsByCategory(NewsItems, "Financial");
        }
    }

    // XAML FILE CODE
    <GridView ItemsSource="{x:Bind NewsItems}" Background="LightGray">
        <GridView.ItemTemplate>
            <DataTemplate x:DataType="data:NewsItem">
                <local:NewsContentControl HorizontalAlignment="Stretch" VerticalAlignment="Stretch"/>
            </DataTemplate>
        </GridView.ItemTemplate>
    </GridView>

    //MODELS NEWSITEMS CLASS FILE
    public static void GetNewItemsByCategory(ObservableCollection<NewsItem> NewsItems, string Category)
    {
        var allnewsitems = getNewsItems();
        var filteredNewsItems = allnewsitems.Where(p => p.Category == Category && IsExist(NewsItems, p.Id)).ToList();
        filteredNewsItems.ForEach(p => NewsItems.Add(p));
    }

    private static Boolean IsExist(ObservableCollection<NewsItem> NewsItems, int Id)
    {
        return NewsItems.ToList().TrueForAll(p => Id == p.Id);
    }

    private static List<NewsItem> getNewsItems()
    {
        var items = new List<NewsItem>();

        items.Add(new NewsItem() { Id = 1, Category = "Financial", Headline = "Lorem Ipsum", Subhead = "doro sit amet", DateLine = "Nunc tristique nec", Image = "Assets/Financial1.png" });
        items.Add(new NewsItem() { Id = 2, Category = "Financial", Headline = "Etiam ac felis viverra", Subhead = "vulputate nisl ac, aliquet nisi", DateLine = "tortor porttitor, eu fermentum ante congue", Image = "Assets/Financial2.png" });
        items.Add(new NewsItem() { Id = 3, Category = "Financial", Headline = "Integer sed turpis erat", Subhead = "Sed quis hendrerit lorem, quis interdum dolor", DateLine = "in viverra metus facilisis sed", Image = "Assets/Financial3.png" });
        items.Add(new NewsItem() { Id = 4, Category = "Financial", Headline = "Proin sem neque", Subhead = "aliquet quis ipsum tincidunt", DateLine = "Integer eleifend", Image = "Assets/Financial4.png" }); items.Add(new NewsItem() { Id = 5, Category = "Financial", Headline = "Mauris bibendum non leo vitae tempor", Subhead = "In nisl tortor, eleifend sed ipsum eget", DateLine = "Curabitur dictum augue vitae elementum ultrices", Image = "Assets/Financial5.png" });

        items.Add(new NewsItem() { Id = 6, Category = "Food", Headline = "Lorem ipsum", Subhead = "dolor sit amet", DateLine = "Nunc tristique nec", Image = "Assets/Food1.png" });
        items.Add(new NewsItem() { Id = 7, Category = "Food", Headline = "Etiam ac felis viverra", Subhead = "vulputate nisl ac, aliquet nisi", DateLine = "tortor porttitor, eu fermentum ante congue", Image = "Assets/Food2.png" });
        items.Add(new NewsItem() { Id = 8, Category = "Food", Headline = "Integer sed turpis erat", Subhead = "Sed quis hendrerit lorem, quis interdum dolor", DateLine = "in viverra metus facilisis sed", Image = "Assets/Food3.png" });
        items.Add(new NewsItem() { Id = 9, Category = "Food", Headline = "Proin sem neque", Subhead = "aliquet quis ipsum tincidunt", DateLine = "Integer eleifend", Image = "Assets/Food4.png" });
        items.Add(new NewsItem() { Id = 10, Category = "Food", Headline = "Mauris bibendum non leo vitae tempor", Subhead = "In nisl tortor, eleifend sed ipsum eget", DateLine = "Curabitur dictum augue vitae elementum ultrices", Image = "Assets/Food5.png" });
        return items;
        }
</code>```

答:
OK... I think I've found a solution for you.

Instead of updating the bindings in your user control with the lambda expression, try it this way:

```<code>public NewsContentControl()
{
    this.InitializeComponent();
    this.DataContextChanged += OnDataCtxChanged; //+= (s, e) => Bindings.Update();
}

private void OnDataCtxChanged(FrameworkElement sender, DataContextChangedEventArgs args)
{
    System.Diagnostics.Debug.WriteLine("context 'changed'");
    if(NewsItem != args.NewValue as NewsItem)
    {
        Bindings.Update();
    }
}
</code>```

This triggers the update only if the value is actually different.  Additionally, you can use "Binding" instead of x:Bind.

None of this answers for me why the datacontext is changing... but this should get rid of your flicker.

Body:
I'm studying UWP by Windows 10 development for absolute beginners, and I meet some problems.
Reflash my ObservableCollection<> data will cause the screen to flash. How do I fix it?
The program details are in UWP beginner

    //CS FILE CODE

    public sealed partial class FinancialPage : Page
    {
        ObservableCollection<NewsItem> NewsItems;
        public FinancialPage()
        {
            NewsItems = new ObservableCollection<NewsItem>();
            this.InitializeComponent();
            GetNewsItemManager.GetNewItemsByCategory(NewsItems, "Financial");
        }
    }

    // XAML FILE CODE
    <GridView ItemsSource="{x:Bind NewsItems}" Background="LightGray">
        <GridView.ItemTemplate>
            <DataTemplate x:DataType="data:NewsItem">
                <local:NewsContentControl HorizontalAlignment="Stretch" VerticalAlignment="Stretch"/>
            </DataTemplate>
        </GridView.ItemTemplate>
    </GridView>

    //MODELS NEWSITEMS CLASS FILE
    public static void GetNewItemsByCategory(ObservableCollection<NewsItem> NewsItems, string Category)
    {
        var allnewsitems = getNewsItems();
        var filteredNewsItems = allnewsitems.Where(p => p.Category == Category && IsExist(NewsItems, p.Id)).ToList();
        filteredNewsItems.ForEach(p => NewsItems.Add(p));
    }

    private static Boolean IsExist(ObservableCollection<NewsItem> NewsItems, int Id)
    {
        return NewsItems.ToList().TrueForAll(p => Id == p.Id);
    }

    private static List<NewsItem> getNewsItems()
    {
        var items = new List<NewsItem>();

        items.Add(new NewsItem() { Id = 1, Category = "Financial", Headline = "Lorem Ipsum", Subhead = "doro sit amet", DateLine = "Nunc tristique nec", Image = "Assets/Financial1.png" });
        items.Add(new NewsItem() { Id = 2, Category = "Financial", Headline = "Etiam ac felis viverra", Subhead = "vulputate nisl ac, aliquet nisi", DateLine = "tortor porttitor, eu fermentum ante congue", Image = "Assets/Financial2.png" });
        items.Add(new NewsItem() { Id = 3, Category = "Financial", Headline = "Integer sed turpis erat", Subhead = "Sed quis hendrerit lorem, quis interdum dolor", DateLine = "in viverra metus facilisis sed", Image = "Assets/Financial3.png" });
        items.Add(new NewsItem() { Id = 4, Category = "Financial", Headline = "Proin sem neque", Subhead = "aliquet quis ipsum tincidunt", DateLine = "Integer eleifend", Image = "Assets/Financial4.png" }); items.Add(new NewsItem() { Id = 5, Category = "Financial", Headline = "Mauris bibendum non leo vitae tempor", Subhead = "In nisl tortor, eleifend sed ipsum eget", DateLine = "Curabitur dictum augue vitae elementum ultrices", Image = "Assets/Financial5.png" });

        items.Add(new NewsItem() { Id = 6, Category = "Food", Headline = "Lorem ipsum", Subhead = "dolor sit amet", DateLine = "Nunc tristique nec", Image = "Assets/Food1.png" });
        items.Add(new NewsItem() { Id = 7, Category = "Food", Headline = "Etiam ac felis viverra", Subhead = "vulputate nisl ac, aliquet nisi", DateLine = "tortor porttitor, eu fermentum ante congue", Image = "Assets/Food2.png" });
        items.Add(new NewsItem() { Id = 8, Category = "Food", Headline = "Integer sed turpis erat", Subhead = "Sed quis hendrerit lorem, quis interdum dolor", DateLine = "in viverra metus facilisis sed", Image = "Assets/Food3.png" });
        items.Add(new NewsItem() { Id = 9, Category = "Food", Headline = "Proin sem neque", Subhead = "aliquet quis ipsum tincidunt", DateLine = "Integer eleifend", Image = "Assets/Food4.png" });
        items.Add(new NewsItem() { Id = 10, Category = "Food", Headline = "Mauris bibendum non leo vitae tempor", Subhead = "In nisl tortor, eleifend sed ipsum eget", DateLine = "Curabitur dictum augue vitae elementum ultrices", Image = "Assets/Food5.png" });
        return items;
        }

Body:
OK... I think I've found a solution for you.

Instead of updating the bindings in your user control with the lambda expression, try it this way:

public NewsContentControl()
{
    this.InitializeComponent();
    this.DataContextChanged += OnDataCtxChanged; //+= (s, e) => Bindings.Update();
}

private void OnDataCtxChanged(FrameworkElement sender, DataContextChangedEventArgs args)
{
    System.Diagnostics.Debug.WriteLine("context 'changed'");
    if(NewsItem != args.NewValue as NewsItem)
    {
        Bindings.Update();
    }
}

This triggers the update only if the value is actually different.  Additionally, you can use "Binding" instead of x:Bind.

None of this answers for me why the datacontext is changing... but this should get rid of your flicker.


问:
xcrun: error: unable to find utility "PackageApplication", not a developer tool or in PATH - Since updating Xcode
Updated Xcode this morning and now ionic project wont deploy to a device.

```<code>ionic run ios --device
</code>```

Returns:

```<code>** BUILD SUCCEEDED **

xcrun: error: unable to find utility "PackageApplication", not a developer tool or in PATH

Error: Error code 72 for command: xcrun with args: -sdk,iphoneos,PackageApplication,-v
</code>```

No idea what to do to fix, Googling returns lots of options but none correct.

答:
Hi its official Bug from jenkins

here you have a fresh status

https://issues.jenkins-ci.org/browse/JENKINS-43163

Little bit clearer to look at this:

http://subathrathanabalan.com/2016/01/07/building-ipa-export-archive/

Body:
Updated Xcode this morning and now ionic project wont deploy to a device.

ionic run ios --device

Returns:

** BUILD SUCCEEDED **

xcrun: error: unable to find utility "PackageApplication", not a developer tool or in PATH

Error: Error code 72 for command: xcrun with args: -sdk,iphoneos,PackageApplication,-v

No idea what to do to fix, Googling returns lots of options but none correct.


问:
Reference all indexes in list and check for existence of value in python
I'm trying to create if block in my python3 script that checks if a value exists within a list I pull from JSON. The JSON data is below:

```<code>[
  {
    "id": 59616405645,
    "name": "Foo"
  },
  {
    "id": 990164054345,
    "name": "FindMe"
  },
  {
    "id": 2009167874,
    "name": "Bar"
  }
]
</code>```

I'm trying to determine whether or not the value of Bar exists within the list. To do so I'm doing the following which directly references the index:

```<code>if "FindMe" in m_orgs[1].values():
    print("Yo it's here")
else:
    print("Yo it's not here.")
</code>```

But the JSON data I'm pulling will always have different results and we will never know the index numbers, so direct reference will not work. How do I reference all indexes in a list at once?

答:
You can use any() like this:</p>

```<code>if any(d['name'] == 'Foo' for d in json):
    do this
</code>```

Body:
I'm trying to create if block in my python3 script that checks if a value exists within a list I pull from JSON. The JSON data is below:

[
  {
    "id": 59616405645,
    "name": "Foo"
  },
  {
    "id": 990164054345,
    "name": "FindMe"
  },
  {
    "id": 2009167874,
    "name": "Bar"
  }
]

I'm trying to determine whether or not the value of Bar exists within the list. To do so I'm doing the following which directly references the index:

if "FindMe" in m_orgs[1].values():
    print("Yo it's here")
else:
    print("Yo it's not here.")

But the JSON data I'm pulling will always have different results and we will never know the index numbers, so direct reference will not work. How do I reference all indexes in a list at once?

Body:
You can use any() like this:

if any(d['name'] == 'Foo' for d in json):
    do this


问:
How to practically handle validation of revoked certificates?
As far as I know every certificate should be verified regarding revocation during certificate chain verification to protect connection against MITM attacks.

For this reason as I understand, I should use CRL/CRL deltas or OCSP. I'm some how newbie in this area, but even after reading some related RFCs(however not so carefully), I have no idea how practically use/check revocations.

What kind of protocols are widely used as OCSP "transport layer" - I know only HTTP - there are other competitive alternatives, which modern client should support?

If I understand correctly CA will point in every certificate where to find CRL (except root CA / which is self signed) (in list of "CRL Distribution Points"?), so to implement strict client should I download CRL during certificate chain handshake. I know that for this purpose may be used HTTP and LDAP - are there other competitive alternatives, which modern client need to support? LDAP for this purpose is still common(or maybe this is just legacy)?

Is in CRL way to detect how long it is valid, so can I cache it somehow for further connections?

Is there practical way to work "offline" with CRL? As I understand to have it working in general, I should download(and update) CRL for every possible CA in world, which will require a much more resources/effort than doing so "online".

How deep may be typical certificate chain? Eg. more than for example 10 certificates in chain is possible?

Does boost asio support somehow natively CRL and/or OCSP? I need to do this by myself?

How in botan implement CRL "online" validation for cert chain? Maybe it is out of the box(as OCSP is implemented)?

Both methods should be supported or maybe OCSP is used by most CA and CRL is defined by them only for legacy sw support reasons? If I would like just connect to 95% servers, then I need implement only OCSP and not care about CRL and reject certificates which cannot be verified using OCSP? Or maybe support for OCSP is relatively rare? As I found ocsp is supported for EV certs but not for OV and DV. Is that true?

Maybe I should check revocation both through OCSP and CRL. Is it sufficient that one "preferred" is available or do I need both?

答:
A MITM attack is not avoided with a revocation check.

To prevent a MITM you need to include the server root CA certificate in the client truststore and check that the server certificate has been issued by a trusted CA (present in your truststore). You can include also the server certificate in the truststore. A revocation check could make sense in the case that the attacker had stolen the certificate

1) What kind of protocols are widely used as OCSP "transport layer" - I know only HTTP - there are other competitive alternatives, which modern client should support?

HTTP and HTTPS

2) If I understand correctly CA will point in every certificate where to find CRL (except root CA / which is self signed) (in list of "CRL Distribution Points"?), so to implement strict client should I download CRL during certificate chain handshake. I know that for this purpose may be used HTTP and ldap - are there other competitive alternatives, which modern client need to support? ldap for this purpose is still common(or meybe this is just legacy)?

HTTP is the usual way. But it can be HTTP, FTP, LDAP, or FILE. LDAP is also used in some environments

3) Is in CRL way to detect how long it is valid, so can I cache it somehow for further connections?

CRL includes a nextUpdate field  that indicates the date by which the next CRL will be issued

4) Is there practical way to work "offline" with CRL? As I understand to have it working in general, I should download(and update) CRL for every possible CA in world, which will require a much more resources/effort than doing so "online".

The usual way is to download the CRL when you need it, cache it and in the next check, check if you already have it

5) How deep may be typical certificate chain? Eg. more than for example 10 certificates in chain is possible?

There is no limit, but the usual value is 2-4

6) Does boost asio support somehow natively CRL and/or OCSP? I need to do this by myself?

There is no reference in the certificate verification section of asio so I'm afraid you'll have to implement it yourself

7) How in botan implement CRL "online" validation for cert chain? Maybe it is out of the box(as OCSP is implemented)?

OCSP is Online Certificate Status Protocol. In the web seem they refer to OCSP when they talk about online validation, but only CRL is supported

8) Both methods should be supported or meybe OCSP is used by most CA and CRL is defined by them only for legacy sw support reasons? If I would like just connect to 95% servers, then I need implement only OCSP and not care about CRL and reject certificates which cannot be verified using OCSP? Or maybe support for OCSP is relatively rare? As I found ocsp is supported for EV certs but not for OV and DV. That's true?

CA usually support OCSP & CRL. You need to support both. Even in the same CA it could be certificates that has to be checked with OCSP and others with CRL

9) Maybe I should check revocation both through OCSP and CRL if both available or just one "preferred" is enough?

OCSP is preferable because it is faster and uses fewer resources. The normal implementation is to launch a query in parallel to both services and use the response that came before