问:
How to update the version of compiled framework
I am using XCode 8.3 and I am trying to Run my project which is connected with link and now I have a XCode Error: Module compiled with Swift 3.0.2 cannot be imported in Swift 3.1
So my question is how to update the version of the framework?
I downloaded this framework from the link that I've posted above.</p>

答:
I think that you need to update CocoaPods to a newer version supports XCode 8 (CocoaPods 1.1.0 or newer):

```<code>sudo gem install cocoapods
</code>```

Then do a pod update to fix your dependencies that are not linking:

```<code>pod update
</code>```

Delete the DerivedData folder for your project and rebuild, the link error should be gone.

Body:
I think that you need to update CocoaPods to a newer version supports XCode 8 (CocoaPods 1.1.0 or newer):

sudo gem install cocoapods

Then do a pod update to fix your dependencies that are not linking:

pod update

Delete the DerivedData folder for your project and rebuild, the link error should be gone.


来源: stackexchange

问:
how to save arraylist<object> after app is closed
how to save arraylist after the app is closed.
This is my global class

```<code>public class GlobalClass extends Application {

ArrayList<Trip> allTrips = new ArrayList<>();

public ArrayList<String> allTripsString() {
    ArrayList<String> allTripsString = new ArrayList<String>();
    for (Trip trip : allTrips){
        allTripsString.add(trip.getName());
    }
    return allTripsString;
    }
}
</code>```

This is my trip class

```<code>public class Trip {

/** A map with category as key and the associed list of items as value */
Map<String,List<Item>> expanses;

private String name;
public ArrayList<String> ExpensesCategory = new ArrayList<>();
public ArrayList<String> Adults = new ArrayList<>();
public ArrayList<String> Children = new ArrayList<>();
public ArrayList<String> ShoppingName = new ArrayList<>();
public ArrayList<Double> ShoppingPrice = new ArrayList<>();
public ArrayList<String> ShoppingCategory = new ArrayList<>();
public double budget = 0;

/** An item in the expanses list */
static class Item {
    final String name;
    final double cost;
    final String Category;
    public Item(String name, double cost, String Category) {
        this.name = name;
        this.cost = cost;
        this.Category = Category;
    }
    @Override public String toString() {
        return this.name + " (" + this.cost + "$)";
    }
    public String getName(){
        return name;
    }
    public String getCategory(){
        return Category;
    }
    public double getCost(){
        return cost;
    }
}

public Trip(String name) {
    this.name = name;
    this.expanses = new HashMap<String,List<Item>>();
    for (String cat: ExpensesCategory) { // init the categories with empty lists
        this.expanses.put(cat, new ArrayList<Item>());
    }
}

public String getName(){
    return name;
}

/** Register a new expanse to the trip. */
public void add(String item, double cost, String category) {
    List<Item> list = this.expanses.get(category);
    if (list == null)
        throw new IllegalArgumentException("Category '"+category+"' does not exist.");
    list.add( new Item(item, cost, category) );
}

/** Get the expanses, given a category.
 * @return  a fresh ArrayList containing the category elements, or null if the category does not exists
 */
public List<Item> getItems(String category) {
    List<Item> list = this.expanses.get(category);
    if (list == null)
        return null;
    return new ArrayList<Item>(list);
}

/** Get the expanses, given a category.
 * @return  a fresh ArrayList containing all the elements
 */
public List<Item> getItems() {
    List<Item> list = new ArrayList<Item>();
    for (List<Item> l: this.expanses.values()) // fill with each category items
        list.addAll(l);
    return list;
}

public ArrayList<String> getItemsString() {
    List<Item> list = new ArrayList<Item>();
    for (List<Item> l: this.expanses.values()) // fill with each category items
        list.addAll(l);
    ArrayList<String> listString = new ArrayList<String>();
    for (Item item : list){
        listString.add(item.getName());
    }
    return listString;
}

public ArrayList<Double> getItemsCost(){
    List<Item> list = new ArrayList<Item>();
    for (List<Item> l: this.expanses.values()) // fill with each category items
        list.addAll(l);
    ArrayList<Double> listDouble = new ArrayList<>();
    for (Item item : list){
        listDouble.add(item.getCost());
    }
    return listDouble;
}

public ArrayList<String> getItemsCategory() {
    List<Item> list = new ArrayList<Item>();
    for (List<Item> l: this.expanses.values()) // fill with each category items
        list.addAll(l);
    ArrayList<String> listString = new ArrayList<String>();
    for (Item item : list){
        listString.add(item.getCategory());
    }
    return listString;
}

/** Get the total cost, given a category. */
public double getCost(String category) {
    List<Item> list = this.expanses.get(category);
    if (list == null)
        return -1;
    double cost = 0;
    for (Item item: list)
        cost += item.cost;
    return cost;
}

/** Get the total cost. */
public double getCost() {
    double cost = 0;
    for (List<Item> l: this.expanses.values())
        for (Item item: l)
            cost += item.cost;
    cost *= 1000;
    cost = (int)(cost);
    cost /= 1000;
    return cost;
    }
}
</code>```

I want to save the array list and when I close and open the app the array list (alltrips) is saved. How to do this?

I want to use shared preferences but I don't know how to do this because it is not a string it array list with Trip. Can anyone help me to save the arraylist in shared preferences?

答:
SharedPreferences allows you to save a Set of Strings, so your best scenario is to convert every object into a String and then save this collection of String into sharedpreferences, and then when needed you can rebuild the objects from these Strings.

Or you can save it in file system or DB, but SharedPreferences is lighter and easier if all you want is this. Either way you will need to construct/deconstruct the saved content of your list.

```<code>//Retrieve the values
Set<String> set = myScores.getStringSet("key", null);

//Set the values
Set<String> set = new HashSet<String>();
set.addAll(listOfExistingScores);
scoreEditor.putStringSet("key", set);
scoreEditor.commit();
</code>```

EDIT

simple example

```<code>public void saveToSharedPreferences(Context context, List<String> list){

    Set<String> set =
            list.stream()
            .collect(Collectors.toSet()); // Returns in this case a Set, if you need Iterable or Collection it is also available.

    PreferenceManager.getDefaultSharedPreferences(context) // Get Default preferences, you could use other.
            .edit()
            .putStringSet("myKey", set) // Save the Set of Strings (all trips but as Strings) with the key "myKey", this key is up to you.
            .apply();                   // When possible commit the changes to SharePreferences.
}

public void saveToSharedPreferences(Context context, List<Trip> list){
    List<String> stringList = list.stream()
            .map(Trip::getName) // This uses this method to transform a Trip into a String
                                // you could use other method to transform into String but if all you need to save is the name this suffices
                                // examples: .map( trip -> trip.getName()), .map(trip -> trip.toString()), etc. you choose how to save.
                                // It should save every state that a Trip has, so when you are reading the saved Strings
                                // you will be able to reconstruct a Trip with its state from each String.
            .collect(Collectors.toList());
    saveToSharedPreferences(context, stringList);
}
</code>```

NOTE i did not test this but it should be ok (currently i do not have Android Studio so there might be some little errors, but from this solution you should be able to finish this. If needed i could give you the complete solution working. As of now i do not have access to my IDE and WorkStation.

ContentLicense: CC BY-SA 3.0

Body:
how to save arraylist after the app is closed.
This is my global class

public class GlobalClass extends Application {

ArrayList<Trip> allTrips = new ArrayList<>();

public ArrayList<String> allTripsString() {
    ArrayList<String> allTripsString = new ArrayList<String>();
    for (Trip trip : allTrips){
        allTripsString.add(trip.getName());
    }
    return allTripsString;
    }
}

This is my trip class

public class Trip {

/** A map with category as key and the associed list of items as value */
Map<String,List<Item>> expanses;

private String name;
public ArrayList<String> ExpensesCategory = new ArrayList<>();
public ArrayList<String> Adults = new ArrayList<>();
public ArrayList<String> Children = new ArrayList<>();
public ArrayList<String> ShoppingName = new ArrayList<>();
public ArrayList<Double> ShoppingPrice = new ArrayList<>();
public ArrayList<String> ShoppingCategory = new ArrayList<>();
public double budget = 0;

/** An item in the expanses list */
static class Item {
    final String name;
    final double cost;
    final String Category;
    public Item(String name, double cost, String Category) {
        this.name = name;
        this.cost = cost;
        this.Category = Category;
    }
    @Override public String toString() {
        return this.name + " (" + this.cost + "$)";
    }
    public String getName(){
        return name;
    }
    public String getCategory(){
        return Category;
    }
    public double getCost(){
        return cost;
    }
}

public Trip(String name) {
    this.name = name;
    this.expanses = new HashMap<String,List<Item>>();
    for (String cat: ExpensesCategory) { // init the categories with empty lists
        this.expanses.put(cat, new ArrayList<Item>());
    }
}

public String getName(){
    return name;
}

/** Register a new expanse to the trip. */
public void add(String item, double cost, String category) {
    List<Item> list = this.expanses.get(category);
    if (list == null)
        throw new IllegalArgumentException("Category '"+category+"' does not exist.");
    list.add( new Item(item, cost, category) );
}

/** Get the expanses, given a category.
 * @return  a fresh ArrayList containing the category elements, or null if the category does not exists
 */
public List<Item> getItems(String category) {
    List<Item> list = this.expanses.get(category);
    if (list == null)
        return null;
    return new ArrayList<Item>(list);
}

/** Get the expanses, given a category.
 * @return  a fresh ArrayList containing all the elements
 */
public List<Item> getItems() {
    List<Item> list = new ArrayList<Item>();
    for (List<Item> l: this.expanses.values()) // fill with each category items
        list.addAll(l);
    return list;
}

public ArrayList<String> getItemsString() {
    List<Item> list = new ArrayList<Item>();
    for (List<Item> l: this.expanses.values()) // fill with each category items
        list.addAll(l);
    ArrayList<String> listString = new ArrayList<String>();
    for (Item item : list){
        listString.add(item.getName());
    }
    return listString;
}

public ArrayList<Double> getItemsCost(){
    List<Item> list = new ArrayList<Item>();
    for (List<Item> l: this.expanses.values()) // fill with each category items
        list.addAll(l);
    ArrayList<Double> listDouble = new ArrayList<>();
    for (Item item : list){
        listDouble.add(item.getCost());
    }
    return listDouble;
}

public ArrayList<String> getItemsCategory() {
    List<Item> list = new ArrayList<Item>();
    for (List<Item> l: this.expanses.values()) // fill with each category items
        list.addAll(l);
    ArrayList<String> listString = new ArrayList<String>();
    for (Item item : list){
        listString.add(item.getCategory());
    }
    return listString;
}

/** Get the total cost, given a category. */
public double getCost(String category) {
    List<Item> list = this.expanses.get(category);
    if (list == null)
        return -1;
    double cost = 0;
    for (Item item: list)
        cost += item.cost;
    return cost;
}

/** Get the total cost. */
public double getCost() {
    double cost = 0;
    for (List<Item> l: this.expanses.values())
        for (Item item: l)
            cost += item.cost;
    cost *= 1000;
    cost = (int)(cost);
    cost /= 1000;
    return cost;
    }
}

I want to save the array list and when I close and open the app the array list (alltrips) is saved. How to do this?

I want to use shared preferences but I don't know how to do this because it is not a string it array list with Trip. Can anyone help me to save the arraylist in shared preferences?

Body:
SharedPreferences allows you to save a Set of Strings, so your best scenario is to convert every object into a String and then save this collection of String into sharedpreferences, and then when needed you can rebuild the objects from these Strings.

Or you can save it in file system or DB, but SharedPreferences is lighter and easier if all you want is this. Either way you will need to construct/deconstruct the saved content of your list.

//Retrieve the values
Set<String> set = myScores.getStringSet("key", null);

//Set the values
Set<String> set = new HashSet<String>();
set.addAll(listOfExistingScores);
scoreEditor.putStringSet("key", set);
scoreEditor.commit();

EDIT

simple example

public void saveToSharedPreferences(Context context, List<String> list){

    Set<String> set =
            list.stream()
            .collect(Collectors.toSet()); // Returns in this case a Set, if you need Iterable or Collection it is also available.

    PreferenceManager.getDefaultSharedPreferences(context) // Get Default preferences, you could use other.
            .edit()
            .putStringSet("myKey", set) // Save the Set of Strings (all trips but as Strings) with the key "myKey", this key is up to you.
            .apply();                   // When possible commit the changes to SharePreferences.
}

public void saveToSharedPreferences(Context context, List<Trip> list){
    List<String> stringList = list.stream()
            .map(Trip::getName) // This uses this method to transform a Trip into a String
                                // you could use other method to transform into String but if all you need to save is the name this suffices
                                // examples: .map( trip -> trip.getName()), .map(trip -> trip.toString()), etc. you choose how to save.
                                // It should save every state that a Trip has, so when you are reading the saved Strings
                                // you will be able to reconstruct a Trip with its state from each String.
            .collect(Collectors.toList());
    saveToSharedPreferences(context, stringList);
}

NOTE i did not test this but it should be ok (currently i do not have Android Studio so there might be some little errors, but from this solution you should be able to finish this. If needed i could give you the complete solution working. As of now i do not have access to my IDE and WorkStation.


问:
SQL - Retrieve Avg Score from Group
My Database contains the following:

```<code>|    ID     |     UID      |     file    |    score    |    time   |
     1    |     a827vgj28df |  jack_123  |      75     |       12:44
     2    |     ayeskfkfjhk  | jack_999   |      5     |      12:12
     3     |    b83759       | adam_123   |      7      |      12:12
</code>```

Goal:
I am trying to get a query that displays the avg scores for each file prefix (jack/adam)

To display like:

```<code>|  Key   |   AVG
  jack       40
  adam        7
</code>```

答:
you can get the key using SUBSTRING_INDEX and  then group by </p>

```<code>  SELECT
      SUBSTRING_INDEX(file, '_', 1) AS key
      , avg(score) average
  from my_table
  group by  key
</code>```

Title: SQL - Retrieve Avg Score from Group

Body:
My Database contains the following:

|    ID     |     UID      |     file    |    score    |    time   |
     1    |     a827vgj28df |  jack_123  |      75     |       12:44
     2    |     ayeskfkfjhk  | jack_999   |      5     |      12:12
     3     |    b83759       | adam_123   |      7      |      12:12

Goal:
I am trying to get a query that displays the avg scores for each file prefix (jack/adam)

To display like:

|  Key   |   AVG
  jack       40
  adam        7

Body:
you can get the key using SUBSTRING_INDEX and  then group by

  SELECT
      SUBSTRING_INDEX(file, '_', 1) AS key
      , avg(score) average
  from my_table
  group by  key


问:
How to get cmake to find size of type in third-party header mpi.h?
I am working on a free-software project which involves high performance computing and the MPI library.

In my code, I need to know the size of the MPI_Offset type, which is defined in mpi.h.

Normally such projects would be build using autotools and this problem would be easily solved. But for my sins, I am working with a CMake build and I can't find any way to perform this simple task. But there must be a way to do - it is commonly done on autotools projects, so I assume it is also possible in CMake.

When I use:

```<code>check_type_size("MPI_Offset" SIZEOF_MPI_OFFSET)
</code>```

It fails, because mpi.h is not included in the generated C code.

Is there a way to tell check_type_size() to include mpi.h?

答:
This is done via CMAKE_EXTRA_INCLUDE_FILES:

```<code>INCLUDE (CheckTypeSize)

find_package(MPI)
include_directories(SYSTEM ${MPI_INCLUDE_PATH})

SET(CMAKE_EXTRA_INCLUDE_FILES "mpi.h")
check_type_size("MPI_Offset" SIZEOF_MPI_OFFSET)
SET(CMAKE_EXTRA_INCLUDE_FILES)
</code>```

It may be more common to write platform checks with autotools, so here is some more information on how to write platform checks with CMake.

On a personal note, while CMake is certainly not the most pleasant exercise, for me autotools is reserved for the capital sins. It is really hard to me to defend CMake, but in this instance, it is even documented. Naturally, setting a separate "variable" that you even have to reset after the fact, instead of just passing it as a parameter, is clearly conforming to the surprising "design principles" of CMake.

Body:
I am working on a free-software project which involves high performance computing and the MPI library.

In my code, I need to know the size of the MPI_Offset type, which is defined in mpi.h.

Normally such projects would be build using autotools and this problem would be easily solved. But for my sins, I am working with a CMake build and I can't find any way to perform this simple task. But there must be a way to do - it is commonly done on autotools projects, so I assume it is also possible in CMake.

When I use:

check_type_size("MPI_Offset" SIZEOF_MPI_OFFSET)

It fails, because mpi.h is not included in the generated C code.

Is there a way to tell check_type_size() to include mpi.h?

Body:
This is done via CMAKE_EXTRA_INCLUDE_FILES:

INCLUDE (CheckTypeSize)

find_package(MPI)
include_directories(SYSTEM ${MPI_INCLUDE_PATH})

SET(CMAKE_EXTRA_INCLUDE_FILES "mpi.h")
check_type_size("MPI_Offset" SIZEOF_MPI_OFFSET)
SET(CMAKE_EXTRA_INCLUDE_FILES)

It may be more common to write platform checks with autotools, so here is some more information on how to write platform checks with CMake.

On a personal note, while CMake is certainly not the most pleasant exercise, for me autotools is reserved for the capital sins. It is really hard to me to defend CMake, but in this instance, it is even documented. Naturally, setting a separate "variable" that you even have to reset after the fact, instead of just passing it as a parameter, is clearly conforming to the surprising "design principles" of CMake.


问:
No cookie in HTTP header
I have made a HttpConnection in BlackBerry. It has return me a successful login but I am unable to retrieve the cookie as there isn't one in the header. Does anyone know how I can get the cookie?

This is the code..

```<code>private String login(String URL)
{

    HttpConnection      httpConn = null;
    DataInputStream     dis = null;
    DataOutputStream    dos = null;
    StringBuffer        responseMessage = new StringBuffer();
    // the request body

    //Encode the login information in Base64 format.

    //String username = userName.getString();
    //String password = userPassWord.getString();
    // username = loginScreen.getUserId();
    //password = loginScreen.getPassword();
    try {
        // an HttpConnection with both read and write access
        net.rim.blackberry.api.browser.URLEncodedPostData login = new net.rim.blackberry.api.browser.URLEncodedPostData(null, false);
        login.append("username"); //field name , value
        login.append("password");
        httpConn = ( HttpConnection )Connector.open( URL, Connector.READ_WRITE );

        // set the request method to POST
        httpConn.setRequestMethod( HttpConnection.POST );
        httpConn.setRequestProperty(HttpProtocolConstants.HEADER_CONTENT_TYPE, HttpProtocolConstants.CONTENT_TYPE_APPLICATION_X_WWW_FORM_URLENCODED);
        httpConn.setRequestProperty("Accept", "text/html");

        // obtain DataOutputStream for sending the request string
        dos = httpConn.openDataOutputStream();
        byte[] request_body = login.getBytes();

        // send request string to server
        for( int i = 0; i < request_body.length; i++ ) {
            dos.writeByte( request_body[i] );
        }//end for( int i = 0; i < request_body.length; i++ )

        for (int i=0; ; i++) {
            String headerName = httpConn.getHeaderFieldKey(i);
            String headerValue = httpConn.getHeaderField(i);
            if (headerName == null && headerValue == null) {
                // No more headers
                break;
            } else
                responseMessage.append("headerName : " + headerName + ", headerValue : " + headerValue + "\n");
        }

        // obtain DataInputStream for receiving server response
        dis = new DataInputStream( httpConn.openInputStream() );

        // retrieve the response from server
        int data;
        tmpCookie = httpConn.getHeaderField("Set-Cookie");

        responseMessage.append("1st Cookie" + tmpCookie);
         if (tmpCookie != null) {
         int semicolon = tmpCookie.indexOf(';');
          cookie = tmpCookie.substring(0, semicolon);
             responseMessage.append("Cookie" + cookie);
            }

        responseMessage.append( "LOGIN RESPONSE :" );
        while( ( data = dis.read() ) != -1 ) {
            responseMessage.append((char)data  );

        }//end while( ( ch = dis.read() ) != -1 ) {

    }

    catch( Exception e )
    {
        e.printStackTrace();
        responseMessage.append( "ERROR" );
    }
    finally {
        // free up i/o streams and http connection
        try {
            if( httpConn != null ) httpConn.close();
            if( dis != null ) dis.close();
            if( dos != null ) dos.close();
        } catch ( IOException ioe ) {
            ioe.printStackTrace();
        }//end try/catch
    }//end try/catch/finally
    return responseMessage.toString();
}//end sendHttpPost( String )
</code>```

答:
Double check the service API. Maybe you're expecting something that doesn't exist (service doesn't use cookie) or maybe you didn't use the API as expected (service supports cookie but service request didn't ask for one).

Or, but the service API should tell it, the cookie is generate locally with javascript. In this case, you won't find a header entry and you'll have to execute the script code to set the cookie.

ContentLicense: CC BY-SA 2.5

Title: No cookie in HTTP header

Body:
I have made a HttpConnection in BlackBerry. It has return me a successful login but I am unable to retrieve the cookie as there isn't one in the header. Does anyone know how I can get the cookie?

This is the code..

private String login(String URL)
{

    HttpConnection      httpConn = null;
    DataInputStream     dis = null;
    DataOutputStream    dos = null;
    StringBuffer        responseMessage = new StringBuffer();
    // the request body

    //Encode the login information in Base64 format.

    //String username = userName.getString();
    //String password = userPassWord.getString();
    // username = loginScreen.getUserId();
    //password = loginScreen.getPassword();
    try {
        // an HttpConnection with both read and write access
        net.rim.blackberry.api.browser.URLEncodedPostData login = new net.rim.blackberry.api.browser.URLEncodedPostData(null, false);
        login.append("username"); //field name , value
        login.append("password");
        httpConn = ( HttpConnection )Connector.open( URL, Connector.READ_WRITE );

        // set the request method to POST
        httpConn.setRequestMethod( HttpConnection.POST );
        httpConn.setRequestProperty(HttpProtocolConstants.HEADER_CONTENT_TYPE, HttpProtocolConstants.CONTENT_TYPE_APPLICATION_X_WWW_FORM_URLENCODED);
        httpConn.setRequestProperty("Accept", "text/html");

        // obtain DataOutputStream for sending the request string
        dos = httpConn.openDataOutputStream();
        byte[] request_body = login.getBytes();

        // send request string to server
        for( int i = 0; i < request_body.length; i++ ) {
            dos.writeByte( request_body[i] );
        }//end for( int i = 0; i < request_body.length; i++ )

        for (int i=0; ; i++) {
            String headerName = httpConn.getHeaderFieldKey(i);
            String headerValue = httpConn.getHeaderField(i);
            if (headerName == null && headerValue == null) {
                // No more headers
                break;
            } else
                responseMessage.append("headerName : " + headerName + ", headerValue : " + headerValue + "\n");
        }

        // obtain DataInputStream for receiving server response
        dis = new DataInputStream( httpConn.openInputStream() );

        // retrieve the response from server
        int data;
        tmpCookie = httpConn.getHeaderField("Set-Cookie");

        responseMessage.append("1st Cookie" + tmpCookie);
         if (tmpCookie != null) {
         int semicolon = tmpCookie.indexOf(';');
          cookie = tmpCookie.substring(0, semicolon);
             responseMessage.append("Cookie" + cookie);
            }

        responseMessage.append( "LOGIN RESPONSE :" );
        while( ( data = dis.read() ) != -1 ) {
            responseMessage.append((char)data  );

        }//end while( ( ch = dis.read() ) != -1 ) {

    }

    catch( Exception e )
    {
        e.printStackTrace();
        responseMessage.append( "ERROR" );
    }
    finally {
        // free up i/o streams and http connection
        try {
            if( httpConn != null ) httpConn.close();
            if( dis != null ) dis.close();
            if( dos != null ) dos.close();
        } catch ( IOException ioe ) {
            ioe.printStackTrace();
        }//end try/catch
    }//end try/catch/finally
    return responseMessage.toString();
}//end sendHttpPost( String )


问:
Compile the Sass locally,
I’ve just got to grips with SASS and Compass and have been using it locally. Is there a simpler way of uploading the files online though? My natural instinct is to edit live files but it just doesn’t work with SASS.

How do people go about updating their live css files?

答:
In my opinion, the best set-up for doing Sass changes is to have a local environment that mimics your production environment. With a local environment you can keep Compass running as you make Sass changes, and you just need to refresh your local to see changes.

When you're happy with your changes, upload your compiled CSS to the server.

I'm sure there are ways to write and compile Sass on the server, but at that you're also introducing an easy way to blow up your site if you get a compiling error.

Depending on what your live environment is (static HTML pages, WordPress, Magento, etc.) there are different local environments that work best.

Static pages - You should be able to just work out of the browser with a set of files

WordPress - I prefer using Brad Parbs' Variable VVV

Magento - I prefer setting up Magento through MAMP

Title: Compile the Sass locally,


问:
Overwriting content of PHP file
I want to ovewrite some labeled data in PHP Config file which looks like this:

```<code>define("__dbhost__",                    '{DB_HOST}');
define("__dbname__",                    '{DB_NAME}');
define("__dbuser__",                    '{DB_USER}');
define("__dbpass__",                    '{DB_PASS}');
define("__dbport__",                    '{DB_PORT}');
</code>```

So the file is really simple.

The way i'm trying to replace data is by:

```<code>$searchF  = array('{DB_HOST}','{DB_NAME}','{DB_USER}','{DB_PASS}', '{DB_PORT}');
$replaceW = array('a','c','d','b','a');

$fname = "../app/config/database.php";
$fhandle = fopen($fname,"r");
$content = fread($fhandle,filesize($fname));
$content = str_replace($searchF, $replaceW, $content);

$fhandle = fopen($fname,"w");
fwrite($fhandle,$content);
fclose($fhandle);
</code>```

But once finished and after I open the file I get

```<code>Resource id #16
</code>```

Inside of it.

What's going on and why typical str_replace won't work for this case?

答:
Just read the entire file into a string:

```<code>$searchF  = array('{DB_HOST}','{DB_NAME}','{DB_USER}','{DB_PASS}', '{DB_PORT}');
$replaceW = array('a','c','d','b','a');

$fname = "../app/config/database.php";
$content = file_get_contents($fname);
$content = str_replace($searchF, $replaceW, $content);
file_put_contents($fname, $content);
</code>```

Read file into string

Replace on that string

Write string to file

Title: Overwriting content of PHP file

Body:
I want to ovewrite some labeled data in PHP Config file which looks like this:

define("__dbhost__",                    '{DB_HOST}');
define("__dbname__",                    '{DB_NAME}');
define("__dbuser__",                    '{DB_USER}');
define("__dbpass__",                    '{DB_PASS}');
define("__dbport__",                    '{DB_PORT}');

So the file is really simple.

The way i'm trying to replace data is by:

$searchF  = array('{DB_HOST}','{DB_NAME}','{DB_USER}','{DB_PASS}', '{DB_PORT}');
$replaceW = array('a','c','d','b','a');

$fname = "../app/config/database.php";
$fhandle = fopen($fname,"r");
$content = fread($fhandle,filesize($fname));
$content = str_replace($searchF, $replaceW, $content);

$fhandle = fopen($fname,"w");
fwrite($fhandle,$content);
fclose($fhandle);

But once finished and after I open the file I get

Resource id #16

Inside of it.

What's going on and why typical str_replace won't work for this case?

Body:
Just read the entire file into a string:

$searchF  = array('{DB_HOST}','{DB_NAME}','{DB_USER}','{DB_PASS}', '{DB_PORT}');
$replaceW = array('a','c','d','b','a');

$fname = "../app/config/database.php";
$content = file_get_contents($fname);
$content = str_replace($searchF, $replaceW, $content);
file_put_contents($fname, $content);

Read file into string

Replace on that string

Write string to file


问:
Define what makes a code section in rstudio
Rstudio changed how a code section is defined. In version 0.99.902 code sections had to have some text behind the hash symbol. But now in version 1.0.136 if there are 5 hashes in a row it will define a new section.

Is there anyway to make it go back to the old way of defining sections? It isn't a big deal except I would mark my sections with hashes above and below the name and now it is creating 3x as many sections.

Old version:

New version:

答:
I don't know if there's a way to recover the old behavior, but you could use + instead. In addition, you can put this in a code snippet (if you haven't already). In Preferences, go to the Code tab, scroll to the bottom and click the Edit Snippets button. Then add something like the following:

```<code>snippet hd
  `r "# ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
  ### HEAD ##########
  # ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++"`
</code>```

Then, when you type hd followed by a tab (actually two tabs, since the first tab will bring up a few options that start with hd, but hd will be at the top, so you can just press tab twice) in your R script file, the following will appear:

```<code># ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
### HEAD ##########
# ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
</code>```

Better yet, you can create a snippet that takes the heading text as an argument:

```<code>snippet hd
   `r paste("# ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++\n",
   "### ", "${1:HEAD}", " ##########\n",
   "# ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++", sep="")`
</code>```

Then, when you type hd followed by two tabs, the HEAD text will be highlighted and you can just type in your actual heading text.

Body:
I don't know if there's a way to recover the old behavior, but you could use + instead. In addition, you can put this in a code snippet (if you haven't already). In Preferences, go to the Code tab, scroll to the bottom and click the Edit Snippets button. Then add something like the following:

snippet hd
  `r "# ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
  ### HEAD ##########
  # ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++"`

Then, when you type hd followed by a tab (actually two tabs, since the first tab will bring up a few options that start with hd, but hd will be at the top, so you can just press tab twice) in your R script file, the following will appear:

# ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
### HEAD ##########
# ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++

Better yet, you can create a snippet that takes the heading text as an argument:

snippet hd
   `r paste("# ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++\n",
   "### ", "${1:HEAD}", " ##########\n",
   "# ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++", sep="")`

Then, when you type hd followed by two tabs, the HEAD text will be highlighted and you can just type in your actual heading text.


问:
Sending data throgh NamedPipe when server is down
I was wondering how to handle a situation where you successfully connected two processes through named pipe (one server and one client), and suddenly (for some reason) the server process ends.

What happens to the pipe? Does it close?
What happens to information being sent by the client to the server? Does it get lost?
How can the client know if the server is down?

All The Best,

Gil

答:
If you are using System.IO.Pipes and NamedPipeServerStream for example, you would get IOException when a pipe is broken or disconnected.

When you are using NamedPipeClientStream for reading in information from server, I believe the client would wait till a connection is established on the NamedPipeClientStream.Connect() call alternative you could use  NamedPipeClientStream.Connect(Int32) option to timeout a connection after a predetermined period. Apart from that the StreamReader.ReadLine() is also capable of throwing IOException when something does not go well.

The NamedPipeClientStream.IsConnected would be a simple way to determine if the client is connected successfully to the server or if it is disconnected, closed, or broken.


问:
Create a list based on nested For loops
Assume that I am using a client computer that will not allow for pip or pandas and must use Python 2.7. Binaries and converting into an exe is not allowed. I am reading in a CSV with column headers as names with numpy.

In my dataset, I am attempting to generate a list of orders that apply to unique combinations of Facility, Destination, Program #, and other factors, where p is the read csv dataset.

CSV starting out

What it would look like if I did this in Excel. The values in the Order field are what I'd like to have as a list in a variable called my_orders.

My current code looks like:

```<code>progs = np.unique(p['Program'])
facil = np.unique(p['Facility'])
dest = np.unique(p['Destination'])
reqs = np.unique(p['Requested'])
prods = np.unique(p['Produced'])
tier1 = np.unique(p['Tier1'])
tier2 = np.unique(p['Tier2'])
</code>```

Which is followed by the following method originally written with pandas and Python3 in mind until discovering that only 2.7 and numpy were available:

```<code>for a in range(len(progs)):
    print("on Program ",a)
    ProgChild = {"name":progs[a], 'children':[]}
    for r in range(len(reqs)):
        reqChild = {"name":reqs[r], 'children':[]}
        for s in range(len(prods)):
            prodChild = {'name':prods[s], "children":[]}
            for g in range(len(progs)):
                programChild = {'name':progs[g], "children":[]}
                for i in range(len(facil)):
                    FacilChild={"name":facil[i], "children":[]}
                    for c in range(len(tier1)):
                        Tier1Child={"name":tier1[c], "children":[]}
                        for d in range(len(tier2)):
                            # here's where I'm in trouble:
                            Order_Cond = np.array[[progs[a]& reqs[r]&
                                prods[s]&progs[g]& facil[i]& tier1[c]]
                            my_orders = np.where(p['Orders'], Order_cond)
                            print my_orders
                            # do other things
</code>```

As you can see the original intent was to use the For loops to set up a routine that only returned a list of Orders that came from unique combinations of facility, destination, program, etc. The Order_cond variable obviously has the wrong syntax.

If this were in SQL I'd just say "Select Orders From My_Data Where progs=a & reqs=r;" and so on.

I also considered a list comprehension but it doesn't work yet either:

```<code>list(x for p['Orders'] in p if p['Orders'] in Order_cond)
</code>```

Again, the goal is for a list of Orders to be created and stored in my_orders, which I then use for other functions.

答:
I haven't followed your whole nested if code, but here's a way of identifying records in an structured array that meet certain criteria

Make a sample array with 3 fields:

```<code>In [447]: dt = np.dtype('S10,S10,int')
In [448]: data = np.ones((10,),dt)
In [451]: data['f0']='one two three four five six seven eight nine ten'.split()
In [452]: data['f1']='a b c a b c a b c a'.split()
In [453]: data['f2']=np.arange(10)
In [454]: data
Out[454]:
array([(b'one', b'a', 0), (b'two', b'b', 1), (b'three', b'c', 2),
       (b'four', b'a', 3), (b'five', b'b', 4), (b'six', b'c', 5),
       (b'seven', b'a', 6), (b'eight', b'b', 7), (b'nine', b'c', 8),
       (b'ten', b'a', 9)],
      dtype=[('f0', 'S10'), ('f1', 'S10'), ('f2', '<i4')])
</code>```

Test one field:

```<code>In [461]: cond = data['f0']==b'three'
In [462]: cond
Out[462]: array([False, False,  True, False, False, False, False, False, False, False], dtype=bool)
</code>```

Another field with several matches:

```<code>In [463]: cond = data['f1']==b'c'
In [464]: cond
Out[464]: array([False, False,  True, False, False,  True, False, False,  True, False], dtype=bool)
</code>```

Combining several field tests:

```<code>In [465]: cond = (data['f1']==b'c') & (data['f0']==b'three') & (data['f2']==2)
In [466]: cond
Out[466]: array([False, False,  True, False, False, False, False, False, False, False], dtype=bool)
In [467]: data[cond]
Out[467]:
array([(b'three', b'c', 2)],
      dtype=[('f0', 'S10'), ('f1', 'S10'), ('f2', '<i4')])
</code>```

Or going the sql route:

```<code>In [468]: import sqlite3
In [469]: conn=sqlite3.connect(':memory:')
In [470]: cur = conn.cursor()
In [471]: cur.execute('''CREATE TABLE array (f0 str, f1 str, f2 int)''')
Out[471]: <sqlite3.Cursor at 0xaa0a38a0>
In [472]: cur.executemany("INSERT INTO array VALUES (?,?,?)",data)
</code>```

An element of data looks just like a tuple; so the insert is trivial.

```<code>Out[472]: <sqlite3.Cursor at 0xaa0a38a0>
In [473]: cur.execute('select * from array')
Out[473]: <sqlite3.Cursor at 0xaa0a38a0>
In [474]: cur.fetchall()
Out[474]:
[(b'one', b'a', b'\x00\x00\x00\x00'),
 (b'two', b'b', b'\x01\x00\x00\x00'),
 (b'three', b'c', b'\x02\x00\x00\x00'),
 ...
 (b'ten', b'a', b'\t\x00\x00\x00')]
In [486]: cur.execute('select * from array where f0==(?)',(b"four",))
Out[486]: <sqlite3.Cursor at 0xaa0a38a0>
In [487]: cur.fetchall()
    Out[487]: [(b'four', b'a', b'\x03\x00\x00\x00')]
In [488]: cur.execute('select * from array where f0==(?) or f1==(?)',(b"four",b"c"))
Out[488]: <sqlite3.Cursor at 0xaa0a38a0>
In [489]: cur.fetchall()
Out[489]:
[(b'three', b'c', b'\x02\x00\x00\x00'),
 (b'four', b'a', b'\x03\x00\x00\x00'),
 (b'six', b'c', b'\x05\x00\x00\x00'),
 (b'nine', b'c', b'\x08\x00\x00\x00')]
</code>```

This example needs to be cleaner, but it gives the rough idea of what's possible.

Title: Create a list based on nested For loops

Body:
Assume that I am using a client computer that will not allow for pip or pandas and must use Python 2.7. Binaries and converting into an exe is not allowed. I am reading in a CSV with column headers as names with numpy.

In my dataset, I am attempting to generate a list of orders that apply to unique combinations of Facility, Destination, Program #, and other factors, where p is the read csv dataset.

CSV starting out

What it would look like if I did this in Excel. The values in the Order field are what I'd like to have as a list in a variable called my_orders.

My current code looks like:

progs = np.unique(p['Program'])
facil = np.unique(p['Facility'])
dest = np.unique(p['Destination'])
reqs = np.unique(p['Requested'])
prods = np.unique(p['Produced'])
tier1 = np.unique(p['Tier1'])
tier2 = np.unique(p['Tier2'])

Which is followed by the following method originally written with pandas and Python3 in mind until discovering that only 2.7 and numpy were available:

for a in range(len(progs)):
    print("on Program ",a)
    ProgChild = {"name":progs[a], 'children':[]}
    for r in range(len(reqs)):
        reqChild = {"name":reqs[r], 'children':[]}
        for s in range(len(prods)):
            prodChild = {'name':prods[s], "children":[]}
            for g in range(len(progs)):
                programChild = {'name':progs[g], "children":[]}
                for i in range(len(facil)):
                    FacilChild={"name":facil[i], "children":[]}
                    for c in range(len(tier1)):
                        Tier1Child={"name":tier1[c], "children":[]}
                        for d in range(len(tier2)):
                            # here's where I'm in trouble:
                            Order_Cond = np.array[[progs[a]& reqs[r]&
                                prods[s]&progs[g]& facil[i]& tier1[c]]
                            my_orders = np.where(p['Orders'], Order_cond)
                            print my_orders
                            # do other things

As you can see the original intent was to use the For loops to set up a routine that only returned a list of Orders that came from unique combinations of facility, destination, program, etc. The Order_cond variable obviously has the wrong syntax.

If this were in SQL I'd just say "Select Orders From My_Data Where progs=a & reqs=r;" and so on.

I also considered a list comprehension but it doesn't work yet either:

list(x for p['Orders'] in p if p['Orders'] in Order_cond)

Again, the goal is for a list of Orders to be created and stored in my_orders, which I then use for other functions.

Body:
I haven't followed your whole nested if code, but here's a way of identifying records in an structured array that meet certain criteria

Make a sample array with 3 fields:

In [447]: dt = np.dtype('S10,S10,int')
In [448]: data = np.ones((10,),dt)
In [451]: data['f0']='one two three four five six seven eight nine ten'.split()
In [452]: data['f1']='a b c a b c a b c a'.split()
In [453]: data['f2']=np.arange(10)
In [454]: data
Out[454]:
array([(b'one', b'a', 0), (b'two', b'b', 1), (b'three', b'c', 2),
       (b'four', b'a', 3), (b'five', b'b', 4), (b'six', b'c', 5),
       (b'seven', b'a', 6), (b'eight', b'b', 7), (b'nine', b'c', 8),
       (b'ten', b'a', 9)],
      dtype=[('f0', 'S10'), ('f1', 'S10'), ('f2', '<i4')])

Test one field:

In [461]: cond = data['f0']==b'three'
In [462]: cond
Out[462]: array([False, False,  True, False, False, False, False, False, False, False], dtype=bool)

Another field with several matches:

In [463]: cond = data['f1']==b'c'
In [464]: cond
Out[464]: array([False, False,  True, False, False,  True, False, False,  True, False], dtype=bool)

Combining several field tests:

In [465]: cond = (data['f1']==b'c') & (data['f0']==b'three') & (data['f2']==2)
In [466]: cond
Out[466]: array([False, False,  True, False, False, False, False, False, False, False], dtype=bool)
In [467]: data[cond]
Out[467]:
array([(b'three', b'c', 2)],
      dtype=[('f0', 'S10'), ('f1', 'S10'), ('f2', '<i4')])

Or going the sql route:

In [468]: import sqlite3
In [469]: conn=sqlite3.connect(':memory:')
In [470]: cur = conn.cursor()
In [471]: cur.execute('''CREATE TABLE array (f0 str, f1 str, f2 int)''')
Out[471]: <sqlite3.Cursor at 0xaa0a38a0>
In [472]: cur.executemany("INSERT INTO array VALUES (?,?,?)",data)

An element of data looks just like a tuple; so the insert is trivial.

Out[472]: <sqlite3.Cursor at 0xaa0a38a0>
In [473]: cur.execute('select * from array')
Out[473]: <sqlite3.Cursor at 0xaa0a38a0>
In [474]: cur.fetchall()
Out[474]:
[(b'one', b'a', b'\x00\x00\x00\x00'),
 (b'two', b'b', b'\x01\x00\x00\x00'),
 (b'three', b'c', b'\x02\x00\x00\x00'),
 ...
 (b'ten', b'a', b'\t\x00\x00\x00')]
In [486]: cur.execute('select * from array where f0==(?)',(b"four",))
Out[486]: <sqlite3.Cursor at 0xaa0a38a0>
In [487]: cur.fetchall()
    Out[487]: [(b'four', b'a', b'\x03\x00\x00\x00')]
In [488]: cur.execute('select * from array where f0==(?) or f1==(?)',(b"four",b"c"))
Out[488]: <sqlite3.Cursor at 0xaa0a38a0>
In [489]: cur.fetchall()
Out[489]:
[(b'three', b'c', b'\x02\x00\x00\x00'),
 (b'four', b'a', b'\x03\x00\x00\x00'),
 (b'six', b'c', b'\x05\x00\x00\x00'),
 (b'nine', b'c', b'\x08\x00\x00\x00')]

This example needs to be cleaner, but it gives the rough idea of what's possible.


问:
Using MDM To Configure An Enterprise App Via NSUserDefaults
I'm using Profile Manager in OS X Server 3.0.1 on 10.9 to push my enterprise app to a managed device running iOS7.  This is working well, and I am also able to push device configuration settings.

My roadblock is how to take the information offered in Apple's example project, ManagedAppConfig, and apply it to an app distributed by Profile Manager.

ManagedAppConfig provides a simple plist which is supposed to be used to put data into an app's NSUserDefaults, which is then used for app configuration; but, there is no direction given for how to use MDM to get this data dictionary into the NSUserDefaults.

I am obviously missing a piece of information for how to send a plist of data to a managed app's NSUSerDefaults, but so far my searching has been fruitless.  Is it possible to to this with Profile Manager?  Is there another way with OS X Server that I haven't yet found?

Here's a quote from Apple's doc on ManagedAppConfig:

"ManagedAppConfig" demonstrates how to implement managed app
  configuration and feedback support in an iOS application. This
  functionality allows a Mobile Device Management (MDM) server to push
  down a dictionary into the managed app's NSUserDefaults for the
  purposes of remotely configuring settings.

Here's the example plist with the two pieces of data which are somehow placed in the app's NSUserDefaults:

```<code><?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
    <key>serverURL</key>
    <string>http://developer.apple.com/</string>
    <key>disableCloudDocumentSync</key>
    <true/>
</dict>
</plist>
</code>```

The docs for NSUserDefaults even mention configuration via MDM, but no specifics are given.

If your application supports managed environments, you can use an
  NSUserDefaults object to determine which preferences are managed by an
  administrator for the benefit of the user. Managed environments
  correspond to computer labs or classrooms where an administrator or
  teacher may want to configure the systems in a particular way. In
  these situations, the teacher can establish a set of default
  preferences and force those preferences on users. If a preference is
  managed in this manner, applications should prevent users from editing
  that preference by disabling any appropriate controls.

My afternoon has been spent pursuing this elusive piece of info without success, so I ask the assistance of the SO community.  Can anyone point me to the info I need to use MDM to stick a dictionary of data into NSUserDefaults?

Many Thanks.

答:
to read the config (swift 3):

```<code>if let managedConf = UserDefaults.standard.object(forKey: "com.apple.configuration.managed") as? [String:Any?] {
    if let serverURL = managedConf["serverURL"] as? String{
        return serverURL
    }
}
if let serverURL = Bundle.main.object(forInfoDictionaryKey: "serverURL") as? String {
    return serverURL
}
return  "https://apple.com/"
</code>```

as you can see - the app needs to manually enable reading from MDM bundle configuration.

P,S:
only managed apps can get those configs.

Body:
I'm using Profile Manager in OS X Server 3.0.1 on 10.9 to push my enterprise app to a managed device running iOS7.  This is working well, and I am also able to push device configuration settings.

My roadblock is how to take the information offered in Apple's example project, ManagedAppConfig, and apply it to an app distributed by Profile Manager.

ManagedAppConfig provides a simple plist which is supposed to be used to put data into an app's NSUserDefaults, which is then used for app configuration; but, there is no direction given for how to use MDM to get this data dictionary into the NSUserDefaults.

I am obviously missing a piece of information for how to send a plist of data to a managed app's NSUSerDefaults, but so far my searching has been fruitless.  Is it possible to to this with Profile Manager?  Is there another way with OS X Server that I haven't yet found?

Here's a quote from Apple's doc on ManagedAppConfig:

"ManagedAppConfig" demonstrates how to implement managed app
  configuration and feedback support in an iOS application. This
  functionality allows a Mobile Device Management (MDM) server to push
  down a dictionary into the managed app's NSUserDefaults for the
  purposes of remotely configuring settings.

Here's the example plist with the two pieces of data which are somehow placed in the app's NSUserDefaults:

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
    <key>serverURL</key>
    <string>http://developer.apple.com/</string>
    <key>disableCloudDocumentSync</key>
    <true/>
</dict>
</plist>

The docs for NSUserDefaults even mention configuration via MDM, but no specifics are given.

If your application supports managed environments, you can use an
  NSUserDefaults object to determine which preferences are managed by an
  administrator for the benefit of the user. Managed environments
  correspond to computer labs or classrooms where an administrator or
  teacher may want to configure the systems in a particular way. In
  these situations, the teacher can establish a set of default
  preferences and force those preferences on users. If a preference is
  managed in this manner, applications should prevent users from editing
  that preference by disabling any appropriate controls.

My afternoon has been spent pursuing this elusive piece of info without success, so I ask the assistance of the SO community.  Can anyone point me to the info I need to use MDM to stick a dictionary of data into NSUserDefaults?

Many Thanks.

Body:
to read the config (swift 3):

if let managedConf = UserDefaults.standard.object(forKey: "com.apple.configuration.managed") as? [String:Any?] {
    if let serverURL = managedConf["serverURL"] as? String{
        return serverURL
    }
}
if let serverURL = Bundle.main.object(forInfoDictionaryKey: "serverURL") as? String {
    return serverURL
}
return  "https://apple.com/"

as you can see - the app needs to manually enable reading from MDM bundle configuration.

P,S:
only managed apps can get those configs.


问:
Json Deserialize C#
I want to parsing this json file.

{"features":[{"type":"Feature","geometry":{"type":"Polygon","coordinates":[[[26.4217861898109,40.127607984644],[26.4219934821323,40.1275230229872],[26.4218810759267,40.1273800013679],[26.4216801413981,40.1274730404221],[26.4217861898109,40.127607984644]]]},"properties":{"ParselNo":"1","Alan":"340.48
  m2","Mevkii":"-","Nitelik":"Arsa","Ada":"698","Il":"Çanakkale","Ilce":"Merkez","Pafta":"16","Mahalle":"Barbaros"}}],"type":"FeatureCollection","crs":{"type":"name","properties":{"name":"EPSG:4326"}}}

I try this code:

```<code>string fileName = file.FileName;
string json = System.IO.File.ReadAllText(fileName);
dynamic stuff = JsonConvert.DeserializeObject(json);

string s1 = Convert.ToString(stuff.features.Count);
string s2 = stuff.properties.ParselNo;
MessageBox.Show(s1);
MessageBox.Show(s2);
</code>```

s1 is working but s2 give error. How can I fix it?

I want to get it like this:

```<code>Coordinates[] coordinates = [(26.xx, 40.xx), (26.xx,40.xx) ... ]
ParselNo = 1
Alan = 340.48
Nitelik = Arsa
Ada = 698
İl = Çanakkale
İlçe = Merkez
Pafta = 16
dat_name = EPSG:4326
</code>```

what can i do?

答:
I try this:

```<code> string s2 = stuff.features.properties.ParselNo;
 MessageBox.Show(s2);
</code>```

give this error:
Error...

Title: Json Deserialize C#

Body:
I want to parsing this json file.

{"features":[{"type":"Feature","geometry":{"type":"Polygon","coordinates":[[[26.4217861898109,40.127607984644],[26.4219934821323,40.1275230229872],[26.4218810759267,40.1273800013679],[26.4216801413981,40.1274730404221],[26.4217861898109,40.127607984644]]]},"properties":{"ParselNo":"1","Alan":"340.48
  m2","Mevkii":"-","Nitelik":"Arsa","Ada":"698","Il":"Çanakkale","Ilce":"Merkez","Pafta":"16","Mahalle":"Barbaros"}}],"type":"FeatureCollection","crs":{"type":"name","properties":{"name":"EPSG:4326"}}}

I try this code:

string fileName = file.FileName;
string json = System.IO.File.ReadAllText(fileName);
dynamic stuff = JsonConvert.DeserializeObject(json);

string s1 = Convert.ToString(stuff.features.Count);
string s2 = stuff.properties.ParselNo;
MessageBox.Show(s1);
MessageBox.Show(s2);

s1 is working but s2 give error. How can I fix it?

I want to get it like this:

Coordinates[] coordinates = [(26.xx, 40.xx), (26.xx,40.xx) ... ]
ParselNo = 1
Alan = 340.48
Nitelik = Arsa
Ada = 698
İl = Çanakkale
İlçe = Merkez
Pafta = 16
dat_name = EPSG:4326

what can i do?

Body:
I try this:

 string s2 = stuff.features.properties.ParselNo;
 MessageBox.Show(s2);

give this error:
Error...


问:
Set timeout to WS https call in Spring (HttpsUrlConnectionMessageSender)
I am trying to set timeout for WS call. I extended WebServiceGatewaySupport and was trying to set to Sender timeout like this:

```<code>public Object marshalSendAndReceive(Object requestPayload) {

        WebServiceTemplate wsTemplate = this.getWebServiceTemplate();
        for (WebServiceMessageSender sender : wsTemplate.getMessageSenders()) {
            try {
                HttpComponentsMessageSender httpSender = (HttpComponentsMessageSender) sender;
                httpSender.setReadTimeout(3000);
                httpSender.setConnectionTimeout(2000);
            } catch (ClassCastException | NumberFormatException cex) {
                logger.warn("Cannot set WS timeout: " + cex.getMessage());
            }
        }

        return wsTemplate.marshalSendAndReceive(requestPayload);
    }
</code>```

(credit to question #6733744)

However I get: Cannot set WS timeout: org.springframework.ws.transport.http.HttpsUrlConnectionMessageSender cannot be cast to org.springframework.ws.transport.http.HttpComponentsMessageSender

Can timeout be set to HttpsUrlConnectionMessageSender somehow? Or is there any other way to set timeout to https ws call in spring-boot?

Thank you.

答: You're getting a cast exception because HttpsUrlConnectionMessageSender  and HttpComponentsMessageSender are not compatible types. They both share the same superclass (WebServiceMessageSender), but you can't cast one to the other. I think you can just use a HttpComponentsMessageSender in your WebServiceTemplate configuration.  See How to set timeout in Spring WebServiceTemplate and Spring webServiceTemplate connection timeout property</p>

Body:
I am trying to set timeout for WS call. I extended WebServiceGatewaySupport and was trying to set to Sender timeout like this:

public Object marshalSendAndReceive(Object requestPayload) {

        WebServiceTemplate wsTemplate = this.getWebServiceTemplate();
        for (WebServiceMessageSender sender : wsTemplate.getMessageSenders()) {
            try {
                HttpComponentsMessageSender httpSender = (HttpComponentsMessageSender) sender;
                httpSender.setReadTimeout(3000);
                httpSender.setConnectionTimeout(2000);
            } catch (ClassCastException | NumberFormatException cex) {
                logger.warn("Cannot set WS timeout: " + cex.getMessage());
            }
        }

        return wsTemplate.marshalSendAndReceive(requestPayload);
    }

(credit to question #6733744)

However I get: Cannot set WS timeout: org.springframework.ws.transport.http.HttpsUrlConnectionMessageSender cannot be cast to org.springframework.ws.transport.http.HttpComponentsMessageSender

Can timeout be set to HttpsUrlConnectionMessageSender somehow? Or is there any other way to set timeout to https ws call in spring-boot?

Thank you.


问:
How to authorize 000webhost posts?
I am using curl in php to post data from my local server to a webhost server:

```<code>  $post = array('test' => 'this is a test' );
    $url = "https://my-app.000webhostapp.com";
            $curlSesh = curl_init();
            curl_setopt($curlSesh, CURLOPT_URL, $url);
            curl_setopt($curlSesh, CURLOPT_POST, true);
            curl_setopt($curlSesh, CURLOPT_POSTFIELDS, $post);
            curl_setopt($curlSesh, CURLOPT_RETURNTRANSFER, true);
            $response = curl_exec($curlSesh);
            curl_close($curlSesh);
            echo "response: ";
            echo $response;
            if ($response == "validate post")echo ' post has been validated';
</code>```

On my 000webhost server, I accept the array sent in $post using file put contents:

```<code>file_put_contents('incomingData.txt', $_POST["test"]. "\n", FILE_APPEND );
</code>```

Surely this means that anyone can send a post request to my webhost server with an array key 'test' and that will be placed in my incomingData.txt file? This is extremely unsecure. Is there a way to make it so only my local server data is accepted, or maybe can I encrypt the data in some way? Thanks.

答:
To authenticate your data received by your Curl request, beyond reasonable doubt as to its authenticity, you can use HMAC system which is a Hash-based Message Authentication Code and is also what TLS (https) uses to verify the data receieved is the same as the data sent in a transfer.

An HMAC is a small set of data that helps authenticate the nature of message; it protects the integrity (and by extension the authenticity) of the message.

The method is this:

Collect your data you are sending into a single string/array/object value.

Add a secret key

Create a Hash of the combined data + secret key. This is the HMAC

Send the data "payload" and the HMAC to the receiver.

Do NOT send the secret key.

Receiver then collects the Payload, and adds its own copy of the secret key and generates a hash, as the sender did.

If the local HMAC is equal to the HMAC sent over the wise, this shows that the payload data sent is the same as the payload data received.

A BIG advantage to this method is that unlike ma11ocs answer your secret key is never shared or transported in the data (payload) it is protecting.

The secret key is a unique piece of information that is used to compute the HMAC and is known both by the sender and the receiver of the message but is never sent within the message. This key will vary in length depending on the algorithm that you use. Some algorithms are better than others, some such as MD5 should not be used as they're too fast and easily researched.

Links

HMAC

Online HMAC generator tool

Best HMAC hashes to use

A post about Curl and PHP and SSL

Title: How to authorize 000webhost posts?

Body:
I am using curl in php to post data from my local server to a webhost server:

  $post = array('test' => 'this is a test' );
    $url = "https://my-app.000webhostapp.com";
            $curlSesh = curl_init();
            curl_setopt($curlSesh, CURLOPT_URL, $url);
            curl_setopt($curlSesh, CURLOPT_POST, true);
            curl_setopt($curlSesh, CURLOPT_POSTFIELDS, $post);
            curl_setopt($curlSesh, CURLOPT_RETURNTRANSFER, true);
            $response = curl_exec($curlSesh);
            curl_close($curlSesh);
            echo "response: ";
            echo $response;
            if ($response == "validate post")echo ' post has been validated';

On my 000webhost server, I accept the array sent in $post using file put contents:

file_put_contents('incomingData.txt', $_POST["test"]. "\n", FILE_APPEND );

Surely this means that anyone can send a post request to my webhost server with an array key 'test' and that will be placed in my incomingData.txt file? This is extremely unsecure. Is there a way to make it so only my local server data is accepted, or maybe can I encrypt the data in some way? Thanks.


问:
How to copy column data from one sheet and then copy that to another sheet in vba excel
I need help with this small project. What I need to accomplished this task is the following:

I have a excel file where my macro button once clicked will read the data from a sheet1 only in column A then should throw the data to another sheet2 and move every data from the sheet1 to sheet2 and display all the data to each separate column.

here is a image of the data example. in the image every circle needs to be in its own column to the new sheet2 that is only part of the data the total of the column rows is around 900.

if need more information please let me know.

here is the code I have it copy the sheet from sheet1 to sheet2 but I need the rest to work

```<code>Sub ExportFile()
Dim strValue As String
Dim strCellNum As String
Dim x As String
x = 1

For i = 1 To 700 Step 7
    strCellNum = "A" & i
    strValue = Worksheets("data").Range(strCellNum).Value
    Debug.Print strValue
    Worksheets("NewData").Range("A" & x).Value = strValue
    x = x + 1
Next
End Sub
</code>```

答:
you can try this:</p>

```<code>Sub ExportFile()
    Dim area As Range
    Dim icol As Long

    With Worksheets("data")
        With .Range("A1", .Cells(.Rows.Count, 1).End(xlUp)).SpecialCells(xlCellTypeConstants)
            For Each area In .Areas
                icol = icol + 1
                Worksheets("NewData").Cells(1, icol).Resize(area.Rows.Count).Value = area.Value
            Next
        End With
    End With
End Sub
</code>```

Body:
I need help with this small project. What I need to accomplished this task is the following:

I have a excel file where my macro button once clicked will read the data from a sheet1 only in column A then should throw the data to another sheet2 and move every data from the sheet1 to sheet2 and display all the data to each separate column.

here is a image of the data example. in the image every circle needs to be in its own column to the new sheet2 that is only part of the data the total of the column rows is around 900.

if need more information please let me know.

here is the code I have it copy the sheet from sheet1 to sheet2 but I need the rest to work

Sub ExportFile()
Dim strValue As String
Dim strCellNum As String
Dim x As String
x = 1

For i = 1 To 700 Step 7
    strCellNum = "A" & i
    strValue = Worksheets("data").Range(strCellNum).Value
    Debug.Print strValue
    Worksheets("NewData").Range("A" & x).Value = strValue
    x = x + 1
Next
End Sub

Body:
you can try this:

Sub ExportFile()
    Dim area As Range
    Dim icol As Long

    With Worksheets("data")
        With .Range("A1", .Cells(.Rows.Count, 1).End(xlUp)).SpecialCells(xlCellTypeConstants)
            For Each area In .Areas
                icol = icol + 1
                Worksheets("NewData").Cells(1, icol).Resize(area.Rows.Count).Value = area.Value
            Next
        End With
    End With
End Sub


问:
Scrape .txt table from URL in R
Here is the URL:

```<code>https://www.bls.gov/lau/laucnty15.txt
</code>```

Unfortunately, I think the problem is that the table is tab-delimited but values are not delimited by quotes ("").  So I don't know how I would strip out values using spaces without breaking apart the county name, for example.

I have tried:

```<code>webData <- data.frame(read.table(usrWebsiteURL,sep="\t",skip=5,header=F))

webData <- data.frame(readLines(usrWebsiteURL)),sep="\t",skip=5,header=F)
</code>```

Either method creates a large, 1-column data.frame.

Why is the sep="\t" not working?  Worse-case scenario, I can accept a split apart County Name and put it back together later, but I can't even achieve splitting apart the words in the table.

答:
This code, using the readr (from CRAN) package worked for me:

```<code>    readr::read_table("https://www.bls.gov/lau/laucnty15.txt", skip = 6, col_names = FALSE)
</code>```

You would probably want to add the column names after reading the file, but this can be done manually, eg., by using

```<code>    dat <- readr::read_table("https://www.bls.gov/lau/laucnty15.txt", skip = 6, col_names = FALSE)
    colnames(dat) <- c("LAUS Code", "State FIPS Code", "County FIPS Code", "County name", "Year", "Labor Force", "Employed", "Unemployed Level", "Unemployed Rate")
</code>```

Title: Scrape .txt table from URL in R

Body:
Here is the URL:

https://www.bls.gov/lau/laucnty15.txt

Unfortunately, I think the problem is that the table is tab-delimited but values are not delimited by quotes ("").  So I don't know how I would strip out values using spaces without breaking apart the county name, for example.

I have tried:

webData <- data.frame(read.table(usrWebsiteURL,sep="\t",skip=5,header=F))

webData <- data.frame(readLines(usrWebsiteURL)),sep="\t",skip=5,header=F)

Either method creates a large, 1-column data.frame.

Why is the sep="\t" not working?  Worse-case scenario, I can accept a split apart County Name and put it back together later, but I can't even achieve splitting apart the words in the table.

Body:
This code, using the readr (from CRAN) package worked for me:

    readr::read_table("https://www.bls.gov/lau/laucnty15.txt", skip = 6, col_names = FALSE)

You would probably want to add the column names after reading the file, but this can be done manually, eg., by using

    dat <- readr::read_table("https://www.bls.gov/lau/laucnty15.txt", skip = 6, col_names = FALSE)
    colnames(dat) <- c("LAUS Code", "State FIPS Code", "County FIPS Code", "County name", "Year", "Labor Force", "Employed", "Unemployed Level", "Unemployed Rate")


问:
Find in string with Excel and VBA?
I have a spreadsheet with a few worksheets in it, one being Product Inventory and one being Material Inventory...

I am trying to figure out how I can have another worksheet to where I can look up a product code, pull the description out of Product Inventory, and extract materials needed from Material Inventory. I know how to do this in other languages, but I'm extremely limited to just Excel and I don't know how to go about it.

Say I have Product Lookup:$B$2 = "ps26k417", which I already have pulling info from Product Inventory which pulls the item description, Garden Gate Indigo/Linen Natural 26x26 KE Fiber Pillow* But now I need to figure out how to pull from Material Inventory..

From that product description, I need to pull two rows out of the Material Inventory sheet.. I need a way to extract info based on the description, in this example I need the row for 417 Garden Gate Indigo/Linen and the row for 554 Linen Natural/S Backed

Is it even worth going this in-depth in an Excel macro?

答:
If each result from the ProductInventory sheet translates into exactly two entries on the MaterialInventory sheet, the simplest option would be to use two VLOOKUPS formulae.

If you'd like to go down the VBA route, you'll probably need code like the following:

```<code>Public Sub SearchForMaterial(materials() As String)
    Dim N As Long
    Dim materialsList As Range
    Set materialsList = ' Set to the relevant range

    Dim cell As Range

    Dim output(UBound(materials) - LBound(materials)) As String
    Dim outputCount As Long

    For N = LBound(materials) To UBound(materials)
        For Each cell In materialsList.Cells
            If cell.Value = materialsList(N) Then
                output(outputCount) = cell.Offset(ColumnOffset:= ??)
            End If
        Next cell
    Next N
End Sub
</code>```

This code isn't particularly efficient. You say that you have experience in other languages, so hopefully this should be enough to get you started.

Title: Find in string with Excel and VBA?

Body:
If each result from the ProductInventory sheet translates into exactly two entries on the MaterialInventory sheet, the simplest option would be to use two VLOOKUPS formulae.

If you'd like to go down the VBA route, you'll probably need code like the following:

Public Sub SearchForMaterial(materials() As String)
    Dim N As Long
    Dim materialsList As Range
    Set materialsList = ' Set to the relevant range

    Dim cell As Range

    Dim output(UBound(materials) - LBound(materials)) As String
    Dim outputCount As Long

    For N = LBound(materials) To UBound(materials)
        For Each cell In materialsList.Cells
            If cell.Value = materialsList(N) Then
                output(outputCount) = cell.Offset(ColumnOffset:= ??)
            End If
        Next cell
    Next N
End Sub

This code isn't particularly efficient. You say that you have experience in other languages, so hopefully this should be enough to get you started.


问:
Is it possible to attach Google Cloud Persistent Disk to a Job in Kubernetes?
I searched the documents. I wrote a job descripiton and deployed it but the disk did not show up in Kubernetes Dashboard.

Is it possible to attach Google Cloud Persistent Disk to a Job in Kubernetes?

Update: Here is the definition file. The disk site1-disk exists:

```<code>apiVersion: batch/v1
kind: Job
metadata:
  name: page-retriever
spec:
  template:
    metadata:
      name: page-retriever
    spec:
      containers:
      - name: page-retriever
        image: eu.gcr.io/crawler-162906/page-retriever:v1
      restartPolicy: OnFailure
      volumes:
          - name: page-retriver-first-persistent-storage
            gcePersistentDisk:
              # This disk must already exist.
              pdName: site1-disk
              fsType: ext4
</code>```

答:
You absolutely can. It looks like you're just missing the volumeMounts section of your container def:

```<code>apiVersion: batch/v1
kind: Job
metadata:
  name: page-retriever
spec:
  template:
    metadata:
      name: page-retriever
    spec:
      containers:
      - name: page-retriever
        image: eu.gcr.io/crawler-162906/page-retriever:v1
        volumeMounts:
        - name: page-retriver-first-persistent-storage
          mountPath: /path/to/where/the/disk/will/be/mounted/in/container

      restartPolicy: OnFailure

      volumes:
          - name: page-retriver-first-persistent-storage
            gcePersistentDisk:
              # This disk must already exist.
              pdName: site1-disk
              fsType: ext4
</code>```

without that, the volume 'page-retrier-first-persistent-storage' has no relationship to the container 'page-retriever'

Body:
I searched the documents. I wrote a job descripiton and deployed it but the disk did not show up in Kubernetes Dashboard.

Is it possible to attach Google Cloud Persistent Disk to a Job in Kubernetes?

Update: Here is the definition file. The disk site1-disk exists:

apiVersion: batch/v1
kind: Job
metadata:
  name: page-retriever
spec:
  template:
    metadata:
      name: page-retriever
    spec:
      containers:
      - name: page-retriever
        image: eu.gcr.io/crawler-162906/page-retriever:v1
      restartPolicy: OnFailure
      volumes:
          - name: page-retriver-first-persistent-storage
            gcePersistentDisk:
              # This disk must already exist.
              pdName: site1-disk
              fsType: ext4

Body:
You absolutely can. It looks like you're just missing the volumeMounts section of your container def:

apiVersion: batch/v1
kind: Job
metadata:
  name: page-retriever
spec:
  template:
    metadata:
      name: page-retriever
    spec:
      containers:
      - name: page-retriever
        image: eu.gcr.io/crawler-162906/page-retriever:v1
        volumeMounts:
        - name: page-retriver-first-persistent-storage
          mountPath: /path/to/where/the/disk/will/be/mounted/in/container

      restartPolicy: OnFailure

      volumes:
          - name: page-retriver-first-persistent-storage
            gcePersistentDisk:
              # This disk must already exist.
              pdName: site1-disk
              fsType: ext4

without that, the volume 'page-retrier-first-persistent-storage' has no relationship to the container 'page-retriever'


问:
D3.js code not rendering in browser when loaded from file, but works fine in console
I'm using Rails 4.0beta and I have the following d3.js script at the bottom of the body section. When pasted directly into the Chrome developer tools console, the code generates the graph. But if it is just as a script in the file that gets sent from the server to render the page, it doesn't generate the graph. Anyone know why? I must be making some simple mistake ... just can't figure out where.</p>

```<code><script type="text/javascript" src="http://d3js.org/d3.v3.min.js">
function generateGraph() {
    var margin = {top: 30, right: 20, bottom: 30, left: 50},
            width = 600 - margin.left - margin.right,
            height = 270 - margin.top - margin.bottom;

    var parseDate = d3.time.format("%d-%b-%y").parse;

    var x = d3.time.scale().range([0, width]);
    var y = d3.scale.linear().range([height, 0]);

    var xAxis = d3.svg.axis().scale(x).orient("bottom").ticks(5);
    var yAxis = d3.svg.axis().scale(y).orient("left").ticks(5);

    var valueline = d3.svg.line().x(function(d) { return x(d.date); }).y(function(d) { return y(d.load_volume); });

    var svg = d3.select("body").append("svg")
                .attr("width", width + margin.left + margin.right)
                .attr("height", height + margin.top + margin.bottom)
                .append("g").attr("transform", "translate(" + margin.left + "," + margin.top + ")");

    d3.json("/users/5/workouts/analyze.json", function(error, data) {
    data.forEach( function (d) {
       d.date = parseDate(d.date);
       d.load_volume = +d.load_volume;
    });
        // Scale the range of the data
        x.domain(d3.extent(data, function(d) { return d.date; }));
        y.domain([0, d3.max(data, function(d) { return d.load_volume; })]);

        svg.append("path").attr("d", valueline(data));                                              // Add the valueline path
        svg.append("g").attr("transform", "translate(0," + height + ")") .call(xAxis);  // Add the X Axis .attr("class", "x axis")
        svg.append("g").attr("class", "y axis").call(yAxis);                                        // Add the Y Axis

    });
};

generateGraph();

</script>
</code>```

答:
Create another script tag inside body tag, and call the function from that script tag. i.e.</p>

```<code><script>
function generateGraph() {
// function definition
}
</script>

<body>
<script>
generateGraph();
</script>
</body>
</code>```

Body:
Create another script tag inside body tag, and call the function from that script tag. i.e.

<script>
function generateGraph() {
// function definition
}
</script>

<body>
<script>
generateGraph();
</script>
</body>


问:
How to make Firebase rest api call from android when database security is set
How to authenticate against the Firebase rest api from Android when I have this
database rule:

```<code>"TOY_STORE": {
  ".read": "auth != null",
  ".write": "auth != null"
},
</code>```

If I set the ".read": "true" I can access a nod using this code

```<code> com.loopj.android.http.AsyncHttpClient client = new AsyncHttpClient();
    client.get("https://xxx-project.firebaseio.com/TOY_STORE/.json?print=pretty&shallow=true?auth=HnhLyXRxUsadhj237eYiQ53",  new JsonHttpResponseHandler() {

// respons..
}
</code>```

But when having ".read": "auth != null" it gíve permission denied.

Im signed in to Firebase usning Google credentials and the auth=HnhLyXRxUsadhj237eYiQ53 is my Firebase ID. I can read and write to database making regularly ValueEventListener and updateChildren calls.

I have also tried the Web API Key for auth but not working.

I want to run this code because of the Firebase REST API shallow-data

答:
If you want to read from firebase by rule ".read": "auth != null" and you do not want to use firebase api I recommend Retrofit2 library. You have to auth by Bearer service account token.

Warning! The token is valid only for one hour. Then you need to refresh the new token.

```<code>@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

....

//mykey.json you get from FBconsole/Project Settings/service accounts/generte new private key

    myFile = new File(mykey.json);

    GoogleCredential googleCred = null;
    try {
        googleCred = GoogleCredential.fromStream(new FileInputStream(myFile));
    } catch (IOException e) {
        e.printStackTrace();
    }
    GoogleCredential scoped = googleCred.createScoped(
            Arrays.asList(
                    "https://www.googleapis.com/auth/firebase.database",
                    "https://www.googleapis.com/auth/userinfo.email"
            )
    );
    try {
        scoped.refreshToken();
    } catch (IOException e) {
        e.printStackTrace();
    }
    token = scoped.getAccessToken();
    Log.d("token ", token);

}//end of oncreate
</code>```

Button click for read from FB

```<code>public void onClick(View view) {

    authtoken = "Bearer " + token;

    HttpLoggingInterceptor logging = new HttpLoggingInterceptor();
    logging.setLevel(HttpLoggingInterceptor.Level.BODY);

    OkHttpClient.Builder httpClient = new OkHttpClient.Builder();
    httpClient.addInterceptor(new Interceptor() {
        @Override
        public okhttp3.Response intercept(Chain chain) throws IOException {
            Request original = chain.request();

            // Request customization: add request headers
            Request.Builder requestBuilder = original.newBuilder()
                    .header("Authorization", authtoken); // <-- this is the important line
            Request request = requestBuilder.build();
            return chain.proceed(request);
        }
    });

    httpClient.addInterceptor(logging);
    OkHttpClient client = httpClient.build();

    Retrofit retrofit = new Retrofit.Builder()
            .baseUrl("https://yourproject.firebaseio.com")//url of firebase database app
            .client(client)
            .addConverterFactory(GsonConverterFactory.create())//use for convert JSON file into object
            .build();

    // prepare call in Retrofit 2.0
    FirebaseAPI firebaseAPI = retrofit.create(FirebaseAPI.class);

    Call<Event> call2=firebaseAPI.getPrivateData();

    call2.enqueue(new Callback<Event>() {
        @Override
        public void onResponse(Call<Event> call, Response<Event> response) {

            Log.d("Response ", "onResponse");
            //t1.setText("success name "+response.body().getName());

        }

        @Override
        public void onFailure(Call<Event> call, Throwable t) {
            Log.d("Response ", "onFailure");
            //t1.setText("Notification failure");
        }
    });
}
</code>```

FirebaseAPI.java

```<code>public interface FirebaseAPI {

@GET("/uploadprivate/event.json")
Call<Event> getPrivateData();

}
</code>```

POJO event.java

```<code>public class Event {
String name;
String address;

public Event(String name, String address) {
    this.address = address;
    this.name = name;
}

public String getName() {
    return name;
}

public void setName(String name) {
    this.name = name;
}

public String getAddress() {
    return address;
}

public void setAddress(String address) {
    this.address = address;
}

}
</code>```

Data in FB console

Body:
How to authenticate against the Firebase rest api from Android when I have this
database rule:

"TOY_STORE": {
  ".read": "auth != null",
  ".write": "auth != null"
},

If I set the ".read": "true" I can access a nod using this code

 com.loopj.android.http.AsyncHttpClient client = new AsyncHttpClient();
    client.get("https://xxx-project.firebaseio.com/TOY_STORE/.json?print=pretty&shallow=true?auth=HnhLyXRxUsadhj237eYiQ53",  new JsonHttpResponseHandler() {

// respons..
}

But when having ".read": "auth != null" it gíve permission denied.

Im signed in to Firebase usning Google credentials and the auth=HnhLyXRxUsadhj237eYiQ53 is my Firebase ID. I can read and write to database making regularly ValueEventListener and updateChildren calls.

I have also tried the Web API Key for auth but not working.

I want to run this code because of the Firebase REST API shallow-data

Body:
If you want to read from firebase by rule ".read": "auth != null" and you do not want to use firebase api I recommend Retrofit2 library. You have to auth by Bearer service account token.

Warning! The token is valid only for one hour. Then you need to refresh the new token.

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

....

//mykey.json you get from FBconsole/Project Settings/service accounts/generte new private key

    myFile = new File(mykey.json);

    GoogleCredential googleCred = null;
    try {
        googleCred = GoogleCredential.fromStream(new FileInputStream(myFile));
    } catch (IOException e) {
        e.printStackTrace();
    }
    GoogleCredential scoped = googleCred.createScoped(
            Arrays.asList(
                    "https://www.googleapis.com/auth/firebase.database",
                    "https://www.googleapis.com/auth/userinfo.email"
            )
    );
    try {
        scoped.refreshToken();
    } catch (IOException e) {
        e.printStackTrace();
    }
    token = scoped.getAccessToken();
    Log.d("token ", token);

}//end of oncreate

Button click for read from FB

public void onClick(View view) {

    authtoken = "Bearer " + token;

    HttpLoggingInterceptor logging = new HttpLoggingInterceptor();
    logging.setLevel(HttpLoggingInterceptor.Level.BODY);

    OkHttpClient.Builder httpClient = new OkHttpClient.Builder();
    httpClient.addInterceptor(new Interceptor() {
        @Override
        public okhttp3.Response intercept(Chain chain) throws IOException {
            Request original = chain.request();

            // Request customization: add request headers
            Request.Builder requestBuilder = original.newBuilder()
                    .header("Authorization", authtoken); // <-- this is the important line
            Request request = requestBuilder.build();
            return chain.proceed(request);
        }
    });

    httpClient.addInterceptor(logging);
    OkHttpClient client = httpClient.build();

    Retrofit retrofit = new Retrofit.Builder()
            .baseUrl("https://yourproject.firebaseio.com")//url of firebase database app
            .client(client)
            .addConverterFactory(GsonConverterFactory.create())//use for convert JSON file into object
            .build();

    // prepare call in Retrofit 2.0
    FirebaseAPI firebaseAPI = retrofit.create(FirebaseAPI.class);

    Call<Event> call2=firebaseAPI.getPrivateData();

    call2.enqueue(new Callback<Event>() {
        @Override
        public void onResponse(Call<Event> call, Response<Event> response) {

            Log.d("Response ", "onResponse");
            //t1.setText("success name "+response.body().getName());

        }

        @Override
        public void onFailure(Call<Event> call, Throwable t) {
            Log.d("Response ", "onFailure");
            //t1.setText("Notification failure");
        }
    });
}

FirebaseAPI.java

public interface FirebaseAPI {

@GET("/uploadprivate/event.json")
Call<Event> getPrivateData();

}

POJO event.java

public class Event {
String name;
String address;

public Event(String name, String address) {
    this.address = address;
    this.name = name;
}

public String getName() {
    return name;
}

public void setName(String name) {
    this.name = name;
}

public String getAddress() {
    return address;
}

public void setAddress(String address) {
    this.address = address;
}

}

Data in FB console