问:
Cannot read property 'context' of null
I've been going through the Egghead "Build your first production quality React app" and everything's going fine until lesson 17, where you're supposed to use contextto create your own home made router component. As far as I can tell, I do exactly the same thing as in the lesson, but I get this console error when I click on one of the Link component:

```<code>Link.js:11 Uncaught TypeError: Cannot read property 'context' of null
at handleClick (http://localhost:3000/static/js/bundle.js:33792:12)
at Object.ReactErrorUtils.invokeGuardedCallback (http://localhost:3000/static/js/bundle.js:17162:17)
at executeDispatch (http://localhost:3000/static/js/bundle.js:16945:22)
at Object.executeDispatchesInOrder (http://localhost:3000/static/js/bundle.js:16968:6)
at executeDispatchesAndRelease (http://localhost:3000/static/js/bundle.js:16356:23)
at executeDispatchesAndReleaseTopLevel (http://localhost:3000/static/js/bundle.js:16367:11)
at Array.forEach (native)
at forEachAccumulated (http://localhost:3000/static/js/bundle.js:17265:10)
at Object.processEventQueue (http://localhost:3000/static/js/bundle.js:16570:8)
at runEventQueueInBatch (http://localhost:3000/static/js/bundle.js:24192:19)
</code>```

The link component looks like that:

```<code>import React, { Component } from 'react';

export class Link extends Component {
  static contextTypes = {
    route: React.PropTypes.string,
    linkHandler: React.PropTypes.func,
  }

  handleClick(e) {
    e.preventDefault();
    this.context.linkHandler(this.props.to)
  }

  render() {
    const activeClass = this.context.route === this.props.to ? 'active' : '';
    return <a href="#" className={activeClass} onClick={this.handleClick}>{this.props.children}</a>
  }
}

Link.propTypes = {
  to: React.PropTypes.string.isRequired
}
</code>```

And the Router component looks like that:

```<code>import React, { Component } from 'react';

const getCurrentPath = () => {
  const path = document.location.pathname;
  return path.substring(path.lastIndexOf('/'));
}

export class Router extends Component {
  state = {
    route: getCurrentPath()
  }

  handleLinkClick = (route) => {
    this.setState({ route }); // same as { route: route }
    history.pushState(null, '', route);
  }

  static childContextTypes = {
    route: React.PropTypes.string,
    linkHandler: React.PropTypes.func,
  };

  getchildContext() {
    return {
      route: this.state.route,
      linkHandler: this.handleLinkClick,
    };
  }

  render() {
    return <div>{this.props.children}</div>
  }
}
</code>```

Any idea of what could be causing the problem?

Thanks for any pointer in the right direction!

EDIT:

After following the advices I got (thanks!), I bound the handleClick in a constructor (same result with an arrow function) and verified that the function is called as expected, but now I get a different error:

```<code>Uncaught TypeError: this.context.linkHandler is not a function
at Link.handleClick (http://localhost:3000/static/js/bundle.js:33707:21)
at Object.ReactErrorUtils.invokeGuardedCallback (http://localhost:3000/static/js/bundle.js:17162:17)
at executeDispatch (http://localhost:3000/static/js/bundle.js:16945:22)
at Object.executeDispatchesInOrder (http://localhost:3000/static/js/bundle.js:16968:6)
at executeDispatchesAndRelease (http://localhost:3000/static/js/bundle.js:16356:23)
at executeDispatchesAndReleaseTopLevel (http://localhost:3000/static/js/bundle.js:16367:11)
at Array.forEach (native)
at forEachAccumulated (http://localhost:3000/static/js/bundle.js:17265:10)
at Object.processEventQueue (http://localhost:3000/static/js/bundle.js:16570:8)
at runEventQueueInBatch (http://localhost:3000/static/js/bundle.js:24192:19)
</code>```

答:
To give a clear answer to this question, the others have a great deal of extra information that can lead you astray.

Quoting

You need to bind this to handleClick. You can either do this in a
  constructor or in onClick (not recommended).
  onClick={this.handleClick.bind(this)} . Or use an arrow function for
  handleClick. const handleClick = () = > { }.

– Norm Crandall (from comments)

Title: Cannot read property 'context' of null

Body:
I've been going through the Egghead "Build your first production quality React app" and everything's going fine until lesson 17, where you're supposed to use contextto create your own home made router component. As far as I can tell, I do exactly the same thing as in the lesson, but I get this console error when I click on one of the Link component:

Link.js:11 Uncaught TypeError: Cannot read property 'context' of null
at handleClick (http://localhost:3000/static/js/bundle.js:33792:12)
at Object.ReactErrorUtils.invokeGuardedCallback (http://localhost:3000/static/js/bundle.js:17162:17)
at executeDispatch (http://localhost:3000/static/js/bundle.js:16945:22)
at Object.executeDispatchesInOrder (http://localhost:3000/static/js/bundle.js:16968:6)
at executeDispatchesAndRelease (http://localhost:3000/static/js/bundle.js:16356:23)
at executeDispatchesAndReleaseTopLevel (http://localhost:3000/static/js/bundle.js:16367:11)
at Array.forEach (native)
at forEachAccumulated (http://localhost:3000/static/js/bundle.js:17265:10)
at Object.processEventQueue (http://localhost:3000/static/js/bundle.js:16570:8)
at runEventQueueInBatch (http://localhost:3000/static/js/bundle.js:24192:19)

The link component looks like that:

import React, { Component } from 'react';

export class Link extends Component {
  static contextTypes = {
    route: React.PropTypes.string,
    linkHandler: React.PropTypes.func,
  }

  handleClick(e) {
    e.preventDefault();
    this.context.linkHandler(this.props.to)
  }

  render() {
    const activeClass = this.context.route === this.props.to ? 'active' : '';
    return {this.props.children}
  }
}

Link.propTypes = {
  to: React.PropTypes.string.isRequired
}

And the Router component looks like that:

import React, { Component } from 'react';

const getCurrentPath = () => {
  const path = document.location.pathname;
  return path.substring(path.lastIndexOf('/'));
}

export class Router extends Component {
  state = {
    route: getCurrentPath()
  }

  handleLinkClick = (route) => {
    this.setState({ route }); // same as { route: route }
    history.pushState(null, '', route);
  }

  static childContextTypes = {
    route: React.PropTypes.string,
    linkHandler: React.PropTypes.func,
  };

  getchildContext() {
    return {
      route: this.state.route,
      linkHandler: this.handleLinkClick,
    };
  }

  render() {
    return
{this.props.children}

  }
}

Any idea of what could be causing the problem?

Thanks for any pointer in the right direction!

EDIT:

After following the advices I got (thanks!), I bound the handleClick in a constructor (same result with an arrow function) and verified that the function is called as expected, but now I get a different error:

Uncaught TypeError: this.context.linkHandler is not a function
at Link.handleClick (http://localhost:3000/static/js/bundle.js:33707:21)
at Object.ReactErrorUtils.invokeGuardedCallback (http://localhost:3000/static/js/bundle.js:17162:17)
at executeDispatch (http://localhost:3000/static/js/bundle.js:16945:22)
at Object.executeDispatchesInOrder (http://localhost:3000/static/js/bundle.js:16968:6)
at executeDispatchesAndRelease (http://localhost:3000/static/js/bundle.js:16356:23)
at executeDispatchesAndReleaseTopLevel (http://localhost:3000/static/js/bundle.js:16367:11)
at Array.forEach (native)
at forEachAccumulated (http://localhost:3000/static/js/bundle.js:17265:10)
at Object.processEventQueue (http://localhost:3000/static/js/bundle.js:16570:8)
at runEventQueueInBatch (http://localhost:3000/static/js/bundle.js:24192:19)


来源: stackexchange

问:
How to use quotes in Visual Studio Code settings values?
I'm trying to add this as my default terminal: C:\Windows\System32\cmd.exe /k "C:\Program Files\nodejs\nodevars.bat" but how do I set the "/k "C:\Program Files\nodejs\nodevars.bat" part in terminal.integrated.shellArgs.windows settings. It doesn't allow for nested quotation marks. I tried escaping the quotation marks, double quotes etc.  Each option the command prompt states the path set is invalid.</p>

答:
go to File menu > Preferences > workspace settings. On right hand side, you will see settings.json. In this file add below line-

```<code>"terminal.integrated.shell.windows": "C:\\Windows\\system32\\cmd.exe  /k \"C:\\Program Files\\nodejs\\nodevars.bat\""
</code>```

thats it. now you can run npm install and npm start commands to run your angular2 application.

see if this helps.

ContentLicense: CC BY-SA 3.0

Body:
go to File menu > Preferences > workspace settings. On right hand side, you will see settings.json. In this file add below line-

"terminal.integrated.shell.windows": "C:\\Windows\\system32\\cmd.exe  /k \"C:\\Program Files\\nodejs\\nodevars.bat\""

thats it. now you can run npm install and npm start commands to run your angular2 application.

see if this helps.


问:
How to get the inner array from json in android?
```<code>{"Suggestions":[{"Itinerary_1":[{"Cities":"Madurai - Pazhamudir Cholai (Madurai) - Pillayarpatti - Chennai","Citieids":"14-85-114-2","Kms":595}],"Itinerary_2":[{"Cities":"Madurai - Pillayarpatti - Pillayarpatti - Chennai","Citieids":"14-114-114-2","Kms":560}],"Itinerary_3":[{"Cities":"Madurai - Pillayarpatti - Pillayarpatti - Chennai","Citieids":"14-114-114-2","Kms":560}]}]}
</code>```

This my json response.This json have a inner array how can i get the value

This my code:

```<code>class itinerarydetails extends AsyncTask<String, String, String> {

        /**
         * Before starting background thread Show Progress Dialog
         */
        boolean failure = false;

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
        }

        @Override
        protected String doInBackground(String... args) {
            // TODO Auto-generated method stub
            // Check for success tag
            int success;

            List<NameValuePair> params = new ArrayList<NameValuePair>();
            params.add(new BasicNameValuePair("orgin", "14"));
            params.add(new BasicNameValuePair("destination", "2"));
            params.add(new BasicNameValuePair("orgin_date", "28/06/2017"));
            params.add(new BasicNameValuePair("destination_date", "07/07/2017"));

             json = jsonParser.makeHttpRequest(itineraryurl, "GET",
                    params);
            try {

                //Suggestions
                jsonarray = json.getJSONArray("Suggestions");
               // JSONArray list = mainObj.getJSONArray("prodCat_list");

                String check;
                if(jsonarray != null) {
                   // Toast.makeText(getApplicationCon                                                                                text(), "MAIN ARRAY IS NOT EMPTY ITS HAVE A VALUE",
                    //  Toast.LENGTH_SHORT).show();

                    Log.d("check","MAIN ARRAY IS NOT EMPTY ITS HAVE A VALUE");

                    for (int i = 0; i < jsonarray.length(); i++) {
                        //   JSONObject elem = list.getJSONObject(i);

                        JSONObject object = jsonarray.getJSONObject(i);

                        //JSONArray prods = elem.getJSONArray("prods");

                        jsoninsidearray = object.getJSONArray("Itinerary_1");

                        if(jsoninsidearray != null) {

                            Log.d("check","INSIDE ARRAY IS NOT EMPTY ITS HAVE A VALUE");

                            for (int j = 0; j < jsoninsidearray.length(); j++) {
                                JSONObject innerElem = jsoninsidearray.getJSONObject(j);

                                if(innerElem != null) {

                                    Log.d("check","innerElement ARRAY IS NOT EMPTY ITS HAVE A VALUE");
                                    cityjson = innerElem.getString("Cities");
                                    itinerary = innerElem.getString("Citieids");
                                    totalkms = innerElem.getString("Kms");

                                }
                               else
                                {
                                    Log.d("check","innerElement ARRAY IS EMPTY");

                                }

                            }
                        }
                        else
                        {
                           Toast.makeText(getApplicationContext(), "INSIDE ARRAY IS EMPTY",
                                   Toast.LENGTH_SHORT).show();

                            Log.d("check","INSIDE ARRAY IS EMPTY");
                        }

                    }
                }
                else
                {
                    Toast.makeText(getApplicationContext(), "MAIN ARRAY IS EMPTY",
                            Toast.LENGTH_SHORT).show();

                    Log.d("check","MAIN ARRAY IS EMPTY");
                }
            } catch (JSONException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }

            return null;
        }

        protected void onPostExecute(String file_url) {

            Toast.makeText(getApplicationContext(), "hai",
                    Toast.LENGTH_SHORT).show();
            Toast.makeText(getApplicationContext(), cityjson, Toast.LENGTH_SHORT).show();

        }

    }
</code>```

I am Vignesh i have a doubt so pls help in this below
but empty values has displayed.how can i get the values from inner array from json.

答:
Let's try to understand the structure of your input JSON object.

Suggestions (JSONArray)

First Object (JSONObject)

Itinerary_1 (JSONArray)

First Object (JSONObject)

cities (String)

citieids (String)

kms (String)

Itinerary_2 (JSONArray)

First Object (JSONObject)

cities (String)

citieids (String)

kms (String)

Itinerary_3 (JSONArray)

First Object (JSONObject)

cities (String)

citieids (String)

kms (String)

Second Object (JSONObject)

Itinerary_1 (JSONArray)

First Object (JSONObject)

cities (String)

citieids (String)

kms (String)

Itinerary_2 (JSONArray)

First Object (JSONObject)

cities (String)

citieids (String)

kms (String)

Itinerary_3 (JSONArray)

First Object (JSONObject)

cities (String)

citieids (String)

kms (String)

so on ....

formatted JSON Object

```<code>{
   "Suggestions":[
      {
         "Itinerary_1":[
            {
               "Cities":"Madurai - Pazhamudir Cholai (Madurai) - Pillayarpatti - Chennai",
               "Citieids":"14-85-114-2",
               "Kms":595
            }
         ],
         "Itinerary_2":[
            {
               "Cities":"Madurai - Pillayarpatti - Pillayarpatti - Chennai",
               "Citieids":"14-114-114-2",
               "Kms":560
            }
         ],
         "Itinerary_3":[
            {
               "Cities":"Madurai - Pillayarpatti - Pillayarpatti - Chennai",
               "Citieids":"14-114-114-2",
               "Kms":560
            }
         ]
      }
   ]
}
</code>```

Hence your code should have an additional for loop to loop over 3 itinerary elements of each JSONObject inside Suggestions.

Here is the updated code, check out the new for loop added with index as the iteration counter.

```<code>    try {
        JSONObject json = new JSONObject("{\"Suggestions\":[{\"Itinerary_1\":[{\"Cities\":\"Madurai - Pazhamudir Cholai (Madurai) - Pillayarpatti - Chennai\",\"Citieids\":\"14-85-114-2\",\"Kms\":595}],\"Itinerary_2\":[{\"Cities\":\"Madurai - Pillayarpatti - Pillayarpatti - Chennai\",\"Citieids\":\"14-114-114-2\",\"Kms\":560}],\"Itinerary_3\":[{\"Cities\":\"Madurai - Pillayarpatti - Pillayarpatti - Chennai\",\"Citieids\":\"14-114-114-2\",\"Kms\":560}]}]}");
        JSONArray jsonarray = json.getJSONArray("Suggestions");
        if(jsonarray != null) {
            Log.d("check","MAIN ARRAY IS NOT EMPTY ITS HAVE A VALUE");
            for (int i = 0; i < jsonarray.length(); i++) {
                JSONObject object = jsonarray.getJSONObject(i);
                // ** START NEW FOR LOOP
                for (int index=1; index < 4; index++) {
                    Log.d("check","-------------------------");
                    Log.d("check","Print Itinerary_" + (index));
                    JSONArray jsoninsidearray = object.getJSONArray("Itinerary_" + index);
                    if(jsoninsidearray != null) {
                        Log.d("check","INSIDE ARRAY IS NOT EMPTY ITS HAVE A VALUE");
                        for (int j = 0; j < jsoninsidearray.length(); j++) {
                            JSONObject innerElem = jsoninsidearray.getJSONObject(j);
                            if(innerElem != null) {
                                Log.d("check","innerElement ARRAY IS NOT EMPTY ITS HAVE A VALUE");
                                String cityjson = innerElem.getString("Cities");
                                String itinerary = innerElem.getString("Citieids");
                                String totalkms = innerElem.getString("Kms");
                                Log.d("check", cityjson + " | " + itinerary + " | " + totalkms);
                            } else {
                                Log.d("check","innerElement ARRAY IS EMPTY");
                            }
                        }
                    } else {
                        Log.d("check","INSIDE ARRAY IS EMPTY");
                    }
                } // ** END NEW FOR LOOP
            Log.d("check", "");
            }
        } else {
            Log.d("check","MAIN ARRAY IS EMPTY");
        }
    } catch (JSONException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
</code>```

Sample Run

```<code>07-03 22:03:05.028 30616-30616/a D/check: MAIN ARRAY IS NOT EMPTY ITS HAVE A VALUE
07-03 22:03:05.028 30616-30616/a D/check: --------------------------
07-03 22:03:05.028 30616-30616/a D/check: Print Itinerary_1
07-03 22:03:05.028 30616-30616/a D/check: INSIDE ARRAY IS NOT EMPTY ITS HAVE A VALUE
07-03 22:03:05.028 30616-30616/a D/check: innerElement ARRAY IS NOT EMPTY ITS HAVE A VALUE
07-03 22:03:05.028 30616-30616/a D/check: Madurai - Pazhamudir Cholai (Madurai) - Pillayarpatti - Chennai | 14-85-114-2 | 595
07-03 22:03:05.028 30616-30616/a D/check: --------------------------
07-03 22:03:05.028 30616-30616/a D/check: Print Itinerary_2
07-03 22:03:05.028 30616-30616/a D/check: INSIDE ARRAY IS NOT EMPTY ITS HAVE A VALUE
07-03 22:03:05.028 30616-30616/a D/check: innerElement ARRAY IS NOT EMPTY ITS HAVE A VALUE
07-03 22:03:05.029 30616-30616/a D/check: Madurai - Pillayarpatti - Pillayarpatti - Chennai | 14-114-114-2 | 560
07-03 22:03:05.029 30616-30616/a D/check: --------------------------
07-03 22:03:05.029 30616-30616/a D/check: Print Itinerary_3
07-03 22:03:05.029 30616-30616/a D/check: INSIDE ARRAY IS NOT EMPTY ITS HAVE A VALUE
07-03 22:03:05.029 30616-30616/a D/check: innerElement ARRAY IS NOT EMPTY ITS HAVE A VALUE
07-03 22:03:05.029 30616-30616/a D/check: Madurai - Pillayarpatti - Pillayarpatti - Chennai | 14-114-114-2 | 560
</code>```

Body:
{"Suggestions":[{"Itinerary_1":[{"Cities":"Madurai - Pazhamudir Cholai (Madurai) - Pillayarpatti - Chennai","Citieids":"14-85-114-2","Kms":595}],"Itinerary_2":[{"Cities":"Madurai - Pillayarpatti - Pillayarpatti - Chennai","Citieids":"14-114-114-2","Kms":560}],"Itinerary_3":[{"Cities":"Madurai - Pillayarpatti - Pillayarpatti - Chennai","Citieids":"14-114-114-2","Kms":560}]}]}

This my json response.This json have a inner array how can i get the value

This my code:

class itinerarydetails extends AsyncTask<String, String, String> {

        /**
         * Before starting background thread Show Progress Dialog
         */
        boolean failure = false;

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
        }

        @Override
        protected String doInBackground(String... args) {
            // TODO Auto-generated method stub
            // Check for success tag
            int success;

            List<NameValuePair> params = new ArrayList<NameValuePair>();
            params.add(new BasicNameValuePair("orgin", "14"));
            params.add(new BasicNameValuePair("destination", "2"));
            params.add(new BasicNameValuePair("orgin_date", "28/06/2017"));
            params.add(new BasicNameValuePair("destination_date", "07/07/2017"));

             json = jsonParser.makeHttpRequest(itineraryurl, "GET",
                    params);
            try {

                //Suggestions
                jsonarray = json.getJSONArray("Suggestions");
               // JSONArray list = mainObj.getJSONArray("prodCat_list");

                String check;
                if(jsonarray != null) {
                   // Toast.makeText(getApplicationCon                                                                                text(), "MAIN ARRAY IS NOT EMPTY ITS HAVE A VALUE",
                    //  Toast.LENGTH_SHORT).show();

                    Log.d("check","MAIN ARRAY IS NOT EMPTY ITS HAVE A VALUE");

                    for (int i = 0; i < jsonarray.length(); i++) {
                        //   JSONObject elem = list.getJSONObject(i);

                        JSONObject object = jsonarray.getJSONObject(i);

                        //JSONArray prods = elem.getJSONArray("prods");

                        jsoninsidearray = object.getJSONArray("Itinerary_1");

                        if(jsoninsidearray != null) {

                            Log.d("check","INSIDE ARRAY IS NOT EMPTY ITS HAVE A VALUE");

                            for (int j = 0; j < jsoninsidearray.length(); j++) {
                                JSONObject innerElem = jsoninsidearray.getJSONObject(j);

                                if(innerElem != null) {

                                    Log.d("check","innerElement ARRAY IS NOT EMPTY ITS HAVE A VALUE");
                                    cityjson = innerElem.getString("Cities");
                                    itinerary = innerElem.getString("Citieids");
                                    totalkms = innerElem.getString("Kms");

                                }
                               else
                                {
                                    Log.d("check","innerElement ARRAY IS EMPTY");

                                }

                            }
                        }
                        else
                        {
                           Toast.makeText(getApplicationContext(), "INSIDE ARRAY IS EMPTY",
                                   Toast.LENGTH_SHORT).show();

                            Log.d("check","INSIDE ARRAY IS EMPTY");
                        }

                    }
                }
                else
                {
                    Toast.makeText(getApplicationContext(), "MAIN ARRAY IS EMPTY",
                            Toast.LENGTH_SHORT).show();

                    Log.d("check","MAIN ARRAY IS EMPTY");
                }
            } catch (JSONException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }

            return null;
        }

        protected void onPostExecute(String file_url) {

            Toast.makeText(getApplicationContext(), "hai",
                    Toast.LENGTH_SHORT).show();
            Toast.makeText(getApplicationContext(), cityjson, Toast.LENGTH_SHORT).show();

        }

    }

I am Vignesh i have a doubt so pls help in this below
but empty values has displayed.how can i get the values from inner array from json.

Body:
Let's try to understand the structure of your input JSON object.

Suggestions (JSONArray)

First Object (JSONObject)

Itinerary_1 (JSONArray)

First Object (JSONObject)

cities (String)

citieids (String)

kms (String)

Itinerary_2 (JSONArray)

First Object (JSONObject)

cities (String)

citieids (String)

kms (String)

Itinerary_3 (JSONArray)

First Object (JSONObject)

cities (String)

citieids (String)

kms (String)

Second Object (JSONObject)

Itinerary_1 (JSONArray)

First Object (JSONObject)

cities (String)

citieids (String)

kms (String)

Itinerary_2 (JSONArray)

First Object (JSONObject)

cities (String)

citieids (String)

kms (String)

Itinerary_3 (JSONArray)

First Object (JSONObject)

cities (String)

citieids (String)

kms (String)

so on ....

formatted JSON Object

{
   "Suggestions":[
      {
         "Itinerary_1":[
            {
               "Cities":"Madurai - Pazhamudir Cholai (Madurai) - Pillayarpatti - Chennai",
               "Citieids":"14-85-114-2",
               "Kms":595
            }
         ],
         "Itinerary_2":[
            {
               "Cities":"Madurai - Pillayarpatti - Pillayarpatti - Chennai",
               "Citieids":"14-114-114-2",
               "Kms":560
            }
         ],
         "Itinerary_3":[
            {
               "Cities":"Madurai - Pillayarpatti - Pillayarpatti - Chennai",
               "Citieids":"14-114-114-2",
               "Kms":560
            }
         ]
      }
   ]
}

Hence your code should have an additional for loop to loop over 3 itinerary elements of each JSONObject inside Suggestions.

Here is the updated code, check out the new for loop added with index as the iteration counter.

    try {
        JSONObject json = new JSONObject("{\"Suggestions\":[{\"Itinerary_1\":[{\"Cities\":\"Madurai - Pazhamudir Cholai (Madurai) - Pillayarpatti - Chennai\",\"Citieids\":\"14-85-114-2\",\"Kms\":595}],\"Itinerary_2\":[{\"Cities\":\"Madurai - Pillayarpatti - Pillayarpatti - Chennai\",\"Citieids\":\"14-114-114-2\",\"Kms\":560}],\"Itinerary_3\":[{\"Cities\":\"Madurai - Pillayarpatti - Pillayarpatti - Chennai\",\"Citieids\":\"14-114-114-2\",\"Kms\":560}]}]}");
        JSONArray jsonarray = json.getJSONArray("Suggestions");
        if(jsonarray != null) {
            Log.d("check","MAIN ARRAY IS NOT EMPTY ITS HAVE A VALUE");
            for (int i = 0; i < jsonarray.length(); i++) {
                JSONObject object = jsonarray.getJSONObject(i);
                // ** START NEW FOR LOOP
                for (int index=1; index < 4; index++) {
                    Log.d("check","-------------------------");
                    Log.d("check","Print Itinerary_" + (index));
                    JSONArray jsoninsidearray = object.getJSONArray("Itinerary_" + index);
                    if(jsoninsidearray != null) {
                        Log.d("check","INSIDE ARRAY IS NOT EMPTY ITS HAVE A VALUE");
                        for (int j = 0; j < jsoninsidearray.length(); j++) {
                            JSONObject innerElem = jsoninsidearray.getJSONObject(j);
                            if(innerElem != null) {
                                Log.d("check","innerElement ARRAY IS NOT EMPTY ITS HAVE A VALUE");
                                String cityjson = innerElem.getString("Cities");
                                String itinerary = innerElem.getString("Citieids");
                                String totalkms = innerElem.getString("Kms");
                                Log.d("check", cityjson + " | " + itinerary + " | " + totalkms);
                            } else {
                                Log.d("check","innerElement ARRAY IS EMPTY");
                            }
                        }
                    } else {
                        Log.d("check","INSIDE ARRAY IS EMPTY");
                    }
                } // ** END NEW FOR LOOP
            Log.d("check", "");
            }
        } else {
            Log.d("check","MAIN ARRAY IS EMPTY");
        }
    } catch (JSONException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

Sample Run

07-03 22:03:05.028 30616-30616/a D/check: MAIN ARRAY IS NOT EMPTY ITS HAVE A VALUE
07-03 22:03:05.028 30616-30616/a D/check: --------------------------
07-03 22:03:05.028 30616-30616/a D/check: Print Itinerary_1
07-03 22:03:05.028 30616-30616/a D/check: INSIDE ARRAY IS NOT EMPTY ITS HAVE A VALUE
07-03 22:03:05.028 30616-30616/a D/check: innerElement ARRAY IS NOT EMPTY ITS HAVE A VALUE
07-03 22:03:05.028 30616-30616/a D/check: Madurai - Pazhamudir Cholai (Madurai) - Pillayarpatti - Chennai | 14-85-114-2 | 595
07-03 22:03:05.028 30616-30616/a D/check: --------------------------
07-03 22:03:05.028 30616-30616/a D/check: Print Itinerary_2
07-03 22:03:05.028 30616-30616/a D/check: INSIDE ARRAY IS NOT EMPTY ITS HAVE A VALUE
07-03 22:03:05.028 30616-30616/a D/check: innerElement ARRAY IS NOT EMPTY ITS HAVE A VALUE
07-03 22:03:05.029 30616-30616/a D/check: Madurai - Pillayarpatti - Pillayarpatti - Chennai | 14-114-114-2 | 560
07-03 22:03:05.029 30616-30616/a D/check: --------------------------
07-03 22:03:05.029 30616-30616/a D/check: Print Itinerary_3
07-03 22:03:05.029 30616-30616/a D/check: INSIDE ARRAY IS NOT EMPTY ITS HAVE A VALUE
07-03 22:03:05.029 30616-30616/a D/check: innerElement ARRAY IS NOT EMPTY ITS HAVE A VALUE
07-03 22:03:05.029 30616-30616/a D/check: Madurai - Pillayarpatti - Pillayarpatti - Chennai | 14-114-114-2 | 560


问:
Move file downloaded in Dockerfile to harddrive
First off, I really lack a lot of knowledge regarding Docker itself and its structure. I know that it'd be way more beneficial to learn the basics first, but I do require this to work in order to move on to other things for now.

So within a Dockerfile I installed wget & used it to download a file from a website, authentification & download are successful. However, when I later try move said file it can't be found, and it doesn't show up using e.g explorer either (path was specified)
I thought it might have something to do with RUN & how it executes the wget command; I read that the Id can be used to copy it to harddrive, but how'd I do that within a Dockerfile?

```<code>RUN wget -P ./path/to/somewhere http://something.com/file.txt --username xyz --password bluh

ADD ./path/to/somewhere/file.txt /mainDirectory
</code>```

Download is shown & log-in is successful, but as I mentioned I am having trouble using that file later on as it's not to be located on the harddrive. Probably a basic error, but I'd really appreciate some input that might lead to a solution.

Obviously the error is produced when trying to execute ADD as there is no file to move. I am trying to find a way to mount a volume in order to store it, but so far in vain.

Edit:
Though the question is similiar to the "move to harddrive" one, I am searching for ways to get the id of the container created within the Dockerfile in order to move it; while the thread provides such answers, I haven't had any luck using them within the Dockerfile itself.

答:
Use wget -O instead of -P for specific file download

for e.g.,

RUN wget -O /tmp/new_file.txt  http://something.com --username xyz --password bluh/new_file.txt

Thanks

Body:
First off, I really lack a lot of knowledge regarding Docker itself and its structure. I know that it'd be way more beneficial to learn the basics first, but I do require this to work in order to move on to other things for now.

So within a Dockerfile I installed wget & used it to download a file from a website, authentification & download are successful. However, when I later try move said file it can't be found, and it doesn't show up using e.g explorer either (path was specified)
I thought it might have something to do with RUN & how it executes the wget command; I read that the Id can be used to copy it to harddrive, but how'd I do that within a Dockerfile?

RUN wget -P ./path/to/somewhere http://something.com/file.txt --username xyz --password bluh

ADD ./path/to/somewhere/file.txt /mainDirectory

Download is shown & log-in is successful, but as I mentioned I am having trouble using that file later on as it's not to be located on the harddrive. Probably a basic error, but I'd really appreciate some input that might lead to a solution.

Obviously the error is produced when trying to execute ADD as there is no file to move. I am trying to find a way to mount a volume in order to store it, but so far in vain.

Edit:
Though the question is similiar to the "move to harddrive" one, I am searching for ways to get the id of the container created within the Dockerfile in order to move it; while the thread provides such answers, I haven't had any luck using them within the Dockerfile itself.


问:
Nested site collections in SharePoint Online (O365)
Is it possible to create nested site collections in SharePoint Online - such as  with the following URL:

https://xxx.sharepoint.com/sites/siteCollection1/siteCollection2/siteCollection3

If yes, can please someone give instruction of how it can be done?

答:
It is possible to create a sub site in existing site collection/subsite:

Enter the site collection where you are willing to create a sub-site: https://xxx.sharepoint.com/sites/testsite

Go to "Site contents"

click on New:

Click on subsite.


问:
Error while running iphone app in ipad
I am converting an iPhone App in to the iPad App,

for that I have changed the  buttons size by "Austosizing" feature in Inspecture  and it resized the buttons and it looks fine in the iPad simulator

All the functionalities were working perfectly in the in the  iPhone simulator

The problem is that when I click buttons in the iPad simulator then only certain buttons are working, the others button look as if they are disabled but as such they are not

The screen resizes to the iPad resolution but screen seems to work only till iphone view dimensions

What could be wrong?

what should be done?

Please Help and Suggest

Thanks

答:
Hi if you want to run your iPhone application in iPad then you must have to create iPad nib's and saved them with "nibname-iPad" and also you have to change the .plist file in Other Resource folder with adding option NSMainNibFile~ipad as key and MainWindow-iPad as its value

And also remember that wherever you use iPhone nib you must have to change it with iPad nib name.

ContentLicense: CC BY-SA 2.5

Title: Error while running iphone app in ipad


问:
With Java EE and GWT, how can I open a new browser tab to a web app on the same server?
I have a web app that displays a list of ID's (among other things) to the user. The back end is Java EE, and the front end is built with GWT.

When the user clicks one of the ID's a callback is executed that queries additional parameters from an API using the ID. When the API returns the parameters, I want to open another web app, passing one of the parameters to it so it opens displaying information relating to that parameter. How would this normally be done?

Can I use something like LinkElement for this?

Edit: I got this working using GWT's Window.open("my.url.com");

But I'm wondering if there's a better way?

答: You need to use GWT's Window class to handle this.


问:
How to perform Joi Validations for a TypeScript Class?
I'm able to perform Joi Validations for function expressions in node as shown below

```<code>export var shippingInfo = Joi.object().keys({
   expectedDeliveryDate:Joi.date().required(),
   isRegisteredCompanyAddress:Joi.number().required(),
   addressLine:Joi.string(),
   country:Joi.string(),
   state:Joi.string(),
   city:Joi.string(),
   zipcode:Joi.string()
});
</code>```

But the problem is, I recently started working on typescript. So here, I've few classes and I'm supposed to perform the Joi validations as I did in the above function expressions. i.e I want to validate for the below class

```<code>export class ShippingInfo {
   expectedDeliveryDate: Date,
   isRegisteredCompanyAddress: number,
   addressLine:string,
   country:string,
   state:string,
   city:string,
   zipcode:string
}
</code>```

How should I make validations for the above class. Should do validations for class level or it's object level? how?

答:
you can use this project as a reference. tsdv-joi

```<code>// ...imports...

registerJoi(Joi);

class MyClass {
    @Max(5)
    @Min(2)
    @StringSchema
    public myProperty : string;
}

let instance = new MyClass();
instance.myProperty = "a";

const validator = new Validator();
var result = validator.validate(instance);
console.log(result); // outputs the Joi returned value
</code>```

If you need npm package then you can use this wrapper for it gearworks

Body:
I'm able to perform Joi Validations for function expressions in node as shown below

export var shippingInfo = Joi.object().keys({
   expectedDeliveryDate:Joi.date().required(),
   isRegisteredCompanyAddress:Joi.number().required(),
   addressLine:Joi.string(),
   country:Joi.string(),
   state:Joi.string(),
   city:Joi.string(),
   zipcode:Joi.string()
});

But the problem is, I recently started working on typescript. So here, I've few classes and I'm supposed to perform the Joi validations as I did in the above function expressions. i.e I want to validate for the below class

export class ShippingInfo {
   expectedDeliveryDate: Date,
   isRegisteredCompanyAddress: number,
   addressLine:string,
   country:string,
   state:string,
   city:string,
   zipcode:string
}

How should I make validations for the above class. Should do validations for class level or it's object level? how?

Body:
you can use this project as a reference. tsdv-joi

// ...imports...

registerJoi(Joi);

class MyClass {
    @Max(5)
    @Min(2)
    @StringSchema
    public myProperty : string;
}

let instance = new MyClass();
instance.myProperty = "a";

const validator = new Validator();
var result = validator.validate(instance);
console.log(result); // outputs the Joi returned value

If you need npm package then you can use this wrapper for it gearworks


问:
How to call why3, from the command line, to access a prover with alternatives?
My configuration file includes alternative entries for different provers. When I execute why3 prove with that prover, then the output of why3 is a message informing that I have more than one prover in my configuration file with the given name, the list of these provers.

```<code>/home/xyz> why3 prove --prover Z3 afile.why
More than one prover in /home/xyz/.why3.conf correspond to "Z3":
Z3 (4.4.1), Z3 (4.4.1 noBV)
</code>```

I would like to know how to call why3 on a specific alternative of that prover, if this is possible.

答:
Eventually I peeked at the source code of Why3 to get an answer. It is to be found in why3/src/driver/whyconf.mli and why3/src/driver/whyconf.ml.

A solution is to use the version and alternative fields of the prover entry in Why3's configuration file. For instance, if this file contains the following two entries for Z3:

```<code>[prover]
alternative = "noBV"
command = "%l/why3-cpulimit %t %m -s z3 -smt2 sat.random_seed=42 nlsat.randomize=false smt.random_seed=42 %f"
command_steps = "%l/why3-cpulimit %U %m -s z3 -smt2 sat.random_seed=42 nlsat.randomize=false smt.random_seed=42 memory_max_alloc_count=%S %f"
driver = "/home/ddeharbe/.opam/system/share/why3/drivers/z3_432.drv"
editor = ""
in_place = false
interactive = false
name = "Z3"
version = "4.4.1"

[prover]
command = "%l/why3-cpulimit %t %m -s z3 -smt2 sat.random_seed=42 nlsat.randomize=false smt.random_seed=42 %f"
command_steps = "%l/why3-cpulimit %U %m -s z3 -smt2 sat.random_seed=42 nlsat.randomize=false smt.random_seed=42 memory_max_alloc_count=%S %f"
driver = "/home/ddeharbe/.opam/system/share/why3/drivers/z3_440.drv"
editor = ""
in_place = false
interactive = false
name = "Z3"
shortcut = "z3"
version = "4.4.1"
</code>```

The "alternative" field differs between entries. So to call the first entry, the command is:

```<code>why3 prove afile.why --prover Z3,4.4.1,
</code>```

To call the second entry, the command is:

```<code>why3 prove afile.why --prover Z3,4.4.1,noBV
</code>```

Body:
My configuration file includes alternative entries for different provers. When I execute why3 prove with that prover, then the output of why3 is a message informing that I have more than one prover in my configuration file with the given name, the list of these provers.

/home/xyz> why3 prove --prover Z3 afile.why
More than one prover in /home/xyz/.why3.conf correspond to "Z3":
Z3 (4.4.1), Z3 (4.4.1 noBV)

I would like to know how to call why3 on a specific alternative of that prover, if this is possible.

Body:
Eventually I peeked at the source code of Why3 to get an answer. It is to be found in why3/src/driver/whyconf.mli and why3/src/driver/whyconf.ml.

A solution is to use the version and alternative fields of the prover entry in Why3's configuration file. For instance, if this file contains the following two entries for Z3:

[prover]
alternative = "noBV"
command = "%l/why3-cpulimit %t %m -s z3 -smt2 sat.random_seed=42 nlsat.randomize=false smt.random_seed=42 %f"
command_steps = "%l/why3-cpulimit %U %m -s z3 -smt2 sat.random_seed=42 nlsat.randomize=false smt.random_seed=42 memory_max_alloc_count=%S %f"
driver = "/home/ddeharbe/.opam/system/share/why3/drivers/z3_432.drv"
editor = ""
in_place = false
interactive = false
name = "Z3"
version = "4.4.1"

[prover]
command = "%l/why3-cpulimit %t %m -s z3 -smt2 sat.random_seed=42 nlsat.randomize=false smt.random_seed=42 %f"
command_steps = "%l/why3-cpulimit %U %m -s z3 -smt2 sat.random_seed=42 nlsat.randomize=false smt.random_seed=42 memory_max_alloc_count=%S %f"
driver = "/home/ddeharbe/.opam/system/share/why3/drivers/z3_440.drv"
editor = ""
in_place = false
interactive = false
name = "Z3"
shortcut = "z3"
version = "4.4.1"

The "alternative" field differs between entries. So to call the first entry, the command is:

why3 prove afile.why --prover Z3,4.4.1,

To call the second entry, the command is:

why3 prove afile.why --prover Z3,4.4.1,noBV


问:
Multiple Activity or Single Activity and multiple fragments
I have one very general question, I did not find a concrete answer for my question hence putting it again.

I want to decide between two approaches

Dedicated activities for various various screens and tasks to avoid complexity and issues

Single Activities and multiple fragments for different tasks and user can navigate like Activity holding Fragment A user will navigate to Fragment B, Fragment C , this can be back and forth transaction.

What I want to know?

Is Activity transition is that costly for processor or to achieve simplicity memory overhead is negligible ?

Fragment has overhead of managing life cycle with transition, so what all problem can come with this life cycler management?

How easy is to deal with fragment transaction with saving state of the fragment?

We don't know right now what amount data will be there for fragment to hold.

答:
Well, it totally depends on the application's design, flow and it's navigation.

Here are some benefits of using Single Activity and Multiple Fragments:

Performance fragment transactions are fast than creating new activities.

Navigation Drawer and Toolbar, it's easy to manage with Single activity.

Same Context can be used everywhere.

Fragment's setRetainInstance is very helpful while managing orientation changes.

with it, here comes few drawbacks:

Activity gets really messy with a lots of code.

Handling button backpress is tedious as only Activity can handle that not Fragments.

I personally use Multiple activities with multiple fragments in which I separate activities based on the modules. In same module, submodules can be created in fragments. I found it easy to manage in different scenarios as if application gets closed, reopens, in notifications, orientation changes.


问:
Convert time xx:xxam or xx:xxpm to ISOString
Is there a know way to convert 10:12am and/or 12:10pm to ISOString format?

So far, I was trying to detect if the the time is an am or pm then remove the last 2 chars. After that im just appending new date string like :

```<code>export function timeAMPMToISO(time) {
    var newTime = time.slice(0, -2)
    var isAmPm = time.substr(-2)
    var h = parseInt(newTime.split(':')[0])
    var m = newTime.split(':')[1]
    var date = new Date().toISOString().substring(0, 11);
    if(isAmPm === 'pm'){
        if(h === 12){
            h = h
        }else{
            h += 12
        }
    }
    h = (isAmPm === 'am' && h === 12) ? '00' : h;
    return `${ date }${ h }:${ m }:00.000Z`;
}
</code>```

I have a feeling that this is not normal.

Is there an existing library for this? MomentJs perhaps? If so, how?

Thanks.

答:
You can parse your input using moment (String, String) and then use toISOString().

Your code can be like the following:

```<code>moment('10:12am', 'hh:mma').toISOString()
</code>```

The hh token matches 1-12 hours, mm matches 0-59 minutes and a matches am/pm

Body:
Is there a know way to convert 10:12am and/or 12:10pm to ISOString format?

So far, I was trying to detect if the the time is an am or pm then remove the last 2 chars. After that im just appending new date string like :

export function timeAMPMToISO(time) {
    var newTime = time.slice(0, -2)
    var isAmPm = time.substr(-2)
    var h = parseInt(newTime.split(':')[0])
    var m = newTime.split(':')[1]
    var date = new Date().toISOString().substring(0, 11);
    if(isAmPm === 'pm'){
        if(h === 12){
            h = h
        }else{
            h += 12
        }
    }
    h = (isAmPm === 'am' && h === 12) ? '00' : h;
    return `${ date }${ h }:${ m }:00.000Z`;
}

I have a feeling that this is not normal.

Is there an existing library for this? MomentJs perhaps? If so, how?

Thanks.

Body:
You can parse your input using moment (String, String) and then use toISOString().

Your code can be like the following:

moment('10:12am', 'hh:mma').toISOString()

The hh token matches 1-12 hours, mm matches 0-59 minutes and a matches am/pm


问:
numpy - arange: Why does following example not end at 10
I am beginner in Python.Trying hands on to learn numpy.

```<code>import numpy as np
x = np.arange(0.5, 10.4, 0.8, int)
</code>```

it outputs :

```<code>[ 0  1  2  3  4  5  6  7  8  9 10 11 12 ]
</code>```

I was expecting it to return (as last item is 10.4):

```<code>[ 0  1  2  3  4  5  6  7  8  9 10 ]
</code>```

Apart from above, if I execute this(Understood this example) :

```<code>x = np.arange(0.5, 10.4, 0.8)
print(x)
</code>```

It prints :

```<code>[  0.5  1.3  2.1  2.9  3.7  4.5  5.3  6.1  6.9  7.7  8.5  9.3  10.1 ]
</code>```

答:
This is a pretty weird way to call arange. The behavior is undocumented, and I don't think much thought went into it. Here's what happens, at least in the current release, based on the source.

Using the original arguments you passed, 0.5, 10.4, and 0.8, NumPy computes the length of the result and the second element using the _calc_length helper function. These calculations are done in Python object arithmetic, and the length is converted to a npy_intp integer. In your case, the length is computed as 13.

NumPy then allocates an array of the requested data type and the computed length, and it stores the first two elements in the array. As the elements are stored, they are subjected to usual NumPy dtype conversion. In your case, the first two elements are coerced to 0 and 1.

Finally, NumPy calls the new array's fill function to fill the array with values computed from the first two elements. The fill function recomputes the step from the first two elements, so it computes a step of 1 and fills the array with integers from 0 to 12.

Body:
I am beginner in Python.Trying hands on to learn numpy.

import numpy as np
x = np.arange(0.5, 10.4, 0.8, int)

it outputs :

[ 0  1  2  3  4  5  6  7  8  9 10 11 12 ]

I was expecting it to return (as last item is 10.4):

[ 0  1  2  3  4  5  6  7  8  9 10 ]

Apart from above, if I execute this(Understood this example) :

x = np.arange(0.5, 10.4, 0.8)
print(x)

It prints :

[  0.5  1.3  2.1  2.9  3.7  4.5  5.3  6.1  6.9  7.7  8.5  9.3  10.1 ]


问:
ASP.NET MVC - Order By Date
I am trying to sort table (columns: ID, Name, SermonDate, SermonTitle, BibleReading, VideoLink, BulletinLink) by date (SermonDate) so the data with the newest date comes on top and display it in my MVC application.

After some researching, I've tried putting the below with reference to this and this but nothing worked for me - probably because I misunderstood and put wrong code though.

```<code>public async Task<IActionResult> Index()
{
     return View(await _context.Sermon.OrderBy(sermon =>
     DateTime.Now).Take(5).ToListAsync());
}
</code>```

My current controller (SermonsController.cs):

```<code>public SermonsController(BKPCContext context)
    {
        _context = context;
    }

    public async Task<IActionResult> Index()
    {
        return View(await _context.Sermon.OrderBy(sermon => DateTime.Now).Take(5).ToListAsync());
    }

    public async Task<IActionResult> Details(int? id)
    {
        if (id == null)
        {
            return NotFound();
        }

        var sermon = await _context.Sermon
            .SingleOrDefaultAsync(m => m.ID == id);
        if (sermon == null)
        {
            return NotFound();
        }

        return View(sermon);
    }

    public IActionResult Create()
    {
        return View();
    }

    [HttpPost]
    [ValidateAntiForgeryToken]
    public async Task<IActionResult> Create([Bind("ID,Name,SermonDate,SermonTitle,BibleReading,VideoLink,BulletinLink")] Sermon sermon)
    {
        if (ModelState.IsValid)
        {
            _context.Add(sermon);
            await _context.SaveChangesAsync();
            return RedirectToAction("Index");
        }
        return View(sermon);
    }
</code>```

And the html table in /Sermons/Index.cshtml as below:

```<code><table class="table">
<thead>
    <tr>
        <th>
            @Html.DisplayNameFor(model => model.Name)
        </th>
        <th>
            @Html.DisplayNameFor(model => model.SermonDate)
        </th>
        <th>
            @Html.DisplayNameFor(model => model.SermonTitle)
        </th>
        <th>
            @Html.DisplayNameFor(model => model.BibleReading)
        </th>
        <th>
            @Html.DisplayNameFor(model => model.VideoLink)
        </th>
        <th>
            @Html.DisplayNameFor(model => model.BulletinLink)
        </th>
        <th>

        </th>
    </tr>
</thead>
<tbody>
@foreach (var item in Model) {
    <tr>
        <td>
            @Html.DisplayFor(modelItem => item.Name)
        </td>
        <td>
            @Html.DisplayFor(modelItem => item.SermonDate)
        </td>
        <td>
            @Html.DisplayFor(modelItem => item.SermonTitle)
        </td>
        <td>
            @Html.DisplayFor(modelItem => item.BibleReading)
        </td>
        <td>
            @Html.DisplayFor(modelItem => item.VideoLink)
        </td>
        <td>
            @Html.DisplayFor(modelItem => item.BulletinLink)
        </td>
        <td id="aspButton">
            <a role="button" id="btn-primary" class="btn btn-primary" asp-action="Edit" asp-route-id="@item.ID">Edit</a>
            <a role="button" id="btn-danger" class="btn btn-danger" asp-action="Delete" asp-route-id="@item.ID">Delete</a>
        </td>
    </tr>
    }
</tbody>
</code>```

Any help would really be appreciated.

答:
i think the issue
sermon => DateTime.Now

you are sorting by DateTime.Now?
if sermon has date added field
sermon => dateadded for example

Title: ASP.NET MVC - Order By Date

Body:
I am trying to sort table (columns: ID, Name, SermonDate, SermonTitle, BibleReading, VideoLink, BulletinLink) by date (SermonDate) so the data with the newest date comes on top and display it in my MVC application.

After some researching, I've tried putting the below with reference to this and this but nothing worked for me - probably because I misunderstood and put wrong code though.

public async Task<IActionResult> Index()
{
     return View(await _context.Sermon.OrderBy(sermon =>
     DateTime.Now).Take(5).ToListAsync());
}

My current controller (SermonsController.cs):

public SermonsController(BKPCContext context)
    {
        _context = context;
    }

    public async Task<IActionResult> Index()
    {
        return View(await _context.Sermon.OrderBy(sermon => DateTime.Now).Take(5).ToListAsync());
    }

    public async Task<IActionResult> Details(int? id)
    {
        if (id == null)
        {
            return NotFound();
        }

        var sermon = await _context.Sermon
            .SingleOrDefaultAsync(m => m.ID == id);
        if (sermon == null)
        {
            return NotFound();
        }

        return View(sermon);
    }

    public IActionResult Create()
    {
        return View();
    }

    [HttpPost]
    [ValidateAntiForgeryToken]
    public async Task<IActionResult> Create([Bind("ID,Name,SermonDate,SermonTitle,BibleReading,VideoLink,BulletinLink")] Sermon sermon)
    {
        if (ModelState.IsValid)
        {
            _context.Add(sermon);
            await _context.SaveChangesAsync();
            return RedirectToAction("Index");
        }
        return View(sermon);
    }

And the html table in /Sermons/Index.cshtml as below:

            @Html.DisplayNameFor(model => model.Name)

            @Html.DisplayNameFor(model => model.SermonDate)

            @Html.DisplayNameFor(model => model.SermonTitle)

            @Html.DisplayNameFor(model => model.BibleReading)

            @Html.DisplayNameFor(model => model.VideoLink)

            @Html.DisplayNameFor(model => model.BulletinLink)

@foreach (var item in Model) {

            @Html.DisplayFor(modelItem => item.Name)

            @Html.DisplayFor(modelItem => item.SermonDate)

            @Html.DisplayFor(modelItem => item.SermonTitle)

            @Html.DisplayFor(modelItem => item.BibleReading)

            @Html.DisplayFor(modelItem => item.VideoLink)

            @Html.DisplayFor(modelItem => item.BulletinLink)

            Edit
            Delete

    }

Any help would really be appreciated.


问:
Sonarqube not showing any c# issues
I installed Sonarqube in the same machine where I installed Jenkins. I'm starting a build everytime there is a push on gitlab, the build runs and sonar reports a correct build.

However I added code that is Noncompliant with the current profile (the default for c#).

Sonar.project-propertries:

```<code>sonar.projectKey=devkey:develop
sonar.projectName=FML
sonar.projectVersion=master

sonar.sources=.
sonar.language=cs
sonar.sourceEncoding=UTF-8
</code>```

build log:

```<code>22:43:34 [ExampleJob] $ /opt/sonar-scanner-3.0.3.778-linux/bin/sonar-scanner
-e -Dsonar.host.url=http://........... ******** -
Dsonar.projectBaseDir=/var/lib/jenkins/workspace/ExampleJob
22:43:34 INFO: Option -e/--errors is no longer supported and will be ignored
22:43:34 INFO: Scanner configuration file: /opt/sonar-scanner-3.0.3.778-
linux/conf/sonar-scanner.properties
22:43:34 INFO: Project root configuration file: /var/lib/jenkins/workspace/ExampleJob/sonar-project.properties
22:43:34 INFO: SonarQube Scanner 3.0.3.778
22:43:34 INFO: Java 1.8.0_121 Oracle Corporation (64-bit)
22:43:34 INFO: Linux 3.13.0-119-generic amd64
22:43:35 INFO: User cache: /var/lib/jenkins/.sonar/cache
22:43:36 INFO: Load global settings
22:43:36 INFO: Load global settings (done) | time=134ms
22:43:36 INFO: User cache: /var/lib/jenkins/.sonar/cache
22:43:36 INFO: Load plugins index
22:43:36 INFO: Load plugins index (done) | time=5ms
22:43:37 INFO: SonarQube server 6.4.0
22:43:37 INFO: Default locale: "en_US", source code encoding: "UTF-8"
22:43:37 INFO: Process project properties
22:43:38 INFO: Load project repositories
22:43:38 INFO: Load project repositories (done) | time=150ms
22:43:38 INFO: Execute project builders
22:43:38 INFO: Execute project builders (done) | time=1ms
22:43:38 INFO: Load quality profiles
22:43:38 INFO: Load quality profiles (done) | time=29ms
22:43:38 INFO: Load active rules
22:43:39 INFO: Load active rules (done) | time=515ms
22:43:39 INFO: Load metrics repository
22:43:39 INFO: Load metrics repository (done) | time=112ms
22:43:39 INFO: Publish mode
22:43:39 INFO: Project key: devkey:develop
22:43:39 INFO: -------------  Scan FML
22:43:39 INFO: Load server rules
22:43:39 INFO: Load server rules (done) | time=101ms
22:43:39 INFO: Language is forced to cs
22:43:39 INFO: Initializer GenericCoverageSensor
22:43:39 INFO: Initializer GenericCoverageSensor (done) | time=0ms
22:43:39 INFO: Base dir: /var/lib/jenkins/workspace/ExampleJob
22:43:39 INFO: Working dir: /var/lib/jenkins/workspace/ExampleJob/.scannerwork
22:43:39 INFO: Source paths: .
22:43:39 INFO: Source encoding: UTF-8, default locale: en_US
22:43:39 INFO: Index files
22:43:40 WARN: File '/var/lib/jenkins/workspace/ExampleJob/TestProj/Assets/TestScript.cs.meta' is ignored because it doesn't belong to the forced language 'cs'
22:43:40 WARN: File '/var/lib/jenkins/workspace/ExampleJob/TestProj/Assets/SceneViewWindow.cs.meta' is ignored because it doesn't belong to the forced language 'cs'
22:43:40 WARN: File '/var/lib/jenkins/workspace/ExampleJob/TestProj/ProjectSettings/GraphicsSettings.asset' is ignored because it doesn't belong to the forced language 'cs'
22:43:40 WARN: File '/var/lib/jenkins/workspace/ExampleJob/TestProj/ProjectSettings/Physics2DSettings.asset' is ignored because it doesn't belong to the forced language 'cs'
22:43:40 WARN: File '/var/lib/jenkins/workspace/ExampleJob/TestProj/ProjectSettings/ClusterInputManager.asset' is ignored because it doesn't belong to the forced language 'cs'
22:43:40 WARN: File '/var/lib/jenkins/workspace/ExampleJob/TestProj/ProjectSettings/AudioManager.asset' is ignored because it doesn't belong to the forced language 'cs'
22:43:40 WARN: File '/var/lib/jenkins/workspace/ExampleJob/TestProj/ProjectSettings/EditorBuildSettings.asset' is ignored because it doesn't belong to the forced language 'cs'
22:43:40 WARN: File '/var/lib/jenkins/workspace/ExampleJob/TestProj/ProjectSettings/DynamicsManager.asset' is ignored because it doesn't belong to the forced language 'cs'
22:43:40 WARN: File '/var/lib/jenkins/workspace/ExampleJob/TestProj/ProjectSettings/QualitySettings.asset' is ignored because it doesn't belong to the forced language 'cs'
22:43:40 WARN: File '/var/lib/jenkins/workspace/ExampleJob/TestProj/ProjectSettings/NetworkManager.asset' is ignored because it doesn't belong to the forced language 'cs'
22:43:40 WARN: File '/var/lib/jenkins/workspace/ExampleJob/TestProj/ProjectSettings/TagManager.asset' is ignored because it doesn't belong to the forced language 'cs'
22:43:40 WARN: File '/var/lib/jenkins/workspace/ExampleJob/TestProj/ProjectSettings/InputManager.asset' is ignored because it doesn't belong to the forced language 'cs'
22:43:40 WARN: File '/var/lib/jenkins/workspace/ExampleJob/TestProj/ProjectSettings/UnityConnectSettings.asset' is ignored because it doesn't belong to the forced language 'cs'
22:43:40 WARN: File '/var/lib/jenkins/workspace/ExampleJob/TestProj/ProjectSettings/EditorSettings.asset' is ignored because it doesn't belong to the forced language 'cs'
22:43:40 WARN: File '/var/lib/jenkins/workspace/ExampleJob/TestProj/ProjectSettings/NavMeshAreas.asset' is ignored because it doesn't belong to the forced language 'cs'
22:43:40 WARN: File '/var/lib/jenkins/workspace/ExampleJob/TestProj/ProjectSettings/TimeManager.asset' is ignored because it doesn't belong to the forced language 'cs'
22:43:40 WARN: File '/var/lib/jenkins/workspace/ExampleJob/TestProj/ProjectSettings/ProjectSettings.asset' is ignored because it doesn't belong to the forced language 'cs'
22:43:40 WARN: File '/var/lib/jenkins/workspace/ExampleJob/TestProj/ProjectSettings/ProjectVersion.txt' is ignored because it doesn't belong to the forced language 'cs'
22:43:40 WARN: File '/var/lib/jenkins/workspace/ExampleJob/sonar-project.properties' is ignored because it doesn't belong to the forced language 'cs'
22:43:40 WARN: File '/var/lib/jenkins/workspace/ExampleJob/README.md' is ignored because it doesn't belong to the forced language 'cs'
22:43:40 INFO: 2 files indexed
22:43:40 INFO: Quality profile for cs: Sonar way
22:43:41 INFO: Sensor C# [csharp]
22:43:41 INFO: Sensor C# [csharp] (done) | time=11ms
22:43:41 INFO: Sensor SonarJavaXmlFileSensor [java]
22:43:41 INFO: Sensor SonarJavaXmlFileSensor [java] (done) | time=0ms
22:43:41 INFO: Sensor Analyzer for "php.ini" files [php]
22:43:41 INFO: Sensor Analyzer for "php.ini" files [php] (done) | time=8ms
22:43:41 INFO: Sensor C# Unit Tests Coverage Report Import [csharp]
22:43:41 INFO: Sensor C# Unit Tests Coverage Report Import [csharp] (done) | time=0ms
22:43:41 INFO: Sensor C# Integration Tests Coverage Report Import [csharp]
22:43:41 INFO: Sensor C# Integration Tests Coverage Report Import [csharp] (done) | time=0ms
22:43:41 INFO: Sensor C# Unit Test Results Import [csharp]
22:43:41 INFO: Sensor C# Unit Test Results Import [csharp] (done) | time=0ms
22:43:41 INFO: Sensor Zero Coverage Sensor
22:43:41 INFO: Sensor Zero Coverage Sensor (done) | time=21ms
22:43:41 INFO: Sensor CPD Block Indexer
22:43:41 INFO: Sensor CPD Block Indexer (done) | time=1ms
22:43:42 INFO: SCM provider for this project is: git
22:43:42 INFO: 2 files to be analyzed
22:43:42 INFO: 2/2 files analyzed
22:43:42 INFO: Calculating CPD for 0 files
22:43:42 INFO: CPD calculation finished
22:43:42 INFO: Analysis report generated in 144ms, dir size=23 KB
22:43:42 INFO: Analysis reports compressed in 19ms, zip size=7 KB
22:43:43 INFO: Analysis report uploaded in 381ms
22:43:43 INFO: ANALYSIS SUCCESSFUL, you can browse http://.............
22:43:43 INFO: Note that you will be able to access the updated dashboard once the server has processed the submitted analysis report
22:43:43 INFO: More about the report processing at http://.............
22:43:43 INFO: Task total time: 5.951 s
22:43:43 INFO: ------------------------------------------------------------------------
22:43:43 INFO: EXECUTION SUCCESS
22:43:43 INFO: ------------------------------------------------------------------------
22:43:43 INFO: Total time: 8.665s
22:43:43 INFO: Final Memory: 46M/198M
22:43:43 INFO: ------------------------------------------------------------------------
22:43:44 Finished: SUCCESS
</code>```

答:
You shouldn't be using SonarQube Scanner for C#, but SonarQube Scanner for MSBuild. Why? Because properties files are typically extremely difficult to configure accurately by hand for C# projects. A misconfiguration is probably what you're experiencing.

Using the SonarQube Scanner for MSBuild, you'll bookend your build with scanner begin and end calls like so:

```<code>SonarQube.Scanner.MSBuild.exe begin /k:"org.sonarqube:sonarqube-scanner-msbuild" /n:"Project Name" /v:"1.0"
MSBuild.exe /t:Rebuild
SonarQube.Scanner.MSBuild.exe end
</code>```

Using the SonarQube Scanner for MSBuild, you don't need a properties file. Most of the values are read from your solution file, and the rest are passed on the initial commandline as shown above.

Title: Sonarqube not showing any c# issues

Body:
I installed Sonarqube in the same machine where I installed Jenkins. I'm starting a build everytime there is a push on gitlab, the build runs and sonar reports a correct build.

However I added code that is Noncompliant with the current profile (the default for c#).

Sonar.project-propertries:

sonar.projectKey=devkey:develop
sonar.projectName=FML
sonar.projectVersion=master

sonar.sources=.
sonar.language=cs
sonar.sourceEncoding=UTF-8

build log:

22:43:34 [ExampleJob] $ /opt/sonar-scanner-3.0.3.778-linux/bin/sonar-scanner
-e -Dsonar.host.url=http://........... ******** -
Dsonar.projectBaseDir=/var/lib/jenkins/workspace/ExampleJob
22:43:34 INFO: Option -e/--errors is no longer supported and will be ignored
22:43:34 INFO: Scanner configuration file: /opt/sonar-scanner-3.0.3.778-
linux/conf/sonar-scanner.properties
22:43:34 INFO: Project root configuration file: /var/lib/jenkins/workspace/ExampleJob/sonar-project.properties
22:43:34 INFO: SonarQube Scanner 3.0.3.778
22:43:34 INFO: Java 1.8.0_121 Oracle Corporation (64-bit)
22:43:34 INFO: Linux 3.13.0-119-generic amd64
22:43:35 INFO: User cache: /var/lib/jenkins/.sonar/cache
22:43:36 INFO: Load global settings
22:43:36 INFO: Load global settings (done) | time=134ms
22:43:36 INFO: User cache: /var/lib/jenkins/.sonar/cache
22:43:36 INFO: Load plugins index
22:43:36 INFO: Load plugins index (done) | time=5ms
22:43:37 INFO: SonarQube server 6.4.0
22:43:37 INFO: Default locale: "en_US", source code encoding: "UTF-8"
22:43:37 INFO: Process project properties
22:43:38 INFO: Load project repositories
22:43:38 INFO: Load project repositories (done) | time=150ms
22:43:38 INFO: Execute project builders
22:43:38 INFO: Execute project builders (done) | time=1ms
22:43:38 INFO: Load quality profiles
22:43:38 INFO: Load quality profiles (done) | time=29ms
22:43:38 INFO: Load active rules
22:43:39 INFO: Load active rules (done) | time=515ms
22:43:39 INFO: Load metrics repository
22:43:39 INFO: Load metrics repository (done) | time=112ms
22:43:39 INFO: Publish mode
22:43:39 INFO: Project key: devkey:develop
22:43:39 INFO: -------------  Scan FML
22:43:39 INFO: Load server rules
22:43:39 INFO: Load server rules (done) | time=101ms
22:43:39 INFO: Language is forced to cs
22:43:39 INFO: Initializer GenericCoverageSensor
22:43:39 INFO: Initializer GenericCoverageSensor (done) | time=0ms
22:43:39 INFO: Base dir: /var/lib/jenkins/workspace/ExampleJob
22:43:39 INFO: Working dir: /var/lib/jenkins/workspace/ExampleJob/.scannerwork
22:43:39 INFO: Source paths: .
22:43:39 INFO: Source encoding: UTF-8, default locale: en_US
22:43:39 INFO: Index files
22:43:40 WARN: File '/var/lib/jenkins/workspace/ExampleJob/TestProj/Assets/TestScript.cs.meta' is ignored because it doesn't belong to the forced language 'cs'
22:43:40 WARN: File '/var/lib/jenkins/workspace/ExampleJob/TestProj/Assets/SceneViewWindow.cs.meta' is ignored because it doesn't belong to the forced language 'cs'
22:43:40 WARN: File '/var/lib/jenkins/workspace/ExampleJob/TestProj/ProjectSettings/GraphicsSettings.asset' is ignored because it doesn't belong to the forced language 'cs'
22:43:40 WARN: File '/var/lib/jenkins/workspace/ExampleJob/TestProj/ProjectSettings/Physics2DSettings.asset' is ignored because it doesn't belong to the forced language 'cs'
22:43:40 WARN: File '/var/lib/jenkins/workspace/ExampleJob/TestProj/ProjectSettings/ClusterInputManager.asset' is ignored because it doesn't belong to the forced language 'cs'
22:43:40 WARN: File '/var/lib/jenkins/workspace/ExampleJob/TestProj/ProjectSettings/AudioManager.asset' is ignored because it doesn't belong to the forced language 'cs'
22:43:40 WARN: File '/var/lib/jenkins/workspace/ExampleJob/TestProj/ProjectSettings/EditorBuildSettings.asset' is ignored because it doesn't belong to the forced language 'cs'
22:43:40 WARN: File '/var/lib/jenkins/workspace/ExampleJob/TestProj/ProjectSettings/DynamicsManager.asset' is ignored because it doesn't belong to the forced language 'cs'
22:43:40 WARN: File '/var/lib/jenkins/workspace/ExampleJob/TestProj/ProjectSettings/QualitySettings.asset' is ignored because it doesn't belong to the forced language 'cs'
22:43:40 WARN: File '/var/lib/jenkins/workspace/ExampleJob/TestProj/ProjectSettings/NetworkManager.asset' is ignored because it doesn't belong to the forced language 'cs'
22:43:40 WARN: File '/var/lib/jenkins/workspace/ExampleJob/TestProj/ProjectSettings/TagManager.asset' is ignored because it doesn't belong to the forced language 'cs'
22:43:40 WARN: File '/var/lib/jenkins/workspace/ExampleJob/TestProj/ProjectSettings/InputManager.asset' is ignored because it doesn't belong to the forced language 'cs'
22:43:40 WARN: File '/var/lib/jenkins/workspace/ExampleJob/TestProj/ProjectSettings/UnityConnectSettings.asset' is ignored because it doesn't belong to the forced language 'cs'
22:43:40 WARN: File '/var/lib/jenkins/workspace/ExampleJob/TestProj/ProjectSettings/EditorSettings.asset' is ignored because it doesn't belong to the forced language 'cs'
22:43:40 WARN: File '/var/lib/jenkins/workspace/ExampleJob/TestProj/ProjectSettings/NavMeshAreas.asset' is ignored because it doesn't belong to the forced language 'cs'
22:43:40 WARN: File '/var/lib/jenkins/workspace/ExampleJob/TestProj/ProjectSettings/TimeManager.asset' is ignored because it doesn't belong to the forced language 'cs'
22:43:40 WARN: File '/var/lib/jenkins/workspace/ExampleJob/TestProj/ProjectSettings/ProjectSettings.asset' is ignored because it doesn't belong to the forced language 'cs'
22:43:40 WARN: File '/var/lib/jenkins/workspace/ExampleJob/TestProj/ProjectSettings/ProjectVersion.txt' is ignored because it doesn't belong to the forced language 'cs'
22:43:40 WARN: File '/var/lib/jenkins/workspace/ExampleJob/sonar-project.properties' is ignored because it doesn't belong to the forced language 'cs'
22:43:40 WARN: File '/var/lib/jenkins/workspace/ExampleJob/README.md' is ignored because it doesn't belong to the forced language 'cs'
22:43:40 INFO: 2 files indexed
22:43:40 INFO: Quality profile for cs: Sonar way
22:43:41 INFO: Sensor C# [csharp]
22:43:41 INFO: Sensor C# [csharp] (done) | time=11ms
22:43:41 INFO: Sensor SonarJavaXmlFileSensor [java]
22:43:41 INFO: Sensor SonarJavaXmlFileSensor [java] (done) | time=0ms
22:43:41 INFO: Sensor Analyzer for "php.ini" files [php]
22:43:41 INFO: Sensor Analyzer for "php.ini" files [php] (done) | time=8ms
22:43:41 INFO: Sensor C# Unit Tests Coverage Report Import [csharp]
22:43:41 INFO: Sensor C# Unit Tests Coverage Report Import [csharp] (done) | time=0ms
22:43:41 INFO: Sensor C# Integration Tests Coverage Report Import [csharp]
22:43:41 INFO: Sensor C# Integration Tests Coverage Report Import [csharp] (done) | time=0ms
22:43:41 INFO: Sensor C# Unit Test Results Import [csharp]
22:43:41 INFO: Sensor C# Unit Test Results Import [csharp] (done) | time=0ms
22:43:41 INFO: Sensor Zero Coverage Sensor
22:43:41 INFO: Sensor Zero Coverage Sensor (done) | time=21ms
22:43:41 INFO: Sensor CPD Block Indexer
22:43:41 INFO: Sensor CPD Block Indexer (done) | time=1ms
22:43:42 INFO: SCM provider for this project is: git
22:43:42 INFO: 2 files to be analyzed
22:43:42 INFO: 2/2 files analyzed
22:43:42 INFO: Calculating CPD for 0 files
22:43:42 INFO: CPD calculation finished
22:43:42 INFO: Analysis report generated in 144ms, dir size=23 KB
22:43:42 INFO: Analysis reports compressed in 19ms, zip size=7 KB
22:43:43 INFO: Analysis report uploaded in 381ms
22:43:43 INFO: ANALYSIS SUCCESSFUL, you can browse http://.............
22:43:43 INFO: Note that you will be able to access the updated dashboard once the server has processed the submitted analysis report
22:43:43 INFO: More about the report processing at http://.............
22:43:43 INFO: Task total time: 5.951 s
22:43:43 INFO: ------------------------------------------------------------------------
22:43:43 INFO: EXECUTION SUCCESS
22:43:43 INFO: ------------------------------------------------------------------------
22:43:43 INFO: Total time: 8.665s
22:43:43 INFO: Final Memory: 46M/198M
22:43:43 INFO: ------------------------------------------------------------------------
22:43:44 Finished: SUCCESS

Body:
You shouldn't be using SonarQube Scanner for C#, but SonarQube Scanner for MSBuild. Why? Because properties files are typically extremely difficult to configure accurately by hand for C# projects. A misconfiguration is probably what you're experiencing.

Using the SonarQube Scanner for MSBuild, you'll bookend your build with scanner begin and end calls like so:

SonarQube.Scanner.MSBuild.exe begin /k:"org.sonarqube:sonarqube-scanner-msbuild" /n:"Project Name" /v:"1.0"
MSBuild.exe /t:Rebuild
SonarQube.Scanner.MSBuild.exe end

Using the SonarQube Scanner for MSBuild, you don't need a properties file. Most of the values are read from your solution file, and the rest are passed on the initial commandline as shown above.


问:
When running on Nougat, why does the title gets cut off when using a CollapsingToolbarLayout?
I'm using the following layout and it works great on all versions except Android Nougat where the title gets cut off when fully collapsed.

```<code><android.support.design.widget.CollapsingToolbarLayout
            android:id="@+id/collapsing_toolbar"
            android:layout_width="match_parent"
            android:layout_height="300dp"
            android:fitsSystemWindows="true"
            app:contentScrim="@color/them_color"
            app:expandedTitleTextAppearance="@android:color/transparent"
            app:layout_scrollFlags="scroll|exitUntilCollapsed">

            <ImageView
                android:id="@+id/header_image"
                android:layout_width="match_parent"
                android:layout_height="300dp"
                android:contentDescription="@string/app_name"
                android:fitsSystemWindows="true"
                android:scaleType="fitXY"
                app:layout_collapseMode="parallax"/>

            <android.support.v7.widget.Toolbar
                android:id="@+id/toolbar"
                android:layout_width="match_parent"
                android:layout_height="?android:attr/actionBarSize"
                app:layout_collapseMode="pin"
                app:contentInsetLeft="0dp"
                app:popupTheme="@style/ThemeOverlay.AppCompat.Light"/>

        </android.support.design.widget.CollapsingToolbarLayout>
</code>```

I have tried app:collapsedTitleGravity="center" but it doesn't fix the issue. How can I make it work on Nougat?

答:
removing android:fitsSystemWindows="true"
solved my problem </p>

Body:
I'm using the following layout and it works great on all versions except Android Nougat where the title gets cut off when fully collapsed.

<android.support.design.widget.CollapsingToolbarLayout
            android:id="@+id/collapsing_toolbar"
            android:layout_width="match_parent"
            android:layout_height="300dp"
            android:fitsSystemWindows="true"
            app:contentScrim="@color/them_color"
            app:expandedTitleTextAppearance="@android:color/transparent"
            app:layout_scrollFlags="scroll|exitUntilCollapsed">

            <ImageView
                android:id="@+id/header_image"
                android:layout_width="match_parent"
                android:layout_height="300dp"
                android:contentDescription="@string/app_name"
                android:fitsSystemWindows="true"
                android:scaleType="fitXY"
                app:layout_collapseMode="parallax"/>

            <android.support.v7.widget.Toolbar
                android:id="@+id/toolbar"
                android:layout_width="match_parent"
                android:layout_height="?android:attr/actionBarSize"
                app:layout_collapseMode="pin"
                app:contentInsetLeft="0dp"
                app:popupTheme="@style/ThemeOverlay.AppCompat.Light"/>

        </android.support.design.widget.CollapsingToolbarLayout>

I have tried app:collapsedTitleGravity="center" but it doesn't fix the issue. How can I make it work on Nougat?


问:
Framework for user defined relationships
I'm thinking about creating a Django-powered website where users would be able to relate entities to each other. Examples would for instance include: "John is married to Mary" or "John works at Google".

Users should be able to define the entities and their relationships themselves (and will typically define relations of other people, not of themselves). Ideally, users enter these relations as free text (where subject and object could perhaps be an autocomplete field, based on previously entered existing entities).

Django's model framework is ideal for storing the entities and their relations, but how would one make such a thing manageable on a higher level?

Is there a Python-powered ontological framework (thanks duffymo) that would help me derive structure out of these user-generated relationships? I'm looking for ways to for example derive reversible relations, aggregate relations (e.g. "3 persons are family relations of John"), classify into types of relations (family relations, work relations, ...), and this all based on user generated input and not a (known) predefined set of relations. It

Thanks in advance,

Mathieu

答:
Disclaimer:  I am not an expect.   I'm learning Django in my spare time.   That said..

You may want to look at the "many to many through" as a field relationship.

From the docs:

http://docs.djangoproject.com/en/dev/topics/db/models/

When you're only dealing with simple
  many-to-many relationships such as
  mixing and matching pizzas and
  toppings, a standard ManyToManyField
  is all you need. However, sometimes
  you may need to associate data with
  the relationship between two models.

Where the syntax look like this (also from the example in the docs):

```<code>class Group(models.Model):
    name = models.CharField(max_length=128)
    members = models.ManyToManyField(Person, through='Membership')

    def __unicode__(self):
        return self.name
</code>```

Body:
Disclaimer:  I am not an expect.   I'm learning Django in my spare time.   That said..

You may want to look at the "many to many through" as a field relationship.

From the docs:

http://docs.djangoproject.com/en/dev/topics/db/models/

When you're only dealing with simple
  many-to-many relationships such as
  mixing and matching pizzas and
  toppings, a standard ManyToManyField
  is all you need. However, sometimes
  you may need to associate data with
  the relationship between two models.

Where the syntax look like this (also from the example in the docs):

class Group(models.Model):
    name = models.CharField(max_length=128)
    members = models.ManyToManyField(Person, through='Membership')

    def __unicode__(self):
        return self.name


问:
Python: Perform Google Search and extract only the content from the individual top 10 results
I am trying to write a script which performs a Google search for the input keyword and returns only the content from the top 10 URLs.

Note: Content specifically refers to the content that is being requested by the searched term and is found in the body of the returned URLs.

I am done with the search and top 10 url retrieval part. Here is the script:

```<code>from google import search
top_10_links = search(keyword, tld='com.in', lang='en',stop=10)
</code>```

however i am unable to retrieve only the content from the links without knowing their structure. I can scrape content from a particular site by finding the class etc. of the tags using dev tools.But i am unable to figure out how to get content from the top 10 result URLs since for every searched term there are different URLs(different sites have different css selectors) and it would to pretty hard to find the css class of the required content. here is the sample code to extract content from a particular site.

```<code>content_dict = {}
i = 1
for page in links:
    print(i, ' @ link: ', page)
    article_html = get_page(page)#get_page() returns page's html
    soup = BeautifulSoup(article_html, 'lxml')
    content = soup.find('div',{'class': 'entry-content'}).get_text()
    content_dict[page] = content
    i += 1
</code>```

However the css class changes for the different sites. Is there someway i can get this script working and get the desired content?

答: You can't do scraping without knowing the structure of what you're scraping.But there is a package that does something similar. Take a look at newspaper

Body:
I am trying to write a script which performs a Google search for the input keyword and returns only the content from the top 10 URLs.

Note: Content specifically refers to the content that is being requested by the searched term and is found in the body of the returned URLs.

I am done with the search and top 10 url retrieval part. Here is the script:

from google import search
top_10_links = search(keyword, tld='com.in', lang='en',stop=10)

however i am unable to retrieve only the content from the links without knowing their structure. I can scrape content from a particular site by finding the class etc. of the tags using dev tools.But i am unable to figure out how to get content from the top 10 result URLs since for every searched term there are different URLs(different sites have different css selectors) and it would to pretty hard to find the css class of the required content. here is the sample code to extract content from a particular site.

content_dict = {}
i = 1
for page in links:
    print(i, ' @ link: ', page)
    article_html = get_page(page)#get_page() returns page's html
    soup = BeautifulSoup(article_html, 'lxml')
    content = soup.find('div',{'class': 'entry-content'}).get_text()
    content_dict[page] = content
    i += 1

However the css class changes for the different sites. Is there someway i can get this script working and get the desired content?


问:
How to transform list of objects into one row object in java
I have a class A having private members like below.

```<code>class A {
  String type;
}
</code>```

The above class will come as list objects List . Now  i have Another  class B

```<code>Class B {
  String type1;
  String type2;
  String type3;
  String type4;
  String type5;
  String type6;
  String type7;
  String type8;
}
</code>```

So  Now How i have to iterate through List  and get the (type(s)) data one by one and then put it into Class B as single object like first one will go to Type1 , second one  ---> type2, third one--- > type3 ....., so on.
Note : There will be only 8 types in class A as a list . so we will have exactly 8 types in Class B and i have thought on reflection so please tell how do i use it, if this is the only option.

答:
Jasper supports Map, so I would suggest you can store the values in a SortedMap, such as a TreeMap rather than a class with public variables.

Then you would add your type names like this:

```<code>Map<String, String> b = new TreeMap<>();
b.put("type1", "Foo");
b.put("type2", "Bar");
b.put("type3", "Baz");
...
</code>```

Or if you're populating from a list of A:

```<code>List<A> list = ...;
Map<String, String> b = new TreeMap<>();
for (int i = 0; i < list.size(); i++) {
    b.put("type" + (i + 1), list.get(i).type;
}
</code>```

To iterate over all the names in the map, you could then use:

```<code>for (Map.Entry<String, String> entry: b.entrySet()) {
    String key = entry.key();
    String value = entry.value();
    System.out.println(key + " = " + value);
}
</code>```

Body:
I have a class A having private members like below.

class A {
  String type;
}

The above class will come as list objects List . Now  i have Another  class B

Class B {
  String type1;
  String type2;
  String type3;
  String type4;
  String type5;
  String type6;
  String type7;
  String type8;
}

So  Now How i have to iterate through List  and get the (type(s)) data one by one and then put it into Class B as single object like first one will go to Type1 , second one  ---> type2, third one--- > type3 ....., so on.
Note : There will be only 8 types in class A as a list . so we will have exactly 8 types in Class B and i have thought on reflection so please tell how do i use it, if this is the only option.

Body:
Jasper supports Map, so I would suggest you can store the values in a SortedMap, such as a TreeMap rather than a class with public variables.

Then you would add your type names like this:

Map<String, String> b = new TreeMap<>();
b.put("type1", "Foo");
b.put("type2", "Bar");
b.put("type3", "Baz");
...

Or if you're populating from a list of A:

List<A> list = ...;
Map<String, String> b = new TreeMap<>();
for (int i = 0; i < list.size(); i++) {
    b.put("type" + (i + 1), list.get(i).type;
}

To iterate over all the names in the map, you could then use:

for (Map.Entry<String, String> entry: b.entrySet()) {
    String key = entry.key();
    String value = entry.value();
    System.out.println(key + " = " + value);
}


问:
Python-Django utf-8 csv.writer
im using python csv library for exporting my models into a csv file in django.
codes are like this :

```<code>import csv
from django.http import HttpResponse

def some_view(request):
    # Create the HttpResponse object with the appropriate CSV header.
    response = HttpResponse(content_type='text/csv')
    response['Content-Disposition'] = 'attachment; filename="somefilename.csv"'

    writer = csv.writer(response)
    writer.writerow(['First row', 'Foo', 'Bar', 'Baz'])
    writer.writerow(['Second row', 'A', 'B', 'C', '"Testing"', "Here's a quote"])

    return response
</code>```

My problem :
in my database i have some persian characters that just works with utf-8 encoding format , so when i open generated csv file in excel the persian characters not shown correctly.

答:
i try encode('UTF-8') Solution in some cases, but the result in microsoft excel is not readable , it shows b'\xd8\xb1\xdb\x8c\xd8'.
However i find the correct way for showing CSV in excel readable.

```<code>import csv
from django.http import HttpResponse

def some_view(request):
    # Create the HttpResponse object with the appropriate CSV header.
    response = HttpResponse(content_type='text/csv')
    response['Content-Disposition'] = 'attachment; filename="somefilename.csv"'

    response.write(u'\ufeff'.encode('utf8'))
    writer = csv.writer(response)
    writer.writerow(['First row', 'Foo', 'Bar', 'Baz'])
    writer.writerow(['Second row', 'A', 'B', 'C', '"Testing"', "Here's a quote"])

    return response
</code>```

Just add response.write(u'\ufeff'.encode('utf8')) into the code

Title: Python-Django utf-8 csv.writer

Body:
im using python csv library for exporting my models into a csv file in django.
codes are like this :

import csv
from django.http import HttpResponse

def some_view(request):
    # Create the HttpResponse object with the appropriate CSV header.
    response = HttpResponse(content_type='text/csv')
    response['Content-Disposition'] = 'attachment; filename="somefilename.csv"'

    writer = csv.writer(response)
    writer.writerow(['First row', 'Foo', 'Bar', 'Baz'])
    writer.writerow(['Second row', 'A', 'B', 'C', '"Testing"', "Here's a quote"])

    return response

My problem :
in my database i have some persian characters that just works with utf-8 encoding format , so when i open generated csv file in excel the persian characters not shown correctly.

Body:
i try encode('UTF-8') Solution in some cases, but the result in microsoft excel is not readable , it shows b'\xd8\xb1\xdb\x8c\xd8'.
However i find the correct way for showing CSV in excel readable.

import csv
from django.http import HttpResponse

def some_view(request):
    # Create the HttpResponse object with the appropriate CSV header.
    response = HttpResponse(content_type='text/csv')
    response['Content-Disposition'] = 'attachment; filename="somefilename.csv"'

    response.write(u'\ufeff'.encode('utf8'))
    writer = csv.writer(response)
    writer.writerow(['First row', 'Foo', 'Bar', 'Baz'])
    writer.writerow(['Second row', 'A', 'B', 'C', '"Testing"', "Here's a quote"])

    return response

Just add response.write(u'\ufeff'.encode('utf8')) into the code


问:
DLL File can not add the C# project
I have HikVistion Finger print device, and SDK there are dll files,
When I add the DLL file it's getting this error massage,

if you have a solution for this please share with me,

Thank you,

答:
try to run from cmd the command:

```<code>TlbImp.exe HCNetSDK.dll
</code>```

it should create a valid dll for you.

TlbImp location : C:\Program Files (x86)\Microsoft
  SDKs\Windows\v7.0A\Bin

Tlbimp.exe (Type Library Importer)

The Type Library Importer converts the type definitions found within a COM type library into equivalent definitions in a common language runtime assembly. The output of Tlbimp.exe is a binary file (an assembly) that contains runtime metadata for the types defined within the original type library. You can examine this file with tools such as Ildasm.exe.
This tool is automatically installed with Visual Studio. To run the tool, use the Developer Command Prompt (or the Visual Studio Command Prompt in Windows 7). For more information, see Command Prompts.

If its not helping try to look if you have assembly dependency that your dll looks for.

Title: DLL File can not add the C# project

Body:
try to run from cmd the command:

TlbImp.exe HCNetSDK.dll

it should create a valid dll for you.

TlbImp location : C:\Program Files (x86)\Microsoft
  SDKs\Windows\v7.0A\Bin

Tlbimp.exe (Type Library Importer)

The Type Library Importer converts the type definitions found within a COM type library into equivalent definitions in a common language runtime assembly. The output of Tlbimp.exe is a binary file (an assembly) that contains runtime metadata for the types defined within the original type library. You can examine this file with tools such as Ildasm.exe.
This tool is automatically installed with Visual Studio. To run the tool, use the Developer Command Prompt (or the Visual Studio Command Prompt in Windows 7). For more information, see Command Prompts.

If its not helping try to look if you have assembly dependency that your dll looks for.


问:
C non-blocking keyboard input
I'm trying to write a program in C (on Linux) that loops until the user presses a key, but shouldn't require a keypress to continue each loop.

Is there a simple way to do this? I figure I could possibly do it with select() but that seems like a lot of work.

Alternatively, is there a way to catch a ctrl-c keypress to do cleanup before the program closes instead of non-blocking io?

答:
As already stated, you can use sigaction to trap ctrl-c, or select to trap any standard input.

Note however that with the latter method you also need to set the TTY so that it's in character-at-a-time rather than line-at-a-time mode.  The latter is the default - if you type in a line of text it doesn't get sent to the running program's stdin until you press enter.

You'd need to use the tcsetattr() function to turn off ICANON mode, and probably also disable ECHO too.  From memory, you also have to set the terminal back into ICANON mode when the program exits!

Just for completeness, here's some code I've just knocked up (nb: no error checking!) which sets up a Unix TTY and emulates the DOS <conio.h> functions kbhit() and getch():

```<code>#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/select.h>
#include <termios.h>

struct termios orig_termios;

void reset_terminal_mode()
{
    tcsetattr(0, TCSANOW, &orig_termios);
}

void set_conio_terminal_mode()
{
    struct termios new_termios;

    /* take two copies - one for now, one for later */
    tcgetattr(0, &orig_termios);
    memcpy(&new_termios, &orig_termios, sizeof(new_termios));

    /* register cleanup handler, and set the new terminal mode */
    atexit(reset_terminal_mode);
    cfmakeraw(&new_termios);
    tcsetattr(0, TCSANOW, &new_termios);
}

int kbhit()
{
    struct timeval tv = { 0L, 0L };
    fd_set fds;
    FD_ZERO(&fds);
    FD_SET(0, &fds);
    return select(1, &fds, NULL, NULL, &tv) > 0;
}

int getch()
{
    int r;
    unsigned char c;
    if ((r = read(0, &c, sizeof(c))) < 0) {
        return r;
    } else {
        return c;
    }
}

int main(int argc, char *argv[])
{
    set_conio_terminal_mode();

    while (!kbhit()) {
        /* do some work */
    }
    (void)getch(); /* consume the character */
}
</code>```

OwnerDisplayName: Zxaos

Title: C non-blocking keyboard input

LastEditorDisplayName: Zxaos

Body:
As already stated, you can use sigaction to trap ctrl-c, or select to trap any standard input.

Note however that with the latter method you also need to set the TTY so that it's in character-at-a-time rather than line-at-a-time mode.  The latter is the default - if you type in a line of text it doesn't get sent to the running program's stdin until you press enter.

You'd need to use the tcsetattr() function to turn off ICANON mode, and probably also disable ECHO too.  From memory, you also have to set the terminal back into ICANON mode when the program exits!

Just for completeness, here's some code I've just knocked up (nb: no error checking!) which sets up a Unix TTY and emulates the DOS <conio.h> functions kbhit() and getch():

#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/select.h>
#include <termios.h>

struct termios orig_termios;

void reset_terminal_mode()
{
    tcsetattr(0, TCSANOW, &orig_termios);
}

void set_conio_terminal_mode()
{
    struct termios new_termios;

    /* take two copies - one for now, one for later */
    tcgetattr(0, &orig_termios);
    memcpy(&new_termios, &orig_termios, sizeof(new_termios));

    /* register cleanup handler, and set the new terminal mode */
    atexit(reset_terminal_mode);
    cfmakeraw(&new_termios);
    tcsetattr(0, TCSANOW, &new_termios);
}

int kbhit()
{
    struct timeval tv = { 0L, 0L };
    fd_set fds;
    FD_ZERO(&fds);
    FD_SET(0, &fds);
    return select(1, &fds, NULL, NULL, &tv) > 0;
}

int getch()
{
    int r;
    unsigned char c;
    if ((r = read(0, &c, sizeof(c))) < 0) {
        return r;
    } else {
        return c;
    }
}

int main(int argc, char *argv[])
{
    set_conio_terminal_mode();

    while (!kbhit()) {
        /* do some work */
    }
    (void)getch(); /* consume the character */
}

OwnerDisplayName: Alnitak

ContentLicense: CC BY-SA 4.0

LastEditorDisplayName: Alnitak


问:
Preventing cheating for on-line arcade high score board
I'm going to be developing an online arcade for HTML5/Javascript games written in a to-be-released IDE.

The game will use Ajax requests to the server to record scores when people play these games.

I theoretically have complete control over the design of this, including the mechanics of the code that logs the high scores, game code, everything.

I know it's never impossible to hack client side games such as this or spoof high scores, but I want to make it difficult enough so that anyone competent enough wont be bothered enough to do it (wishful thinking).

I've read:

How can you prevent bogus high scores from appearing on a global high score list?

Which is a slightly different question as this is HTML/JS specific.

My initial idea is that the ajax request checks the source of the request is from the correct location, which is a simple and effective block for most hacking attempts.

答:
Each time you serve the page include a randomly generated key and on the server associate the key with the users session.

pass this key around and manipulate it in obscure ways at various points in your game script.

generate a checksum derived from the score and the manipulated key.

send the checksum to the server along with the score

validate the checksum on the server

obfuscate the script

It won't stop a dedicated hacker though.


问:
UWP InkCanvas fill freehand drawn shape with color
I'm currently working on a UWP app which should allow the user to draw any shape he wants on a InkCanvas. This shapes edges are automatically completed so that there is no open space (Up to this point everything works just fine).

Now my question is: How do I automatically fill this shape with a single color (or a pattern)? I know that there is a "Point in Polygon" algorithm, but I have no idea how to implement it in the UWP InkCanvas, because I don't really get how to search for the points inside the shape without iterating over every point on the canvas.

Edit:
I actually got it done by using a "Canvas" as a overlay to draw a Polyline. By using the Polyline.Fill() method it worked. But I need the same effect on the "InkCanvas" only.

答:
Now my question is: How do I automatically fill this shape with a single color (or a pattern)? I know that there is a "Point in Polygon" algorithm, but I have no idea how to implement it in the UWP InkCanvas

You could redraw your Ink Strokes that exist in Ink Canvas by setting new InkDrawingAttributes for InkStroke.DrawingAttributes.

```<code>private void Button_Click(object sender, RoutedEventArgs e)
{
    InkDrawingAttributes attr = new InkDrawingAttributes();
    attr.Color = Colors.Red;
    attr.IgnorePressure = true;
    attr.PenTip = PenTipShape.Circle;
    attr.Size = new Size(4, 10);
    attr.PenTipTransform = Matrix3x2.CreateRotation((float)(70 * Math.PI / 180));
    IReadOnlyList<InkStroke> InkStrokeList = MyInk.InkPresenter.StrokeContainer.GetStrokes();
    foreach (InkStroke temp in InkStrokeList)
    {
        temp.DrawingAttributes = attr;
    }
}
</code>```

Body:
Now my question is: How do I automatically fill this shape with a single color (or a pattern)? I know that there is a "Point in Polygon" algorithm, but I have no idea how to implement it in the UWP InkCanvas

You could redraw your Ink Strokes that exist in Ink Canvas by setting new InkDrawingAttributes for InkStroke.DrawingAttributes.

private void Button_Click(object sender, RoutedEventArgs e)
{
    InkDrawingAttributes attr = new InkDrawingAttributes();
    attr.Color = Colors.Red;
    attr.IgnorePressure = true;
    attr.PenTip = PenTipShape.Circle;
    attr.Size = new Size(4, 10);
    attr.PenTipTransform = Matrix3x2.CreateRotation((float)(70 * Math.PI / 180));
    IReadOnlyList<InkStroke> InkStrokeList = MyInk.InkPresenter.StrokeContainer.GetStrokes();
    foreach (InkStroke temp in InkStrokeList)
    {
        temp.DrawingAttributes = attr;
    }
}


问:
How to use Reachability in Network Extension, it never callback
I use Reachability demo to check wifi connect, it work fine, now, i want use it in a network extension

Set callback is ok, but it nerver callback even network connect is change.

```<code>SCNetworkReachabilityContext context = {0, (__bridge void *)(self), NULL, NULL, NULL};
if (SCNetworkReachabilitySetCallback(_reachabilityRef, ReachabilityCallback, &context)) // return YES {
    if (SCNetworkReachabilityScheduleWithRunLoop(_reachabilityRef, CFRunLoopGetCurrent(), kCFRunLoopDefaultMode)) { //return YES
    //...
    }
}
</code>```

never call this:

```<code>static void ReachabilityCallback(SCNetworkReachabilityRef target, SCNetworkReachabilityFlags flags, void* info){
    //...
}
</code>```

答: Solve the problem by set callback in main thread，because if the thread is dead，it will never call back.</p>

Body:
I use Reachability demo to check wifi connect, it work fine, now, i want use it in a network extension

Set callback is ok, but it nerver callback even network connect is change.

SCNetworkReachabilityContext context = {0, (__bridge void *)(self), NULL, NULL, NULL};
if (SCNetworkReachabilitySetCallback(_reachabilityRef, ReachabilityCallback, &context)) // return YES {
    if (SCNetworkReachabilityScheduleWithRunLoop(_reachabilityRef, CFRunLoopGetCurrent(), kCFRunLoopDefaultMode)) { //return YES
    //...
    }
}

never call this:

static void ReachabilityCallback(SCNetworkReachabilityRef target, SCNetworkReachabilityFlags flags, void* info){
    //...
}