问:
Graphql postgresql promise executes after the results are returned
I'm trying out graphql.  I'm pulling my data from postgresql and everyting seems to work except for one issue where the resolve completes before the query has completed.  I though I had my query promise working correctly.  Here my class that I created to query the database:

```<code>class PgPoolClient {

    constructor(options) {
        this.connection = options.connection;
    }

    query(sql, data = []) {

        return new Promise((resolve, reject) => {
            var pool = new pg.Pool(this.connection);
            pool.connect((err, client, done) => {
                if (err) {
                    reject({
                        code: 505,
                        message: err.message,
                        entrys: []
                    });
                } else {
                    client.query(sql, data, (err, results) => {
                        done();
                        if (err) {
                            reject({
                                code: 404,
                                message: err.message,
                                entrys: []
                            });
                        } else {
                            resolve({
                                code: 200,
                                message: "ok",
                                entrys: results
                            });
                        }
                    });
                }
            });

            pool.on("error", (err, client) => {
                reject({
                    code: 505,
                    message: err.message,
                    entrys: {}
                });
            });

        });
    }
}
</code>```

Here is my graphql Query:

```<code>const Query = new GraphQLObjectType({
    name: 'Query',
    description: 'Root query object',
    fields: () => ({
        accounts: {
            type: new GraphQLList(Account),
            resolve(root, args) {

                const parameters = [];
                pg.query(`SELECT
id, token, user_identifier as userIdentifier, hash_password as hashPassword,
is_enabled as isEnabled, security_type_id as securityTypeID,
is_admin as isAdmin, ad_path as adPath, date_created as dateCreated,
date_modified as dateModified, modified_by as modifiedBy
FROM accounts.account`, parameters)
                .then((result) =>
                {
                    console.log(result.entrys.rows);
                    //return result.entrys.rows;
                    return [
                        {
                        id: '33333',
                        token: '111',
                        userIdentifier: 'test'
                        }
                    ]

                })
                .catch((err) =>
                {
                    console.log(err);
                    return err.message;
                });

                console.log('finished');
        }
    })
});
</code>```

I commented out my results and just wanted to see about returning static content and it seems that when its within then() the results don't get returned to graphisql (meaning the resolve completed before then() does).  with output:

```<code>{
  "data": {
   "accounts": null
 }
</code>```

}

I was able to verify this by putting the static return array below the console.log('finished') and it returns the data properly.

```<code>console.log('finished');
return [
    {
    id: '33333',
    token: '111',
    userIdentifier: 'test'
    }
]
</code>```

which shows up in graphiql:

```<code>{
  "data": {
    "accounts": [
      {
        "id": "33333",
        "token": "111",
        "userIdentifier": "test"
      }
    ]
  }
}
</code>```

So it seems that my Promise is not being waited on.  Is there something I'm missing in my query function that is causing the resolve not to wait for my results?  Any help would be appreciated.

Update 1

It seems if I wrapp the query in a Promise it works:

```<code>return new Promise((resolve, reject) => {

pg.query(`SELECT
id, token, user_identifier as userIdentifier, hash_password as hashPassword,
is_enabled as isEnabled, security_type_id as securityTypeID,
is_admin as isAdmin, ad_path as adPath, date_created as dateCreated,
date_modified as dateModified, modified_by as modifiedBy
FROM accounts.account`, parameters)
.then((result) =>
{
    console.log(result.entrys.rows);
    //return result.entrys.rows;
    resolve( [
        {
        id: '33333',
        token: '111',
        userIdentifier: 'test'
        }
    ]);

})
.catch((err) =>
{
    console.log(err);
    reject(err.message);
});
</code>```

I guess my question is if my query function is already wrapped in a Promise, why do I have to do it again?

答:
Your resolve function needs to return the promise. When you explicitly wrapped it in a promise, it worked because you returned it. It should work without that if you return the result of calling pg.query.

```<code>const Query = new GraphQLObjectType({
name: 'Query',
description: 'Root query object',
fields: () => ({
    accounts: {
        type: new GraphQLList(Account),
        resolve(root, args) {
            const parameters = [];
            return pg.query(`query`, parameters)
            .then((result) =>
            {
                console.log(result.entrys.rows);
                //return result.entrys.rows;
                return [
                    {
                    id: '33333',
                    token: '111',
                    userIdentifier: 'test'
                    }
                ]
            })
            .catch((err) =>
            {
                console.log(err);
                return err.message;
            });
            console.log('finished');
        }
    })
});
</code>```

Body:
I'm trying out graphql.  I'm pulling my data from postgresql and everyting seems to work except for one issue where the resolve completes before the query has completed.  I though I had my query promise working correctly.  Here my class that I created to query the database:

class PgPoolClient {

    constructor(options) {
        this.connection = options.connection;
    }

    query(sql, data = []) {

        return new Promise((resolve, reject) => {
            var pool = new pg.Pool(this.connection);
            pool.connect((err, client, done) => {
                if (err) {
                    reject({
                        code: 505,
                        message: err.message,
                        entrys: []
                    });
                } else {
                    client.query(sql, data, (err, results) => {
                        done();
                        if (err) {
                            reject({
                                code: 404,
                                message: err.message,
                                entrys: []
                            });
                        } else {
                            resolve({
                                code: 200,
                                message: "ok",
                                entrys: results
                            });
                        }
                    });
                }
            });

            pool.on("error", (err, client) => {
                reject({
                    code: 505,
                    message: err.message,
                    entrys: {}
                });
            });

        });
    }
}

Here is my graphql Query:

const Query = new GraphQLObjectType({
    name: 'Query',
    description: 'Root query object',
    fields: () => ({
        accounts: {
            type: new GraphQLList(Account),
            resolve(root, args) {

                const parameters = [];
                pg.query(`SELECT
id, token, user_identifier as userIdentifier, hash_password as hashPassword,
is_enabled as isEnabled, security_type_id as securityTypeID,
is_admin as isAdmin, ad_path as adPath, date_created as dateCreated,
date_modified as dateModified, modified_by as modifiedBy
FROM accounts.account`, parameters)
                .then((result) =>
                {
                    console.log(result.entrys.rows);
                    //return result.entrys.rows;
                    return [
                        {
                        id: '33333',
                        token: '111',
                        userIdentifier: 'test'
                        }
                    ]

                })
                .catch((err) =>
                {
                    console.log(err);
                    return err.message;
                });

                console.log('finished');
        }
    })
});

I commented out my results and just wanted to see about returning static content and it seems that when its within then() the results don't get returned to graphisql (meaning the resolve completed before then() does).  with output:

{
  "data": {
   "accounts": null
 }

}

I was able to verify this by putting the static return array below the console.log('finished') and it returns the data properly.

console.log('finished');
return [
    {
    id: '33333',
    token: '111',
    userIdentifier: 'test'
    }
]

which shows up in graphiql:

{
  "data": {
    "accounts": [
      {
        "id": "33333",
        "token": "111",
        "userIdentifier": "test"
      }
    ]
  }
}

So it seems that my Promise is not being waited on.  Is there something I'm missing in my query function that is causing the resolve not to wait for my results?  Any help would be appreciated.

Update 1

It seems if I wrapp the query in a Promise it works:

return new Promise((resolve, reject) => {

pg.query(`SELECT
id, token, user_identifier as userIdentifier, hash_password as hashPassword,
is_enabled as isEnabled, security_type_id as securityTypeID,
is_admin as isAdmin, ad_path as adPath, date_created as dateCreated,
date_modified as dateModified, modified_by as modifiedBy
FROM accounts.account`, parameters)
.then((result) =>
{
    console.log(result.entrys.rows);
    //return result.entrys.rows;
    resolve( [
        {
        id: '33333',
        token: '111',
        userIdentifier: 'test'
        }
    ]);

})
.catch((err) =>
{
    console.log(err);
    reject(err.message);
});

I guess my question is if my query function is already wrapped in a Promise, why do I have to do it again?

Body:
Your resolve function needs to return the promise. When you explicitly wrapped it in a promise, it worked because you returned it. It should work without that if you return the result of calling pg.query.

const Query = new GraphQLObjectType({
name: 'Query',
description: 'Root query object',
fields: () => ({
    accounts: {
        type: new GraphQLList(Account),
        resolve(root, args) {
            const parameters = [];
            return pg.query(`query`, parameters)
            .then((result) =>
            {
                console.log(result.entrys.rows);
                //return result.entrys.rows;
                return [
                    {
                    id: '33333',
                    token: '111',
                    userIdentifier: 'test'
                    }
                ]
            })
            .catch((err) =>
            {
                console.log(err);
                return err.message;
            });
            console.log('finished');
        }
    })
});


来源: stackexchange

问:
Extract the movie.json.1 (extension (.1) ) using java
```<code>    File file = new File("D:\\final\\movie.json.1");
    String resp = readFile(file);

    JSONArray array = new JSONArray(resp);
</code>```

But its giving as a the below exception  :

```<code>    Exception in thread "main" org.json.JSONException: Missing value at 1 [character 2 line 1]
</code>```

movie.json.1 :
Sample text :

[{"id":"episode_45747","resourceId":"45747","docType":"episode","uniqueName":"45747","locale":["eng"],"filter_locale":["eng"],"filter_device":

This works If the text copy from .json.1 file to .txt file.

Please help me to extract that this type of extension files.

答:
Can you try using JSON parser?</p>

```<code>JSONParser parser = new JSONParser();
JSONArray array = (JSONArray) parser.parse(new FileReader("D:\\final\\movie.json.1"));
</code>```

ContentLicense: CC BY-SA 3.0

Body:
    File file = new File("D:\\final\\movie.json.1");
    String resp = readFile(file);

    JSONArray array = new JSONArray(resp);

But its giving as a the below exception  :

    Exception in thread "main" org.json.JSONException: Missing value at 1 [character 2 line 1]

movie.json.1 :
Sample text :

[{"id":"episode_45747","resourceId":"45747","docType":"episode","uniqueName":"45747","locale":["eng"],"filter_locale":["eng"],"filter_device":

This works If the text copy from .json.1 file to .txt file.

Please help me to extract that this type of extension files.

Body:
Can you try using JSON parser?

JSONParser parser = new JSONParser();
JSONArray array = (JSONArray) parser.parse(new FileReader("D:\\final\\movie.json.1"));


问:
How to get authorized user from active directory in asp.net using c#?
I want to get authorized user from active directory for login page. When user enter wrong details the page need to show "Invalid user", if enter correct correct details lets go the home page.

Here mentioned my code. When i run this code the page shows "invalid user" even i enter the correct login details.

```<code>protected void Button1_Click1(object sender, EventArgs e)
        {

            string dominName = "ldap://domain.com:121";
            string userName = "guest";
            string password = "testlogin";

            if (true == AuthenticateUser(dominName, userName, password))
            {
                Response.Redirect("default.aspx");
            }
            else
            {
                Response.Write("Invalid user name or Password!");
            }

        }

        public bool AuthenticateUser(string domain, string username, string password)
        {
            DirectoryEntry entry = new DirectoryEntry(domain, username, password);
            try
            {
                DirectorySearcher search = new DirectorySearcher(entry);
                search.Filter = "(sAMAccountName=" + username + ")";
                search.PropertiesToLoad.Add("cn");
                Response.Write(domain);
                SearchResult result = search.FindOne();

                if (null == result)
                {
                    return false;
                }

            }
            catch (Exception ex)
            {
                return false;
                throw new Exception("Error authenticating user." + ex.Message);
            }
            return true;
        }
</code>```

Find the above code what i make a mistake. Please provide a best solution to this...

答:
Finally i got that solution from this site. a little change in the above code. now its works fine perfectly.

```<code>protected void Button1_Click1(object sender, EventArgs e)
        {

            string dominName = "ldap://domain.com";
            string userName = "guest";
            string password = "testlogin";

            if (true == AuthenticateUser(dominName, userName, password))
            {
                Response.Redirect("default.aspx");
            }
            else
            {
                Response.Write("Invalid user name or Password!");
            }

        }

private bool AuthenticateUser( string domain, string userName, string password)
{
    bool authentic = false;
    try
    {
        DirectoryEntry entry = new DirectoryEntry(domain, userName, password);
        entry.Path = "LDAP://OU=allsuers,OU=users,DC=domain,DC=com";
        DirectorySearcher searcher = new DirectorySearcher(entry)
        {
            PageSize = int.MaxValue,
            Filter = "(sAMAccountName=" + userName + ")"
        };

        var result = searcher.FindOne();

        if (result == null) {
            return true;
        }

    }
    catch (DirectoryServicesCOMException) { }
    return authentic;
}
</code>```

Thank you to all. Who are all support to do this.

Body:
I want to get authorized user from active directory for login page. When user enter wrong details the page need to show "Invalid user", if enter correct correct details lets go the home page.

Here mentioned my code. When i run this code the page shows "invalid user" even i enter the correct login details.

protected void Button1_Click1(object sender, EventArgs e)
        {

            string dominName = "ldap://domain.com:121";
            string userName = "guest";
            string password = "testlogin";

            if (true == AuthenticateUser(dominName, userName, password))
            {
                Response.Redirect("default.aspx");
            }
            else
            {
                Response.Write("Invalid user name or Password!");
            }

        }

        public bool AuthenticateUser(string domain, string username, string password)
        {
            DirectoryEntry entry = new DirectoryEntry(domain, username, password);
            try
            {
                DirectorySearcher search = new DirectorySearcher(entry);
                search.Filter = "(sAMAccountName=" + username + ")";
                search.PropertiesToLoad.Add("cn");
                Response.Write(domain);
                SearchResult result = search.FindOne();

                if (null == result)
                {
                    return false;
                }

            }
            catch (Exception ex)
            {
                return false;
                throw new Exception("Error authenticating user." + ex.Message);
            }
            return true;
        }

Find the above code what i make a mistake. Please provide a best solution to this...

Body:
Finally i got that solution from this site. a little change in the above code. now its works fine perfectly.

protected void Button1_Click1(object sender, EventArgs e)
        {

            string dominName = "ldap://domain.com";
            string userName = "guest";
            string password = "testlogin";

            if (true == AuthenticateUser(dominName, userName, password))
            {
                Response.Redirect("default.aspx");
            }
            else
            {
                Response.Write("Invalid user name or Password!");
            }

        }

private bool AuthenticateUser( string domain, string userName, string password)
{
    bool authentic = false;
    try
    {
        DirectoryEntry entry = new DirectoryEntry(domain, userName, password);
        entry.Path = "LDAP://OU=allsuers,OU=users,DC=domain,DC=com";
        DirectorySearcher searcher = new DirectorySearcher(entry)
        {
            PageSize = int.MaxValue,
            Filter = "(sAMAccountName=" + userName + ")"
        };

        var result = searcher.FindOne();

        if (result == null) {
            return true;
        }

    }
    catch (DirectoryServicesCOMException) { }
    return authentic;
}

Thank you to all. Who are all support to do this.


问:
find possible paths in map : recursive function in javascript

doc = {
  'a': {
    'b': {
      'c': 'hello'
    },
    'd': {
      'c': 'sup',
      'e': {
        'f': 'blah blah blah'
      }
    }
  }
}

function get(json, path) {
  var str = path.split('.');
  var temp = json;
  var arr = [];
  var keystr = "";
  for (var i = 0; i < str.length; i++) {
    if (str[i] != "*") {

      keystr += str[i] + ".";

      if (temp[str[i]] === undefined)
        break;
      else {
        temp = temp[str[i]];
        if (i == str.length - 1) {
          var nObj = {};
          nObjKey = keystr.substr(0, keystr.length - 1);
          nObj[nObjKey] = temp
            // console.log("Obj check" + JSON.stringify(nObj) + keystr)
          arr.push(nObj);
        }
      }
    } else {
      for (var key in temp) {
        var concat = key + "."
        for (var j = i + 1; j < str.length; j++)
          concat += str[j] + ".";
        if (temp[key] !== undefined && temp[key] instanceof Object) {

          var m = keystr + concat.substr(0, concat.length - 1);
          var obj = (get(temp, concat.substr(0, concat.length - 1)));

          if (obj != "") {
            // console.log("existing arr "+JSON.stringify(arr))
            obj[m] = (obj[0])[concat.substr(0, concat.length - 1)]
              //  console.log("hello "+JSON.stringify(obj) + " end hello")
            arr.push(obj);
          }
        } else if (temp[key] !== undefined && i == str.length - 1) {
          // arr.push(temp);
        }
      }
    }
  }
  return arr;
}

var result = (get(doc, 'a.*.e'))
console.log(result)```

For input of 'a.*.e' the output should  be {'a.d.e': {'f': 'blah blah blah'}}}. But I get all the replacement for wild card as well in the array. I am sure something is wrong but not able to detect it. Help would be appreciated.

答:
First of all, since your desired output {'a.d.e': {'f': 'blah blah blah'}}} does not contain any array, but only plain objects, you should not need the variable arr in your code.

Instead, return nObj as function result, and declare it at the start, never clearing it.

Secondly, when you come back from the recursive call, the results need to be copied while prefixing the paths with what you already had. Note that checking for an empty array should not be done with != "", but anyway, you don't need that any more.

You could write this from scratch in different ways (see solution at end of answer), but I have first adapted your code to only change the bare minimum, with comments where I made the changes to make it work:

function get(json, path) {
  var str = path.split('.');
  var temp = json;
  var arr = [];
  var keystr = "";
  // *** Define here the object to return
  var nObj = {};

  for (var i = 0; i < str.length; i++) {
    if (str[i] != "*") {
      keystr += str[i] + ".";
      if (temp[str[i]] === undefined)
        break;
      else {
        temp = temp[str[i]];
        if (i == str.length - 1) {
          // *** Move this to start of the function
          //var nObj = {};
          nObjKey = keystr.substr(0, keystr.length - 1);
          nObj[nObjKey] = temp
        }
      }
    } else {
      for (var key in temp) {
        var concat = key + "."
        for (var j = i + 1; j < str.length; j++)
          concat += str[j] + ".";
        if (temp[key] !== undefined && temp[key] instanceof Object) {

          var m = keystr + concat.substr(0, concat.length - 1);
          var obj = get(temp, concat.substr(0, concat.length - 1));
          // *** Return value is object with path(s) as keys
          // *** Don't compare array with string
          //if (arr != "") {
            // *** Iterate over the returned object properties, and prefix them
            for (var deepKey in obj) {
                nObj[keystr + deepKey] = obj[deepKey];
            }
            //*** No need for array; we already have the object properties
            //arr.push(obj);
          //}
        // *** No need for array
        //} else if (temp[key] !== undefined && i == str.length - 1) {
          // arr.push(temp);
        }
      }
    }
  }
  // *** Return object
  return nObj;
}

var doc = {
  'a': {
    'b': {
      'c': 'hello'
    },
    'd': {
      'c': 'sup',
      'e': {
        'f': 'blah blah blah'
      },
    },
    'g': {
      'e': {
        'also': 1
      }
    }
  }
}

var result = (get(doc, 'a.*.e'));
console.log(result);```
</div>
</div>
</p>

<p>Please also consider not name objects <code>json</code> when they are not: JSON is a text format, JavaScript object variables are not the same thing as JSON.</p>

<h3>Compact ES6 solution</h3>

<p>When you are used to array functions like <code>reduce</code> and a <em>functional programming</em> style, the following compact ES6 solution might appeal to you:</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>function get(obj, path) {
    if (typeof path === 'string') path = path.split('.');
    return !path.length ? { '': obj } // Match
        : obj !== Object(obj) ? {} // No match
        : (path[0] === '*' ? Object.keys(obj) : [path[0]]) // Candidates
            .reduce( (acc, key) => {
                const match = get(obj[key], path.slice(1)); // Recurse
                return Object.assign(acc, ...Object.keys(match).map( dotKey =>
                    ({ [key + (dotKey ? '.'  + dotKey : '')]: match[dotKey] })
                ));
            }, {});
}

const doc = {
  'a': {
    'b': {
      'c': 'hello'
    },
    'd': {
      'c': 'sup',
      'e': {
        'f': 'blah blah blah'
      },
    },
    'g': {
      'e': {
        'also': 1
      }
    }
  }
};

const result = get(doc, 'a.*.e');
console.log(result);</code>```

Body:
doc = {
  'a': {
    'b': {
      'c': 'hello'
    },
    'd': {
      'c': 'sup',
      'e': {
        'f': 'blah blah blah'
      }
    }
  }
}

function get(json, path) {
  var str = path.split('.');
  var temp = json;
  var arr = [];
  var keystr = "";
  for (var i = 0; i < str.length; i++) {
    if (str[i] != "*") {

      keystr += str[i] + ".";

      if (temp[str[i]] === undefined)
        break;
      else {
        temp = temp[str[i]];
        if (i == str.length - 1) {
          var nObj = {};
          nObjKey = keystr.substr(0, keystr.length - 1);
          nObj[nObjKey] = temp
            // console.log("Obj check" + JSON.stringify(nObj) + keystr)
          arr.push(nObj);
        }
      }
    } else {
      for (var key in temp) {
        var concat = key + "."
        for (var j = i + 1; j < str.length; j++)
          concat += str[j] + ".";
        if (temp[key] !== undefined && temp[key] instanceof Object) {

          var m = keystr + concat.substr(0, concat.length - 1);
          var obj = (get(temp, concat.substr(0, concat.length - 1)));

          if (obj != "") {
            // console.log("existing arr "+JSON.stringify(arr))
            obj[m] = (obj[0])[concat.substr(0, concat.length - 1)]
              //  console.log("hello "+JSON.stringify(obj) + " end hello")
            arr.push(obj);
          }
        } else if (temp[key] !== undefined && i == str.length - 1) {
          // arr.push(temp);
        }
      }
    }
  }
  return arr;
}

var result = (get(doc, 'a.*.e'))
console.log(result)

For input of 'a.*.e' the output should  be {'a.d.e': {'f': 'blah blah blah'}}}. But I get all the replacement for wild card as well in the array. I am sure something is wrong but not able to detect it. Help would be appreciated.

Body:
First of all, since your desired output {'a.d.e': {'f': 'blah blah blah'}}} does not contain any array, but only plain objects, you should not need the variable arr in your code.

Instead, return nObj as function result, and declare it at the start, never clearing it.

Secondly, when you come back from the recursive call, the results need to be copied while prefixing the paths with what you already had. Note that checking for an empty array should not be done with != "", but anyway, you don't need that any more.

You could write this from scratch in different ways (see solution at end of answer), but I have first adapted your code to only change the bare minimum, with comments where I made the changes to make it work:

function get(json, path) {
  var str = path.split('.');
  var temp = json;
  var arr = [];
  var keystr = "";
  // *** Define here the object to return
  var nObj = {};

  for (var i = 0; i < str.length; i++) {
    if (str[i] != "*") {
      keystr += str[i] + ".";
      if (temp[str[i]] === undefined)
        break;
      else {
        temp = temp[str[i]];
        if (i == str.length - 1) {
          // *** Move this to start of the function
          //var nObj = {};
          nObjKey = keystr.substr(0, keystr.length - 1);
          nObj[nObjKey] = temp
        }
      }
    } else {
      for (var key in temp) {
        var concat = key + "."
        for (var j = i + 1; j < str.length; j++)
          concat += str[j] + ".";
        if (temp[key] !== undefined && temp[key] instanceof Object) {

          var m = keystr + concat.substr(0, concat.length - 1);
          var obj = get(temp, concat.substr(0, concat.length - 1));
          // *** Return value is object with path(s) as keys
          // *** Don't compare array with string
          //if (arr != "") {
            // *** Iterate over the returned object properties, and prefix them
            for (var deepKey in obj) {
                nObj[keystr + deepKey] = obj[deepKey];
            }
            //*** No need for array; we already have the object properties
            //arr.push(obj);
          //}
        // *** No need for array
        //} else if (temp[key] !== undefined && i == str.length - 1) {
          // arr.push(temp);
        }
      }
    }
  }
  // *** Return object
  return nObj;
}

var doc = {
  'a': {
    'b': {
      'c': 'hello'
    },
    'd': {
      'c': 'sup',
      'e': {
        'f': 'blah blah blah'
      },
    },
    'g': {
      'e': {
        'also': 1
      }
    }
  }
}

var result = (get(doc, 'a.*.e'));
console.log(result);

Please also consider not name objects json when they are not: JSON is a text format, JavaScript object variables are not the same thing as JSON.

Compact ES6 solution

When you are used to array functions like reduce and a functional programming style, the following compact ES6 solution might appeal to you:

function get(obj, path) {
    if (typeof path === 'string') path = path.split('.');
    return !path.length ? { '': obj } // Match
        : obj !== Object(obj) ? {} // No match
        : (path[0] === '*' ? Object.keys(obj) : [path[0]]) // Candidates
            .reduce( (acc, key) => {
                const match = get(obj[key], path.slice(1)); // Recurse
                return Object.assign(acc, ...Object.keys(match).map( dotKey =>
                    ({ [key + (dotKey ? '.'  + dotKey : '')]: match[dotKey] })
                ));
            }, {});
}

const doc = {
  'a': {
    'b': {
      'c': 'hello'
    },
    'd': {
      'c': 'sup',
      'e': {
        'f': 'blah blah blah'
      },
    },
    'g': {
      'e': {
        'also': 1
      }
    }
  }
};

const result = get(doc, 'a.*.e');
console.log(result);


问:
Creating subplots with matplotlib
I'm currently learning the basic philosophy of making plots with matplotlib in Python with Jupyter Notebook. My main gripe is when it comes to creating subplots, why do I have to run the code in one single chunk? And whenever I try to run it in separate steps, it throws me weird plots. For exampple:

plt.subplot(211)

plt.plot(range(10))

plt.subplot(212, facecolor='y')

plt.plot(randn(50))

I have to excute those four lines of codes in one step as opposed to run them each in four steps. What's exactly going on here? Why is there such a difference between the two approaches?

答:
In a jupyter notebook, once a cell is evaluated and the figure is shown you're loosing the reference to it and the figure produced in that cell is closed.

In the new cell, when calling plt.subplot(), pyplot does not see any open figure, so it creates a new one.

Most pyplot commands work like this: Find out if there is an open figure (possibly a current axes as well). If this is the case, operate on that figure (axes), if not, create it. This is why it's often called statemachine; depending on the current state, do something.

Opposed to that there is also an object oriented API. It works by explicitely calling the methods of the objects you want to operate on. So in order to reuse the figures or axes from previous cells, we would keep a reference to them.

Explicitely call fig = plt.figure(), such that  fig is still available in the next cell. Same with axes, call ax = fig.add_subplot(111) to have the subplot available in the next cell. At any point, call fig to invoke the display of the figure.

Here is an example:

Title: Creating subplots with matplotlib


问:
Android cannot display a list view to another activity
I am going to display ordered destination information from a list of selected destinations. For example, the user can select some destinations in the list of 10 places, and based on the distance the priority I set, the second activity will display a calculated route for the user.

The priority value of each destination is stored in a cloud database, and I tested that I could successfully get the data. I will use the data to calculate the route.

There is no error in LogCAT, however, the ordered list view cannot display in the second activity. PLEASE help me, it has bothered me for more than three days.

here is my code (first activity):

```<code>public class DestinationActivity extends Activity implements OnClickListener, NumberPicker.OnValueChangeListener {

private TextView from_place, date, days, start_time, end_time, number, money_view;
private Button addButton, subButton;
private ImageView backButton, telephone;
private ListView listView;
private Button destinationOk_btn;

private Tip startTip;

private Calendar calendar;
private DatePickerDialog dialog;
private TimePickerDialog dialog2;

private List<Destination> destinationList = new ArrayList<Destination>();

private DestinationAdapter adapter;

private int number_value = 1;

private String time_start;
private String time_end;
private int travel_days;
double travelTime;//total traveling time
double travel_time;
//long car_time;
private int money;
private int num = 1;

//private SQLiteDatabase db;
//private DestinationDBHelper dbHelper;

private ArrayList<Integer> select_placeID = new ArrayList<Integer>(); //selected destinations
public Map<Integer,Double> weightMap;
public List<Plan> planList = new ArrayList<Plan>();//

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

    Bmob.initialize(this, BmobConfig.APP_ID);

    listView = (ListView) findViewById(R.id.list_destination);

    destinationOk_btn = (Button) findViewById(R.id.okButton);

    initDestinations();

    adapter = new DestinationAdapter(destinationList, DestinationActivity.this);
    //adapter = new DestinationAdapter(this, destinationList, DestinationAdapter.getIsSelected());
    listView.setAdapter(adapter);

    from_place = (TextView) findViewById(R.id.from_place);
    date = (TextView) findViewById(R.id.date);
    start_time = (TextView) findViewById(R.id.time);
    end_time = (TextView) findViewById(R.id.end_time);
    number = (TextView) findViewById(R.id.number);
    money_view = (TextView) findViewById(R.id.request_money_et);
    addButton = (Button) findViewById(btn_add);
    subButton = (Button) findViewById(btn_sub);
    backButton = (ImageView) findViewById(R.id.back);
    telephone = (ImageView) findViewById(R.id.telephone);
    days = (EditText) findViewById(R.id.days);

    //listeners
    from_place.setOnClickListener(this);
    date.setOnClickListener(this);
    start_time.setOnClickListener(this);
    number.setOnClickListener(this);
    destinationOk_btn.setOnClickListener(this);
    addButton.setOnClickListener(this);
    subButton.setOnClickListener(this);
    backButton.setOnClickListener(this);
    telephone.setOnClickListener(this);
    end_time.setOnClickListener(this);

    //submit button
    destinationOk_btn.setOnClickListener(new OnClickListener() {
        @Override
        public void onClick(View v) {

            select_placeID.clear();

            for (int i = 0; i < destinationList.size(); i++) {
                if (DestinationAdapter.getIsSelected().get(i)) {
                    select_placeID.add(i);
                }

            }

            if (select_placeID.size() == 0) {
                AlertDialog.Builder builder1 = new AlertDialog.Builder(DestinationActivity.this);
                builder1.setMessage("no records");
                builder1.show();
            } else {
                AlertDialog.Builder builder = new AlertDialog.Builder(DestinationActivity.this);

                builder.setMessage("waiting for magic...");
                builder.show();

                /**
                 * calculate the route
                 */
                if (validate()) {
                    new calRoute().execute();
                }

                Intent intent = new Intent();
                intent.setClass(DestinationActivity.this, ActivityPlan.class);

                intent.putParcelableArrayListExtra("planInfo", (ArrayList<? extends Parcelable>) planList);

                startActivity(intent);

            }
        }

    });
    }

//initialize the data
private void initDestinations() {
    Destination destination1 = new Destination("香山", R.drawable.xiangshan);
    destinationList.add(destination1);
    Destination destination2 = new Destination("天安门", R.drawable.car);
    destinationList.add(destination2);
    Destination destination3 = new Destination("后海", R.drawable.car);
    destinationList.add(destination3);
    Destination destination4 = new Destination("五道口", R.drawable.car);
    destinationList.add(destination4);
    Destination destination5 = new Destination("朝阳公园", R.drawable.car);
    destinationList.add(destination5);
    Destination destination6 = new Destination("雍和宫", R.drawable.car);
    destinationList.add(destination6);
    Destination destination7 = new Destination("八达岭长城", R.drawable.car);
    destinationList.add(destination7);
    Destination destination8 = new Destination("颐和园", R.drawable.car);
    destinationList.add(destination8);
    Destination destination9 = new Destination("三里屯", R.drawable.car);
    destinationList.add(destination9);
    Destination destination10 = new Destination("故宫", R.drawable.car);
    destinationList.add(destination10);
}

@Override
public void onClick(View v) {
    //.............
}

//number picker
@Override
public void onValueChange(NumberPicker picker, int oldVal, int newVal) {
    Log.i("value is","" + newVal);
}

/**
 * 异步处理
 */
private class calRoute extends AsyncTask<Void, Void, List<Plan>>{

    public calRoute(){
        // TODO Auto-generated constructor stub
    }

    @Override
    protected List<Plan> doInBackground(Void... params) {

        List<Plan> result = calculate(time_start, time_end, travel_days);

        return result;
    }

    //UI
    @Override
    protected void onPostExecute(List<Plan> result) {
        super.onPostExecute(result);
        if (result != null) {
            Toast.makeText(DestinationActivity.this, "success", Toast.LENGTH_SHORT).show();
        }
    }
}

/**
 *plan calculation
 **/
public List<Plan> calculate(String time_start, String time_end, int travel_days) {

    SimpleDateFormat df = new SimpleDateFormat(("HH:mm"));

    Date starttime = new Date();
    Date endtime = new Date();
    try {
        starttime = df.parse(time_start);
    } catch (ParseException e) {
        e.printStackTrace();
    }
    try {
        endtime = df.parse(time_end);
    } catch (ParseException e) {
        e.printStackTrace();
    }

    double l = endtime.getTime() - starttime.getTime();
    double hour = (l / (60 * 60 * 1000));
    double min = ((l / (60 * 1000)) - hour * 60);

    if(min == 0){
        min = 60;
    }
    else {
        travel_time = ((1.0 * travel_days * hour) * (min / 60)); //以小时为单位计算旅行时长calculate total travel time
        DecimalFormat decimalFormat = new DecimalFormat("#.0");
        travelTime = Double.parseDouble(decimalFormat.format(travel_time));//保留一位小数
    }

    //获取不同地点的priority
    weightMap = new LinkedHashMap<Integer, Double>();

    int totalPriority = 0;//总优先级total priority

   // where I am
    final Destination start = new Destination(116.355231, 39.95222);//当前位置

    final HashMap<Integer, Integer> pMap = new HashMap<Integer, Integer>();
    final HashMap<Integer, String> nameMap = new HashMap<Integer, String>();
    final HashMap<Integer, Destination> objectMap = new LinkedHashMap<Integer, Destination>();//储存每个destination的经纬度
    /**
     * 向后端云bmob根据id查询景点的priority
     */
    new Thread (new Runnable(){

        @Override
        public void run() {
            BmobQuery<Destination> query = new BmobQuery<Destination>();
            for (int id : select_placeID) {

                query.addWhereEqualTo("id", id);

                //查询数据, 子查询
                //query.addWhereContainedIn("id", select_placeID);

                //返回10条数据，如果不加上这条语句，默认返回10条数据
                //query.setLimit(10);

                //执行查询方法
                query.findObjects(new FindListener<Destination>() {
                    @Override
                    public void done(List<Destination> list, BmobException e) {
                        if (e == null) {
                            System.out.println("查询成功：共" + list.size() + "条数据。");
                            for (Destination destination : list) {
                                //获得priority的信息
                                int p = destination.getPriority();
                                //获得数据的objectId信息
                                int id = destination.getId();

                                String name = destination.getName();

                                //获取经纬度
                                double longitude = destination.getLongitude();
                                double latitute = destination.getLatitute();

                                objectMap.put(id, new Destination(longitude, latitute));

                                //计算距离
                                double dis = DistanceUtil.distance(start.getLongitude(), start.getLatitute(),
                                        longitude, latitute);

                                pMap.put(id, p);
                                weightMap.put(id, dis);
                                nameMap.put(id, name);

                            }
                        } else {
                            Log.i("bmob", "失败：" + e.getMessage() + "," + e.getErrorCode());
                        }
                    }
                });
            }
        }
    }).start();

    //遍历整个pMap
    for (int v : pMap.values()) {
        totalPriority = totalPriority + v;
    }

    //计算weight并生成最终map
    double weight = 0.0;
    for (Map.Entry<Integer, Double> hm : weightMap.entrySet()) {
        double hm2Value = pMap.get(hm.getKey());
        weight = totalPriority / hm.getValue() * hm2Value;

        weightMap.put(hm.getKey(), weight);
    }

    /**
     * 按照weight值来排序
     * 判断是否传递数据给plan_activity
     */
    MapUtil.sortByValue(weightMap);

    //排好序后计算距离
    Iterator it = weightMap.entrySet().iterator();
    int order = 0;
    while (it.hasNext()) {
        order++;
        Map.Entry entry = (Map.Entry) it.next();
        objectMap.put(order, objectMap.get(entry.getKey()));//有哪些id，并且位置已排列好
    }

    PlanTask planTask = new PlanTask();//封装了每个plan计算的方法
    //遍历map中的值,打印plan
    for (Map.Entry<Integer, Double> entry : weightMap.entrySet()) {
        System.out.println("id= " + entry.getKey());

        double play_time = planTask.calPlay_time(weightMap.size(),
                weightMap.get(entry.getKey()), travelTime);

        //到下一个目的地需要多久开车时间
        //按id找到destination，获取经纬度
        double driving_time = planTask.calDrive_time(DistanceUtil.distance(
                objectMap.get(entry.getKey()).getLatitute(),
                objectMap.get(entry.getKey()).getLongitude(),
                objectMap.get(entry.getKey() + 1).getLatitute(),
                objectMap.get(entry.getKey() + 1).getLongitude()
        ));

        String arrive_time = "hello world";//未完待续

        String place_name = nameMap.get(entry.getKey());

        Plan plan = new Plan(place_name, arrive_time, driving_time, play_time);

        //传递plan对象list
        planList.add(entry.getKey(), plan);
    }

    return planList;

}

//验证用户输入是否完整
public boolean validate(){
    //先计算旅游总时间
    time_start = start_time.getText().toString();
    time_end = end_time.getText().toString();
    try {
        travel_days = Integer.parseInt(days.getText().toString());
    } catch (NumberFormatException e) {
        Toast.makeText(DestinationActivity.this, "游玩天数不正确", Toast.LENGTH_SHORT).show();
    }

        if (StringUtils.isBlank(time_start)) {
            Toast.makeText(DestinationActivity.this, "请输入出发时间", Toast.LENGTH_SHORT).show();
            return false;
        }

        if (StringUtils.isBlank(time_end)) {
            Toast.makeText(DestinationActivity.this, "请输入结束时间", Toast.LENGTH_SHORT).show();
            return false;
        }

        if (travel_days <=0 ){
            Toast.makeText(DestinationActivity.this, "请输入游玩天数", Toast.LENGTH_SHORT).show();
            return false;
        }

    return true;

}

  }
</code>```

this is the code of the second activity:

```<code>public class ActivityPlan extends Activity {

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

    List<Plan> plans = new ArrayList<Plan>();

    Intent intent = getIntent();
    plans = intent.getParcelableArrayListExtra("planInfo");

    PlanAdapter adapter = new PlanAdapter(ActivityPlan.this,
            R.layout.item_plan, plans);

    ListView listView = (ListView) findViewById(R.id.plan_list);
    listView.setAdapter(adapter);

}

}
</code>```

and the code of the model Plan, which I will display on the second activity:

```<code>public class Plan implements Parcelable {

private String place_name;
private String arrive_time;
private double play_time;
private double driving_time;

public Plan(){

}

public Plan(String place_name, String arrive_time, double driving_time, double play_time) {
    this.place_name = place_name;
    this.arrive_time = arrive_time;
    this.driving_time = driving_time;
    this.play_time = play_time;
}

protected Plan(Parcel in) {
    place_name = in.readString();
    arrive_time = in.readString();
    play_time = in.readDouble();
    driving_time = in.readLong();
}

@Override
public int describeContents() {
    // TODO Auto-generated method stub
    return 0;
}

@Override
public void writeToParcel(Parcel dest, int flags) {

    // TODO Auto-generated method stub
    dest.writeString(place_name);
    dest.writeString(arrive_time);
    dest.writeDouble(play_time);
    dest.writeDouble(driving_time);
}

public static final Creator<Plan> CREATOR = new Creator<Plan>() {

    @Override
    public Plan createFromParcel(Parcel source) {
        Plan planInfo  = new Plan();
        planInfo.place_name = source.readString();
        planInfo.arrive_time = source.readString();
        planInfo.play_time= source.readDouble();
        planInfo.driving_time = source.readDouble();

        return planInfo;
    }

    @Override
    public Plan[] newArray(int size) {
        return new Plan[size];
    }
};

public String getPlace_name() {
    return place_name;
}
public String getArrive_time() {
    return arrive_time;
}
public double getPlay_time() {
    return play_time;
}
public double getDriving_time() {
    return driving_time;
}

public void setPlace_name(String place_name){
    this.place_name = place_name;
}

public void setArrive_time(String arrive_time){
    this.arrive_time = arrive_time;
}

public void setPlay_time(double play_time){this.play_time = play_time;}

public void setDriving_time(double driving_time){
    this.driving_time = driving_time;
}

}
</code>```

I am new in Android development and I feel so confused now,
1. why the ordered information cannot be display on the second activity,  2. when I debug, I found that the variable "travelTime" is always 0.0, and the size of planList which I will use to display the information is zero, why is it?? Please help me!! thank you so much!

答:
```<code>startActivity(new Intent(DestinationActivity.this, ActivityPlan.class).putExtra("planInfo", YOUR_ARRAYLIST));
</code>```

In ActicityPlan class

```<code>arraylist = (Arraylist<Plan>) getIntent().getExtras().getSerializable("planInfo")
</code>```

Body:
I am going to display ordered destination information from a list of selected destinations. For example, the user can select some destinations in the list of 10 places, and based on the distance the priority I set, the second activity will display a calculated route for the user.

The priority value of each destination is stored in a cloud database, and I tested that I could successfully get the data. I will use the data to calculate the route.

There is no error in LogCAT, however, the ordered list view cannot display in the second activity. PLEASE help me, it has bothered me for more than three days.

here is my code (first activity):

public class DestinationActivity extends Activity implements OnClickListener, NumberPicker.OnValueChangeListener {

private TextView from_place, date, days, start_time, end_time, number, money_view;
private Button addButton, subButton;
private ImageView backButton, telephone;
private ListView listView;
private Button destinationOk_btn;

private Tip startTip;

private Calendar calendar;
private DatePickerDialog dialog;
private TimePickerDialog dialog2;

private List<Destination> destinationList = new ArrayList<Destination>();

private DestinationAdapter adapter;

private int number_value = 1;

private String time_start;
private String time_end;
private int travel_days;
double travelTime;//total traveling time
double travel_time;
//long car_time;
private int money;
private int num = 1;

//private SQLiteDatabase db;
//private DestinationDBHelper dbHelper;

private ArrayList<Integer> select_placeID = new ArrayList<Integer>(); //selected destinations
public Map<Integer,Double> weightMap;
public List<Plan> planList = new ArrayList<Plan>();//

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

    Bmob.initialize(this, BmobConfig.APP_ID);

    listView = (ListView) findViewById(R.id.list_destination);

    destinationOk_btn = (Button) findViewById(R.id.okButton);

    initDestinations();

    adapter = new DestinationAdapter(destinationList, DestinationActivity.this);
    //adapter = new DestinationAdapter(this, destinationList, DestinationAdapter.getIsSelected());
    listView.setAdapter(adapter);

    from_place = (TextView) findViewById(R.id.from_place);
    date = (TextView) findViewById(R.id.date);
    start_time = (TextView) findViewById(R.id.time);
    end_time = (TextView) findViewById(R.id.end_time);
    number = (TextView) findViewById(R.id.number);
    money_view = (TextView) findViewById(R.id.request_money_et);
    addButton = (Button) findViewById(btn_add);
    subButton = (Button) findViewById(btn_sub);
    backButton = (ImageView) findViewById(R.id.back);
    telephone = (ImageView) findViewById(R.id.telephone);
    days = (EditText) findViewById(R.id.days);

    //listeners
    from_place.setOnClickListener(this);
    date.setOnClickListener(this);
    start_time.setOnClickListener(this);
    number.setOnClickListener(this);
    destinationOk_btn.setOnClickListener(this);
    addButton.setOnClickListener(this);
    subButton.setOnClickListener(this);
    backButton.setOnClickListener(this);
    telephone.setOnClickListener(this);
    end_time.setOnClickListener(this);

    //submit button
    destinationOk_btn.setOnClickListener(new OnClickListener() {
        @Override
        public void onClick(View v) {

            select_placeID.clear();

            for (int i = 0; i < destinationList.size(); i++) {
                if (DestinationAdapter.getIsSelected().get(i)) {
                    select_placeID.add(i);
                }

            }

            if (select_placeID.size() == 0) {
                AlertDialog.Builder builder1 = new AlertDialog.Builder(DestinationActivity.this);
                builder1.setMessage("no records");
                builder1.show();
            } else {
                AlertDialog.Builder builder = new AlertDialog.Builder(DestinationActivity.this);

                builder.setMessage("waiting for magic...");
                builder.show();

                /**
                 * calculate the route
                 */
                if (validate()) {
                    new calRoute().execute();
                }

                Intent intent = new Intent();
                intent.setClass(DestinationActivity.this, ActivityPlan.class);

                intent.putParcelableArrayListExtra("planInfo", (ArrayList<? extends Parcelable>) planList);

                startActivity(intent);

            }
        }

    });
    }

//initialize the data
private void initDestinations() {
    Destination destination1 = new Destination("香山", R.drawable.xiangshan);
    destinationList.add(destination1);
    Destination destination2 = new Destination("天安门", R.drawable.car);
    destinationList.add(destination2);
    Destination destination3 = new Destination("后海", R.drawable.car);
    destinationList.add(destination3);
    Destination destination4 = new Destination("五道口", R.drawable.car);
    destinationList.add(destination4);
    Destination destination5 = new Destination("朝阳公园", R.drawable.car);
    destinationList.add(destination5);
    Destination destination6 = new Destination("雍和宫", R.drawable.car);
    destinationList.add(destination6);
    Destination destination7 = new Destination("八达岭长城", R.drawable.car);
    destinationList.add(destination7);
    Destination destination8 = new Destination("颐和园", R.drawable.car);
    destinationList.add(destination8);
    Destination destination9 = new Destination("三里屯", R.drawable.car);
    destinationList.add(destination9);
    Destination destination10 = new Destination("故宫", R.drawable.car);
    destinationList.add(destination10);
}

@Override
public void onClick(View v) {
    //.............
}

//number picker
@Override
public void onValueChange(NumberPicker picker, int oldVal, int newVal) {
    Log.i("value is","" + newVal);
}

/**
 * 异步处理
 */
private class calRoute extends AsyncTask<Void, Void, List<Plan>>{

    public calRoute(){
        // TODO Auto-generated constructor stub
    }

    @Override
    protected List<Plan> doInBackground(Void... params) {

        List<Plan> result = calculate(time_start, time_end, travel_days);

        return result;
    }

    //UI
    @Override
    protected void onPostExecute(List<Plan> result) {
        super.onPostExecute(result);
        if (result != null) {
            Toast.makeText(DestinationActivity.this, "success", Toast.LENGTH_SHORT).show();
        }
    }
}

/**
 *plan calculation
 **/
public List<Plan> calculate(String time_start, String time_end, int travel_days) {

    SimpleDateFormat df = new SimpleDateFormat(("HH:mm"));

    Date starttime = new Date();
    Date endtime = new Date();
    try {
        starttime = df.parse(time_start);
    } catch (ParseException e) {
        e.printStackTrace();
    }
    try {
        endtime = df.parse(time_end);
    } catch (ParseException e) {
        e.printStackTrace();
    }

    double l = endtime.getTime() - starttime.getTime();
    double hour = (l / (60 * 60 * 1000));
    double min = ((l / (60 * 1000)) - hour * 60);

    if(min == 0){
        min = 60;
    }
    else {
        travel_time = ((1.0 * travel_days * hour) * (min / 60)); //以小时为单位计算旅行时长calculate total travel time
        DecimalFormat decimalFormat = new DecimalFormat("#.0");
        travelTime = Double.parseDouble(decimalFormat.format(travel_time));//保留一位小数
    }

    //获取不同地点的priority
    weightMap = new LinkedHashMap<Integer, Double>();

    int totalPriority = 0;//总优先级total priority

   // where I am
    final Destination start = new Destination(116.355231, 39.95222);//当前位置

    final HashMap<Integer, Integer> pMap = new HashMap<Integer, Integer>();
    final HashMap<Integer, String> nameMap = new HashMap<Integer, String>();
    final HashMap<Integer, Destination> objectMap = new LinkedHashMap<Integer, Destination>();//储存每个destination的经纬度
    /**
     * 向后端云bmob根据id查询景点的priority
     */
    new Thread (new Runnable(){

        @Override
        public void run() {
            BmobQuery<Destination> query = new BmobQuery<Destination>();
            for (int id : select_placeID) {

                query.addWhereEqualTo("id", id);

                //查询数据, 子查询
                //query.addWhereContainedIn("id", select_placeID);

                //返回10条数据，如果不加上这条语句，默认返回10条数据
                //query.setLimit(10);

                //执行查询方法
                query.findObjects(new FindListener<Destination>() {
                    @Override
                    public void done(List<Destination> list, BmobException e) {
                        if (e == null) {
                            System.out.println("查询成功：共" + list.size() + "条数据。");
                            for (Destination destination : list) {
                                //获得priority的信息
                                int p = destination.getPriority();
                                //获得数据的objectId信息
                                int id = destination.getId();

                                String name = destination.getName();

                                //获取经纬度
                                double longitude = destination.getLongitude();
                                double latitute = destination.getLatitute();

                                objectMap.put(id, new Destination(longitude, latitute));

                                //计算距离
                                double dis = DistanceUtil.distance(start.getLongitude(), start.getLatitute(),
                                        longitude, latitute);

                                pMap.put(id, p);
                                weightMap.put(id, dis);
                                nameMap.put(id, name);

                            }
                        } else {
                            Log.i("bmob", "失败：" + e.getMessage() + "," + e.getErrorCode());
                        }
                    }
                });
            }
        }
    }).start();

    //遍历整个pMap
    for (int v : pMap.values()) {
        totalPriority = totalPriority + v;
    }

    //计算weight并生成最终map
    double weight = 0.0;
    for (Map.Entry<Integer, Double> hm : weightMap.entrySet()) {
        double hm2Value = pMap.get(hm.getKey());
        weight = totalPriority / hm.getValue() * hm2Value;

        weightMap.put(hm.getKey(), weight);
    }

    /**
     * 按照weight值来排序
     * 判断是否传递数据给plan_activity
     */
    MapUtil.sortByValue(weightMap);

    //排好序后计算距离
    Iterator it = weightMap.entrySet().iterator();
    int order = 0;
    while (it.hasNext()) {
        order++;
        Map.Entry entry = (Map.Entry) it.next();
        objectMap.put(order, objectMap.get(entry.getKey()));//有哪些id，并且位置已排列好
    }

    PlanTask planTask = new PlanTask();//封装了每个plan计算的方法
    //遍历map中的值,打印plan
    for (Map.Entry<Integer, Double> entry : weightMap.entrySet()) {
        System.out.println("id= " + entry.getKey());

        double play_time = planTask.calPlay_time(weightMap.size(),
                weightMap.get(entry.getKey()), travelTime);

        //到下一个目的地需要多久开车时间
        //按id找到destination，获取经纬度
        double driving_time = planTask.calDrive_time(DistanceUtil.distance(
                objectMap.get(entry.getKey()).getLatitute(),
                objectMap.get(entry.getKey()).getLongitude(),
                objectMap.get(entry.getKey() + 1).getLatitute(),
                objectMap.get(entry.getKey() + 1).getLongitude()
        ));

        String arrive_time = "hello world";//未完待续

        String place_name = nameMap.get(entry.getKey());

        Plan plan = new Plan(place_name, arrive_time, driving_time, play_time);

        //传递plan对象list
        planList.add(entry.getKey(), plan);
    }

    return planList;

}

//验证用户输入是否完整
public boolean validate(){
    //先计算旅游总时间
    time_start = start_time.getText().toString();
    time_end = end_time.getText().toString();
    try {
        travel_days = Integer.parseInt(days.getText().toString());
    } catch (NumberFormatException e) {
        Toast.makeText(DestinationActivity.this, "游玩天数不正确", Toast.LENGTH_SHORT).show();
    }

        if (StringUtils.isBlank(time_start)) {
            Toast.makeText(DestinationActivity.this, "请输入出发时间", Toast.LENGTH_SHORT).show();
            return false;
        }

        if (StringUtils.isBlank(time_end)) {
            Toast.makeText(DestinationActivity.this, "请输入结束时间", Toast.LENGTH_SHORT).show();
            return false;
        }

        if (travel_days <=0 ){
            Toast.makeText(DestinationActivity.this, "请输入游玩天数", Toast.LENGTH_SHORT).show();
            return false;
        }

    return true;

}

  }

this is the code of the second activity:

public class ActivityPlan extends Activity {

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

    List<Plan> plans = new ArrayList<Plan>();

    Intent intent = getIntent();
    plans = intent.getParcelableArrayListExtra("planInfo");

    PlanAdapter adapter = new PlanAdapter(ActivityPlan.this,
            R.layout.item_plan, plans);

    ListView listView = (ListView) findViewById(R.id.plan_list);
    listView.setAdapter(adapter);

}

}

and the code of the model Plan, which I will display on the second activity:

public class Plan implements Parcelable {

private String place_name;
private String arrive_time;
private double play_time;
private double driving_time;

public Plan(){

}

public Plan(String place_name, String arrive_time, double driving_time, double play_time) {
    this.place_name = place_name;
    this.arrive_time = arrive_time;
    this.driving_time = driving_time;
    this.play_time = play_time;
}

protected Plan(Parcel in) {
    place_name = in.readString();
    arrive_time = in.readString();
    play_time = in.readDouble();
    driving_time = in.readLong();
}

@Override
public int describeContents() {
    // TODO Auto-generated method stub
    return 0;
}

@Override
public void writeToParcel(Parcel dest, int flags) {

    // TODO Auto-generated method stub
    dest.writeString(place_name);
    dest.writeString(arrive_time);
    dest.writeDouble(play_time);
    dest.writeDouble(driving_time);
}

public static final Creator<Plan> CREATOR = new Creator<Plan>() {

    @Override
    public Plan createFromParcel(Parcel source) {
        Plan planInfo  = new Plan();
        planInfo.place_name = source.readString();
        planInfo.arrive_time = source.readString();
        planInfo.play_time= source.readDouble();
        planInfo.driving_time = source.readDouble();

        return planInfo;
    }

    @Override
    public Plan[] newArray(int size) {
        return new Plan[size];
    }
};

public String getPlace_name() {
    return place_name;
}
public String getArrive_time() {
    return arrive_time;
}
public double getPlay_time() {
    return play_time;
}
public double getDriving_time() {
    return driving_time;
}

public void setPlace_name(String place_name){
    this.place_name = place_name;
}

public void setArrive_time(String arrive_time){
    this.arrive_time = arrive_time;
}

public void setPlay_time(double play_time){this.play_time = play_time;}

public void setDriving_time(double driving_time){
    this.driving_time = driving_time;
}

}

I am new in Android development and I feel so confused now,
1. why the ordered information cannot be display on the second activity,  2. when I debug, I found that the variable "travelTime" is always 0.0, and the size of planList which I will use to display the information is zero, why is it?? Please help me!! thank you so much!

Body:
startActivity(new Intent(DestinationActivity.this, ActivityPlan.class).putExtra("planInfo", YOUR_ARRAYLIST));

In ActicityPlan class

arraylist = (Arraylist<Plan>) getIntent().getExtras().getSerializable("planInfo")


问:
Getting the first class from multiple classes with the same name with BeautifulSoup
I am trying to extract information from this page which has it's HTML as below.

I am trying to extract the text in the first class="currentServers" (example: I get 745,807 from this line 745,807

The problem is that in the row there are two spans with class name class="currentServers". I want to get the value in the first column of the row.

HTML:

```<code><tr class="player_count_row" style="">
                            <td align="right">
                                <span class="currentServers">745,807</span>
                            </td>
                            <td align="right">
                                <span class="currentServers">836,540</span>
                            </td>
                            <td width="20"> </td>
                            <td>
                                <a class="gameLink" onmouseover="GameHover( this, event, 'global_hover', {"type":"app","id":570,"v6":1} );" onmouseout="HideGameHover( this, event, 'global_hover' )" href="http://store.steampowered.com/app/570/">Dota 2</a>
                            </td>
                        </tr>
</code>```

I feel that I am close but I can't figure it out.

This is what I tried:

```<code>def GetTopGamesByPlayers():
    response = requests.get(url)
    html = response.content

    soup = BeautifulSoup(html)

    r = []

    final_link = soup.p.a
    final_link.decompose()

    links = soup.findAll("a", { "class" : "gameLink" })
    currentPlayers = soup.findAll("span", {"class" : "currentServers"})

    players = ""
    i = 0

    for player in currentPlayers :
        for link in links:
            players = currentPlayers[0].text
            try:
                appid = link.get('onmouseover')
                appid = findAppIdFromStats(appid,'"id":' , ',"public":1')
                linkg = link.get('href')
            except AttributeError:
                r.append(["N/A","N/A","N/A"])
            r.append([appid,linkg,players])

    c = ["N/A","N/A", "N/A"]
    while c in r:
        r.remove(c)
    return r

def findAppIdFromStats( s, first, last ):
      try:
        start = s.index( first ) + len( first )
        end = s.index( last, start )
        return s[start:end]
      except ValueError:
            return "first: " + first + "last: " + last
</code>```

The below is the output :

```<code>[u'346110', u'http://store.steampowered.com/app/346110/', u'745,807']
[u'230410', u'http://store.steampowered.com/app/230410/', u'745,807']
[u'252950', u'http://store.steampowered.com/app/252950/', u'745,807']
[u'482730', u'http://store.steampowered.com/app/482730/', u'745,807']
[u'252490', u'http://store.steampowered.com/app/252490/', u'745,807']
[u'4000', u'http://store.steampowered.com/app/4000/', u'745,807']
[u'444090', u'http://store.steampowered.com/app/444090/', u'745,807']
[u'359550', u'http://store.steampowered.com/app/359550/', u'745,807']
[u'588430', u'http://store.steampowered.com/app/588430/', u'745,807']
[u'374320', u'http://store.steampowered.com/app/374320/', u'745,807']
[u'8930', u'http://store.steampowered.com/app/8930/', u'745,807']
[u'107410', u'http://store.steampowered.com/app/107410/', u'745,807']
[u'238960', u'http://store.steampowered.com/app/238960/', u'745,807']
[u'304930', u'http://store.steampowered.com/app/304930/', u'745,807']
[u'10', u'http://store.steampowered.com/app/10/', u'745,807']
[u'72850', u'http://store.steampowered.com/app/72850/', u'745,807']
[u'289070', u'http://store.steampowered.com/app/289070/', u'745,807']
[u'105600', u'http://store.steampowered.com/app/105600/', u'745,807']
[u'377160', u'http://store.steampowered.com/app/377160/', u'745,807']
[u'236390', u'http://store.steampowered.com/app/236390/', u'745,807']
[u'292030', u'http://store.steampowered.com/app/292030/', u'745,807']
[u'227300', u'http://store.steampowered.com/app/227300/', u'745,807']
[u'386360', u'http://store.steampowered.com/app/386360/', u'745,807']
[u'236850', u'http://store.steampowered.com/app/236850/', u'745,807']
[u'364360', u'http://store.steampowered.com/app/364360/', u'745,807']
[u'381210', u'http://store.steampowered.com/app/381210/', u'745,807']
[u'363970', u'http://store.steampowered.com/app/363970/', u'745,807']
[u'453480', u'http://store.steampowered.com/app/453480/', u'745,807'

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

I want to extract the value that has the red ellipse around it:

(appid, Current Players, Game Name) - I can succesfully get the appid and game name for each game but not the Current Players in sequence

答:
I managed to fix it by amending the code as below:</p>

```<code>links = soup.findAll("a", { "class" : "gameLink" })
    currentPlayers = soup.findAll("span", {"class" : "currentServers"})

    players = ""

    rows = soup.findAll("tr", { "class" : "player_count_row" })

    for row in rows:
        players = row.findAll("span", { "class" : "currentServers" })[0].text
        for link in links:
                try:
                    appid = link.get('onmouseover')
                    appid = findAppIdFromStats(appid,'"id":' , ',"public":1')
                    linkg = link.get('href')
                except AttributeError:
                    r.append(["N/A","N/A","N/A"])
        r.append([appid,linkg,players])
</code>```

Body:
I am trying to extract information from this page which has it's HTML as below.

I am trying to extract the text in the first class="currentServers" (example: I get 745,807 from this line 745,807

The problem is that in the row there are two spans with class name class="currentServers". I want to get the value in the first column of the row.

HTML:

                                745,807

                                836,540

                                Dota 2

I feel that I am close but I can't figure it out.

This is what I tried:

def GetTopGamesByPlayers():
    response = requests.get(url)
    html = response.content

    soup = BeautifulSoup(html)

    r = []

    final_link = soup.p.a
    final_link.decompose()

    links = soup.findAll("a", { "class" : "gameLink" })
    currentPlayers = soup.findAll("span", {"class" : "currentServers"})

    players = ""
    i = 0

    for player in currentPlayers :
        for link in links:
            players = currentPlayers[0].text
            try:
                appid = link.get('onmouseover')
                appid = findAppIdFromStats(appid,'"id":' , ',"public":1')
                linkg = link.get('href')
            except AttributeError:
                r.append(["N/A","N/A","N/A"])
            r.append([appid,linkg,players])

    c = ["N/A","N/A", "N/A"]
    while c in r:
        r.remove(c)
    return r

def findAppIdFromStats( s, first, last ):
      try:
        start = s.index( first ) + len( first )
        end = s.index( last, start )
        return s[start:end]
      except ValueError:
            return "first: " + first + "last: " + last

The below is the output :

[u'346110', u'http://store.steampowered.com/app/346110/', u'745,807']
[u'230410', u'http://store.steampowered.com/app/230410/', u'745,807']
[u'252950', u'http://store.steampowered.com/app/252950/', u'745,807']
[u'482730', u'http://store.steampowered.com/app/482730/', u'745,807']
[u'252490', u'http://store.steampowered.com/app/252490/', u'745,807']
[u'4000', u'http://store.steampowered.com/app/4000/', u'745,807']
[u'444090', u'http://store.steampowered.com/app/444090/', u'745,807']
[u'359550', u'http://store.steampowered.com/app/359550/', u'745,807']
[u'588430', u'http://store.steampowered.com/app/588430/', u'745,807']
[u'374320', u'http://store.steampowered.com/app/374320/', u'745,807']
[u'8930', u'http://store.steampowered.com/app/8930/', u'745,807']
[u'107410', u'http://store.steampowered.com/app/107410/', u'745,807']
[u'238960', u'http://store.steampowered.com/app/238960/', u'745,807']
[u'304930', u'http://store.steampowered.com/app/304930/', u'745,807']
[u'10', u'http://store.steampowered.com/app/10/', u'745,807']
[u'72850', u'http://store.steampowered.com/app/72850/', u'745,807']
[u'289070', u'http://store.steampowered.com/app/289070/', u'745,807']
[u'105600', u'http://store.steampowered.com/app/105600/', u'745,807']
[u'377160', u'http://store.steampowered.com/app/377160/', u'745,807']
[u'236390', u'http://store.steampowered.com/app/236390/', u'745,807']
[u'292030', u'http://store.steampowered.com/app/292030/', u'745,807']
[u'227300', u'http://store.steampowered.com/app/227300/', u'745,807']
[u'386360', u'http://store.steampowered.com/app/386360/', u'745,807']
[u'236850', u'http://store.steampowered.com/app/236850/', u'745,807']
[u'364360', u'http://store.steampowered.com/app/364360/', u'745,807']
[u'381210', u'http://store.steampowered.com/app/381210/', u'745,807']
[u'363970', u'http://store.steampowered.com/app/363970/', u'745,807']
[u'453480', u'http://store.steampowered.com/app/453480/', u'745,807'

... ... ...

I want to extract the value that has the red ellipse around it:

(appid, Current Players, Game Name) - I can succesfully get the appid and game name for each game but not the Current Players in sequence

Body:
I managed to fix it by amending the code as below:

links = soup.findAll("a", { "class" : "gameLink" })
    currentPlayers = soup.findAll("span", {"class" : "currentServers"})

    players = ""

    rows = soup.findAll("tr", { "class" : "player_count_row" })

    for row in rows:
        players = row.findAll("span", { "class" : "currentServers" })[0].text
        for link in links:
                try:
                    appid = link.get('onmouseover')
                    appid = findAppIdFromStats(appid,'"id":' , ',"public":1')
                    linkg = link.get('href')
                except AttributeError:
                    r.append(["N/A","N/A","N/A"])
        r.append([appid,linkg,players])


问:
how to solve Array to string conversion when try to save data to database
i create a code like this

```<code>$peringkat=0;
$ranking = array("$ATTT[0]" => "$HA[0]", "$ATTT[1]" => "$HA[1]");
arsort($ranking);
foreach ($ranking as $alternatif => $nilaialternatif) {
$peringkat++;
echo "
<th class='akhir'><input class='rankingakhir' type='text' name='alternatif[]' value='$alternatif' size='12' readonly></th>
<td class='akhir'><input class='nilaiakhir' type='text' name='nilaialternatif[]' value=".number_format($nilaialternatif, 3, '.', ',')." size='12' readonly></td>
<td class='akhir'><input class='rankakhir' type='text' name='rankingalternatif[]' value='$peringkat' size='12' readonly></td></tr>";

}
echo '<div class="akhir"><input class="akhir" type="submit" value="Simpan Ranking ke Database"></div></table></div></div>
</code>```

my database code like this

```<code><?php  //Sript PHP
$Host = "localhost";
$User = "root";             //Memilih user/pengguna
$Password = "";             //Password, Biasanya Kosong
$db       = "spkjazuly";         //Memilih Database
$konek=mysql_connect($Host,$User,$Password)or die (mysql_error());
mysql_select_db ($db,$konek) or die (mysql_error("TIdak Terhubung Ke Server Mysql")); //Menghubungkan ke Mysql dan memilih Database
mysql_query("insert INTO ranking (idr,alternatif,nilai,ranking) VALUE(DEFAULT,'$_GET[alternatif]','$_GET[nilaialternatif]','$_GET[rankingalternatif]')") //Perintah Mysql untuk mengisi tabel Tamu
or die(mysql_error("Tidak Berhasil Menyimpan !"));  //Or Die (mysql_error()) Pesan Error
echo "<h1>Berhasil Menyimpan Data</h1>";
?>
</code>```

i try run var_dump and the result is like this

```<code>array(3) { ["alternatif"]=> array(2) { [0]=> string(12) "Alternatif 1" [1]=> string(12) "Alternatif 2" } ["nilaialternatif"]=> array(2) { [0]=> string(5) "0.628" [1]=> string(5) "0.372" } ["rankingalternatif"]=> array(2) { [0]=> string(1) "1" [1]=> string(1) "2" } }
</code>```

error displaying

table live desain

database table

答:
There are two ways to answer your question:

(1) Convert an array to a string representation using serialize()

In your example, this would be something like:

```<code>mysql_query("insert INTO ranking (idr,alternatif,nilai,ranking) ".
"VALUE(DEFAULT,'". serialize($_GET['alternatif']) ."','". serialize($_GET['nilaialternatif']) ."','". serialize($_GET['rankingalternatif']) ."')")
</code>```

Of course, when selecting these values from the table, you must use deserialize() to convert them back into the original array structure.

Note that serialize() and deserialize() are PHP specific function while it is bad practice to have database values depend on a specific implementation language. In order to avoid that, you may prefer to use json_encode() and json_decode().

However, now that I have explained how to technically convert arrays into string in order to store them in a database, please consider my second answer:

(2) Don't do this

You may better think over your database design. Even without knowing exactly what you plan to do, I dare to say, that storing arrays as a single database value is a strong indication of bad database design. While this does not actually answer your question, I would recommend to store each array element in a separate table row. Depending on your needs, you may have to add an additional row id or group id column to your table. Then iterate over the array to store the data. For example:

```<code>for ($i = 0; $i < count($_GET[alternatif]; $i++) {
  mysql_query("insert INTO ranking (idr,alternatif,nilai,ranking) ".
  "VALUE(DEFAULT,'". $_GET['alternatif'][$i] ."','". $_GET['nilaialternatif'][$i] ."','". $_GET['rankingalternatif'][$i] ."')")
}
</code>```

In addition to that, I recommend you take a look at the alternatives to the mysql_* functions at http://php.net/manual/de/mysqlinfo.api.choosing.php, as those are deprecated and will be removed in PHP 7.

Body:
i create a code like this

$peringkat=0;
$ranking = array("$ATTT[0]" => "$HA[0]", "$ATTT[1]" => "$HA[1]");
arsort($ranking);
foreach ($ranking as $alternatif => $nilaialternatif) {
$peringkat++;
echo "
<input class='rankingakhir' type='text' name='alternatif[]' value='$alternatif' size='12' readonly>
<input class='nilaiakhir' type='text' name='nilaialternatif[]' value=".number_format($nilaialternatif, 3, '.', ',')." size='12' readonly>
<input class='rankakhir' type='text' name='rankingalternatif[]' value='$peringkat' size='12' readonly>
";

}
echo '
<input class="akhir" type="submit" value="Simpan Ranking ke Database">

my database code like this

<?php  //Sript PHP
$Host = "localhost";
$User = "root";             //Memilih user/pengguna
$Password = "";             //Password, Biasanya Kosong
$db       = "spkjazuly";         //Memilih Database
$konek=mysql_connect($Host,$User,$Password)or die (mysql_error());
mysql_select_db ($db,$konek) or die (mysql_error("TIdak Terhubung Ke Server Mysql")); //Menghubungkan ke Mysql dan memilih Database
mysql_query("insert INTO ranking (idr,alternatif,nilai,ranking) VALUE(DEFAULT,'$_GET[alternatif]','$_GET[nilaialternatif]','$_GET[rankingalternatif]')") //Perintah Mysql untuk mengisi tabel Tamu
or die(mysql_error("Tidak Berhasil Menyimpan !"));  //Or Die (mysql_error()) Pesan Error
echo "
Berhasil Menyimpan Data
";
?>

i try run var_dump and the result is like this

array(3) { ["alternatif"]=> array(2) { [0]=> string(12) "Alternatif 1" [1]=> string(12) "Alternatif 2" } ["nilaialternatif"]=> array(2) { [0]=> string(5) "0.628" [1]=> string(5) "0.372" } ["rankingalternatif"]=> array(2) { [0]=> string(1) "1" [1]=> string(1) "2" } }

error displaying

table live desain

database table

Body:
There are two ways to answer your question:

(1) Convert an array to a string representation using serialize()

In your example, this would be something like:

mysql_query("insert INTO ranking (idr,alternatif,nilai,ranking) ".
"VALUE(DEFAULT,'". serialize($_GET['alternatif']) ."','". serialize($_GET['nilaialternatif']) ."','". serialize($_GET['rankingalternatif']) ."')")

Of course, when selecting these values from the table, you must use deserialize() to convert them back into the original array structure.

Note that serialize() and deserialize() are PHP specific function while it is bad practice to have database values depend on a specific implementation language. In order to avoid that, you may prefer to use json_encode() and json_decode().

However, now that I have explained how to technically convert arrays into string in order to store them in a database, please consider my second answer:

(2) Don't do this

You may better think over your database design. Even without knowing exactly what you plan to do, I dare to say, that storing arrays as a single database value is a strong indication of bad database design. While this does not actually answer your question, I would recommend to store each array element in a separate table row. Depending on your needs, you may have to add an additional row id or group id column to your table. Then iterate over the array to store the data. For example:

for ($i = 0; $i < count($_GET[alternatif]; $i++) {
  mysql_query("insert INTO ranking (idr,alternatif,nilai,ranking) ".
  "VALUE(DEFAULT,'". $_GET['alternatif'][$i] ."','". $_GET['nilaialternatif'][$i] ."','". $_GET['rankingalternatif'][$i] ."')")
}

In addition to that, I recommend you take a look at the alternatives to the mysql_* functions at http://php.net/manual/de/mysqlinfo.api.choosing.php, as those are deprecated and will be removed in PHP 7.


问:
Auth0 Credentials object's Expire date property is always nil
I am using Auth0 SDK version 1.1.0. I am using openid name email offline_access scopes. I am successfully getting credential object in the success response. But credential's expiresIn object always nil.

```<code>var parameters = [String: String]()
parameters["deviceToken"] = "This is a device token from iOS simulator"
parameters["device"]      = UIDevice.current.identifierForVendor?.description ?? UIDevice.current.name

Auth0.authentication().login(usernameOrEmail: usernameField.text!, password: passwordField.text!,
                             multifactorCode: nil, connection: "Username-Password-Authentication",
                             scope: "openid name email offline_access",
                             parameters: parameters).start({ (result) in
                                switch result {
                                case .success(let credentials):
                                    WSDataManger.sharedInstance.saveCredentials(credentials: credentials)
                                    print("credentail expire date is \(credentials.expiresIn)")

                                case .failure(let error):
                                    print("Failed to login: \(error.localizedDescription)")

                             })
}
</code>```

How to get the expiresIn date?

答:
Method 1:
You can decode the idToken and you will get the exp and iatvalue. expires_in can be calculated by the difference between the exp and iat claims of the JWT.

```<code>/// Decode the JWT token
func decodeJwtToken() -> String? {

    let tokenInfoArray = self.components(separatedBy: ".")
    if tokenInfoArray.count >= 2 {
        // First object array contain {"typ":"JWT","alg":"HS256"}
        //Second Object is required information
        let encodedBase64String = tokenInfoArray[1].base64String;
        guard let data = Data(base64Encoded: encodedBase64String, options: Data.Base64DecodingOptions(rawValue: 0)) else {
            return nil
        }

        guard let decodedString = String(data: data, encoding: .utf8) else { return nil }
        //remove null terminator Occurrences.
        let nullTerminatedString = decodedString.replacingOccurrences(of: "\0", with: "")
        //remove whitespace Occurrences.
        let formattedString = nullTerminatedString.replacingOccurrences(of: " ", with: "")
        return formattedString
    }
    return nil
}
</code>```

Method 2: You can use the Auth0 delegation API to get expires_in and store it in defaults or Auth0 Keychain.

```<code>  //  Renewing the expired token
func renewToken() {
    let payload = [
        "refresh_token" : defaults.value(forKey: "refresh_token"),
       "id_token" : defaults.value(forKey: "id_token"),
       "scope": "openid name email offline_access" ]
    Auth0.authentication().delegation(withParameters: payload).start { (result) in
        print(result)
        switch result {
        case .success(let credentials):
            if let value = credentials["id_token"] {
                defaults.setValue(value, forKey: "id_token")
            }
            if let value = credentials["expires_in"] as? Double {
                print("expires_in timestamp \(value)")
                //Calculate timestamp to date format.
            }
            defaults.synchronize()
        case .failure(let error):
              //Handle Error
              print(error)
        }
    }
}
</code>```

Body:
I am using Auth0 SDK version 1.1.0. I am using openid name email offline_access scopes. I am successfully getting credential object in the success response. But credential's expiresIn object always nil.

var parameters = [String: String]()
parameters["deviceToken"] = "This is a device token from iOS simulator"
parameters["device"]      = UIDevice.current.identifierForVendor?.description ?? UIDevice.current.name

Auth0.authentication().login(usernameOrEmail: usernameField.text!, password: passwordField.text!,
                             multifactorCode: nil, connection: "Username-Password-Authentication",
                             scope: "openid name email offline_access",
                             parameters: parameters).start({ (result) in
                                switch result {
                                case .success(let credentials):
                                    WSDataManger.sharedInstance.saveCredentials(credentials: credentials)
                                    print("credentail expire date is \(credentials.expiresIn)")

                                case .failure(let error):
                                    print("Failed to login: \(error.localizedDescription)")

                             })
}

How to get the expiresIn date?

Body:
Method 1:
You can decode the idToken and you will get the exp and iatvalue. expires_in can be calculated by the difference between the exp and iat claims of the JWT.

/// Decode the JWT token
func decodeJwtToken() -> String? {

    let tokenInfoArray = self.components(separatedBy: ".")
    if tokenInfoArray.count >= 2 {
        // First object array contain {"typ":"JWT","alg":"HS256"}
        //Second Object is required information
        let encodedBase64String = tokenInfoArray[1].base64String;
        guard let data = Data(base64Encoded: encodedBase64String, options: Data.Base64DecodingOptions(rawValue: 0)) else {
            return nil
        }

        guard let decodedString = String(data: data, encoding: .utf8) else { return nil }
        //remove null terminator Occurrences.
        let nullTerminatedString = decodedString.replacingOccurrences(of: "\0", with: "")
        //remove whitespace Occurrences.
        let formattedString = nullTerminatedString.replacingOccurrences(of: " ", with: "")
        return formattedString
    }
    return nil
}

Method 2: You can use the Auth0 delegation API to get expires_in and store it in defaults or Auth0 Keychain.

  //  Renewing the expired token
func renewToken() {
    let payload = [
        "refresh_token" : defaults.value(forKey: "refresh_token"),
       "id_token" : defaults.value(forKey: "id_token"),
       "scope": "openid name email offline_access" ]
    Auth0.authentication().delegation(withParameters: payload).start { (result) in
        print(result)
        switch result {
        case .success(let credentials):
            if let value = credentials["id_token"] {
                defaults.setValue(value, forKey: "id_token")
            }
            if let value = credentials["expires_in"] as? Double {
                print("expires_in timestamp \(value)")
                //Calculate timestamp to date format.
            }
            defaults.synchronize()
        case .failure(let error):
              //Handle Error
              print(error)
        }
    }
}


问:
Monit restart program script
I am fairly new to monit and I was wondering if this script is enough to restart a crashed program lets say program1 is the name of the program.

```<code>check process program1
matching "program1"
start program = "/home/user/files/start.sh"
stop program = "/home/user/files/stop.sh"
</code>```

Will it restart a crashed program now? And how can I assure it does not restart the program when it is working?

Edit:
some more info
The program uses port 30000 udp. Will this make it more cautious? And how many seconds are between the "cycles"?

```<code>if failed port 30000 type UDP for 3 cycles then restart
</code>```

答:
I will start a simple node server, which if you kill, monit is gonna restart it again and you will get an email too if set up correctly.

location /home/xxx/monitoring/nodejs

File: node-server.js

```<code>var http = require('http');
var port = 8002;
var fs = require('fs');
var logStream = fs.createWriteStream(port+"_log.txt", {'flags':'a'});
var count = 0;
http.createServer(function(req, res){
    var output = (++count) + ' Request received in '+port+' @ ' + new Date()+'\n';
    console.log(output);
    logStream.write(output);
    res.writeHead(200, {'Content-Type' : 'text/plain'});
    res.end('From '+port+' @ ' + new Date());
}).listen(port);
console.log('Server running @ ' + port)
</code>```

FILE: server.sh

```<code>#!/bin/bash

process=$1
PID_FILE="/home/xxx/monitoring/nodejs/file.pid"
case $process in
    start)
        echo "STARTING node js server in port 8002"
        nohup /usr/sbin/node /home/xxx/monitoring/nodejs/node-server.js > /home/xxx/monitoring/nodejs/server.log 2>&1 &
        echo $! > $PID_FILE
        ;;

    stop)
        kill -9 $(cat $PID_FILE)
        rm $PID_FILE
        ;;

    *)
        echo "INVALID OPTION"
        ;;
esac
</code>```

LOCATION: /etc/monit/monitrc (for ubuntu)

```<code>set mail-format {
   from: monit@TEST
   subject: monit alert -- XXX-PROD $EVENT $SERVICE
   message: $EVENT Service $SERVICE
                 Date:        $DATE
                 Action:      $ACTION
                 Host:        $HOST
                 Description: $DESCRIPTION

Your faithful employee,

 }
set mailserver smtp.gmail.com port 587 username "services.xxx@gmail.com" password "xxx" using tlsv1
set alert xxx@gmail.com

check process nodejs-server with pidfile  /home/xxx/monitoring/nodejs/file.pid
        start program = "/home/xxx/monitoring/nodejs/server.sh start"
        stop program = "/home/xxx/monitoring/nodejs/server.sh stop
</code>```

"

Once the server runs, hit the browser http://localhost:8002/. It will display some result. Now kill the process by finding its process id either from 'monit status' or from any other means. You will get a mail saying the process does not exists but again after some time, the server will run and you will get a mail saying 'process started again'.

But please remember, if you stop the process from monit command like

```<code>monit stop nodejs-server
</code>```

then it will not get restarted. And you get a mail saying that ur process has been stopped.

Title: Monit restart program script

Body:
I am fairly new to monit and I was wondering if this script is enough to restart a crashed program lets say program1 is the name of the program.

check process program1
matching "program1"
start program = "/home/user/files/start.sh"
stop program = "/home/user/files/stop.sh"

Will it restart a crashed program now? And how can I assure it does not restart the program when it is working?

Edit:
some more info
The program uses port 30000 udp. Will this make it more cautious? And how many seconds are between the "cycles"?

if failed port 30000 type UDP for 3 cycles then restart

Body:
I will start a simple node server, which if you kill, monit is gonna restart it again and you will get an email too if set up correctly.

location /home/xxx/monitoring/nodejs

File: node-server.js

var http = require('http');
var port = 8002;
var fs = require('fs');
var logStream = fs.createWriteStream(port+"_log.txt", {'flags':'a'});
var count = 0;
http.createServer(function(req, res){
    var output = (++count) + ' Request received in '+port+' @ ' + new Date()+'\n';
    console.log(output);
    logStream.write(output);
    res.writeHead(200, {'Content-Type' : 'text/plain'});
    res.end('From '+port+' @ ' + new Date());
}).listen(port);
console.log('Server running @ ' + port)

FILE: server.sh

#!/bin/bash

process=$1
PID_FILE="/home/xxx/monitoring/nodejs/file.pid"
case $process in
    start)
        echo "STARTING node js server in port 8002"
        nohup /usr/sbin/node /home/xxx/monitoring/nodejs/node-server.js > /home/xxx/monitoring/nodejs/server.log 2>&1 &
        echo $! > $PID_FILE
        ;;

    stop)
        kill -9 $(cat $PID_FILE)
        rm $PID_FILE
        ;;

    *)
        echo "INVALID OPTION"
        ;;
esac

LOCATION: /etc/monit/monitrc (for ubuntu)

set mail-format {
   from: monit@TEST
   subject: monit alert -- XXX-PROD $EVENT $SERVICE
   message: $EVENT Service $SERVICE
                 Date:        $DATE
                 Action:      $ACTION
                 Host:        $HOST
                 Description: $DESCRIPTION

Your faithful employee,

 }
set mailserver smtp.gmail.com port 587 username "services.xxx@gmail.com" password "xxx" using tlsv1
set alert xxx@gmail.com

check process nodejs-server with pidfile  /home/xxx/monitoring/nodejs/file.pid
        start program = "/home/xxx/monitoring/nodejs/server.sh start"
        stop program = "/home/xxx/monitoring/nodejs/server.sh stop

"

Once the server runs, hit the browser http://localhost:8002/. It will display some result. Now kill the process by finding its process id either from 'monit status' or from any other means. You will get a mail saying the process does not exists but again after some time, the server will run and you will get a mail saying 'process started again'.

But please remember, if you stop the process from monit command like

monit stop nodejs-server

then it will not get restarted. And you get a mail saying that ur process has been stopped.


问:
How to get CUDA to work with python 3.5 and numba
By running the code:

```<code>import numba

numba.cuda.api.detect()
</code>```

I get the error:

```<code>Traceback (most recent call last):
  File "<pyshell#1>", line 1, in <module>
    numba.cuda.api.detect()
  File "C:\Users\Wakasuki\AppData\Local\Programs\Python\Python35-32\lib\site-packages\numba\cuda\api.py", line 257, in detect
    print('Found %d CUDA devices' % len(devlist))
  File "C:\Users\Wakasuki\AppData\Local\Programs\Python\Python35-32\lib\site-packages\numba\cuda\cudadrv\devices.py", line 49, in __len__
    return len(self.lst)
  File "C:\Users\Wakasuki\AppData\Local\Programs\Python\Python35-32\lib\site-packages\numba\cuda\cudadrv\devices.py", line 26, in __getattr__
    numdev = driver.get_device_count()
  File "C:\Users\Wakasuki\AppData\Local\Programs\Python\Python35-32\lib\site-packages\numba\cuda\cudadrv\driver.py", line 269, in get_device_count
    self.cuDeviceGetCount(byref(count))
  File "C:\Users\Wakasuki\AppData\Local\Programs\Python\Python35-32\lib\site-packages\numba\cuda\cudadrv\driver.py", line 218, in __getattr__
    self.initialization_error)
numba.cuda.cudadrv.error.CudaSupportError: Error at driver init:
CUDA disabled by user:
</code>```

How do I enable CUDA within numba? I just recently installed CUDA toolkit 7.5 and the most recent numba and numpy in python 3.5.

答:
Try as follows:

'...' is your installation path of CUDA toolkit 7.5 for "nvvm64_31_0.dll" and "libdevice"

```<code>import os
os.environ['NUMBAPRO_NVVM']=r'C:\NVIDIA GPU Computing Toolkit\CUDA\v8.0\nvvm\bin\nvvm64_31_0.dll'
os.environ['NUMBAPRO_LIBDEVICE']=r'C:\NVIDIA GPU Computing Toolkit\CUDA\v8.0\nvvm\libdevice'
</code>```

Body:
By running the code:

import numba

numba.cuda.api.detect()

I get the error:

Traceback (most recent call last):
  File "<pyshell#1>", line 1, in <module>
    numba.cuda.api.detect()
  File "C:\Users\Wakasuki\AppData\Local\Programs\Python\Python35-32\lib\site-packages\numba\cuda\api.py", line 257, in detect
    print('Found %d CUDA devices' % len(devlist))
  File "C:\Users\Wakasuki\AppData\Local\Programs\Python\Python35-32\lib\site-packages\numba\cuda\cudadrv\devices.py", line 49, in __len__
    return len(self.lst)
  File "C:\Users\Wakasuki\AppData\Local\Programs\Python\Python35-32\lib\site-packages\numba\cuda\cudadrv\devices.py", line 26, in __getattr__
    numdev = driver.get_device_count()
  File "C:\Users\Wakasuki\AppData\Local\Programs\Python\Python35-32\lib\site-packages\numba\cuda\cudadrv\driver.py", line 269, in get_device_count
    self.cuDeviceGetCount(byref(count))
  File "C:\Users\Wakasuki\AppData\Local\Programs\Python\Python35-32\lib\site-packages\numba\cuda\cudadrv\driver.py", line 218, in __getattr__
    self.initialization_error)
numba.cuda.cudadrv.error.CudaSupportError: Error at driver init:
CUDA disabled by user:

How do I enable CUDA within numba? I just recently installed CUDA toolkit 7.5 and the most recent numba and numpy in python 3.5.

Body:
Try as follows:

'...' is your installation path of CUDA toolkit 7.5 for "nvvm64_31_0.dll" and "libdevice"

import os
os.environ['NUMBAPRO_NVVM']=r'C:\NVIDIA GPU Computing Toolkit\CUDA\v8.0\nvvm\bin\nvvm64_31_0.dll'
os.environ['NUMBAPRO_LIBDEVICE']=r'C:\NVIDIA GPU Computing Toolkit\CUDA\v8.0\nvvm\libdevice'