问:
How can I parse a string in JS which is the result of google location api?
Here is the result of ajax request:

```<code>console.log(locations.output);
/*
{
   "predictions" : [
      {
         "description" : "Tehran Province, Iran",
         "id" : "4c45c924b261e2bb262360fb5a25d4b9a94088a7",
         "matched_substrings" : [
            {
               "length" : 6,
               "offset" : 0
            }
         ],
         "place_id" : "ChIJf5Us9YQBjj8R0OohvHQms1U",
         "reference" : "CjQtAAAA6j_9DtMr30DQ9h8dzemfD2NaWEWBgf5yFlQ92XW4EZvHXqZ8Ob6wGkedetO1xNiZEhCGeIk7jBXCQP_ad4V0R-YeGhSIcGtxcxPh-G4e2DMT97Be4xdfkg",
         "structured_formatting" : {
            "main_text" : "Tehran Province",
            "main_text_matched_substrings" : [
               {
                  "length" : 6,
                  "offset" : 0
               }
            ],
            "secondary_text" : "Iran"
         },
         "terms" : [
            {
               "offset" : 0,
               "value" : "Tehran Province"
            },
            {
               "offset" : 17,
               "value" : "Iran"
            }
         ],
         "types" : [ "administrative_area_level_1", "political", "geocode" ]
      },
      {
         "description" : "Tehran, Tehran Province, Iran",
         "id" : "14788d031b564588682273730e2e16d2617d3548",
         "matched_substrings" : [
            {
               "length" : 6,
               "offset" : 0
            }
         ],
         "place_id" : "ChIJ2dzzH0kAjj8RvCRwVnxps_A",
         "reference" : "CkQ1AAAAGXsNCFct3XK9JukMD-C7D7j1f0b-Rk0uBZFULZ9TKziZVKz2HWeNWZ5xWU-aNIceYEioJRxHmYS_O7DhMW32YBIQzGS_zTt6aijJx_onRU9DTRoU-cPuoOF16KrzlFY_4EGlwVf1Izk",
         "structured_formatting" : {
            "main_text" : "Tehran",
            "main_text_matched_substrings" : [
               {
                  "length" : 6,
                  "offset" : 0
               }
            ],
            "secondary_text" : "Tehran Province, Iran"
         },
         "terms" : [
            {
               "offset" : 0,
               "value" : "Tehran"
            },
            {
               "offset" : 8,
               "value" : "Tehran Province"
            },
            {
               "offset" : 25,
               "value" : "Iran"
            }
         ],
         "types" : [ "locality", "political", "geocode" ]
      },
      {
         "description" : "Tehranpars, Tehran, Tehran Province, Iran",
         "id" : "09a979a1ac286c1ff2ee94c5d36258910d7f6ec6",
         "matched_substrings" : [
            {
               "length" : 6,
               "offset" : 0
            }
         ],
         "place_id" : "ChIJX5PM9hwdjj8R6zn_mu5suoE",
         "reference" : "ClRBAAAACKbtLWiAm5kV0JzYtPOLhQTuMxlMMIXxPGRmuLUF7xuAlx7Mueo91OuJmB4mTwo3T0NhnNhamVDUsKFE0fNffkZi1Bv-ZQs1TcXLNx195C0SELOTSsOMn6pYeSnFMtvVqsIaFCxWipFk_wIxDKVoLi8Cd8g993cG",
         "structured_formatting" : {
            "main_text" : "Tehranpars",
            "main_text_matched_substrings" : [
               {
                  "length" : 6,
                  "offset" : 0
               }
            ],
            "secondary_text" : "Tehran, Tehran Province, Iran"
         },
         "terms" : [
            {
               "offset" : 0,
               "value" : "Tehranpars"
            },
            {
               "offset" : 12,
               "value" : "Tehran"
            },
            {
               "offset" : 20,
               "value" : "Tehran Province"
            },
            {
               "offset" : 37,
               "value" : "Iran"
            }
         ],
         "types" : [ "neighborhood", "political", "geocode" ]
      },
      {
         "description" : "Tehran Now, Tehran, Tehran Province, Iran",
         "id" : "1f7583f258e7e92f03b818ba10c48e20d2bd9f59",
         "matched_substrings" : [
            {
               "length" : 6,
               "offset" : 0
            }
         ],
         "place_id" : "ChIJ61k7RLICjj8RnvjuZpbZeEM",
         "reference" : "ClRBAAAAydlnsS8Fjw9ibBXXX-XS4xuY4-7yEqMSZNTz66Q-4hRNnGdEGyOICqFbm4VQ4-ZV7O8fftoznes6-u-6sZyvz8Gp3N3hPLASFvtoWeJBPS8SEE8pPnxD20v8_NPnWLANDG8aFPfquA7RBNHvpEgiH5Q0eIqmtl5k",
         "structured_formatting" : {
            "main_text" : "Tehran Now",
            "main_text_matched_substrings" : [
               {
                  "length" : 6,
                  "offset" : 0
               }
            ],
            "secondary_text" : "Tehran, Tehran Province, Iran"
         },
         "terms" : [
            {
               "offset" : 0,
               "value" : "Tehran Now"
            },
            {
               "offset" : 12,
               "value" : "Tehran"
            },
            {
               "offset" : 20,
               "value" : "Tehran Province"
            },
            {
               "offset" : 37,
               "value" : "Iran"
            }
         ],
         "types" : [ "sublocality_level_1", "sublocality", "political", "geocode" ]
      },
      {
         "description" : "Tehran Bazaar, Tehran, Tehran Province, Iran",
         "id" : "7a97ba4c05dcb1b11c2153bd39673b6737aa5748",
         "matched_substrings" : [
            {
               "length" : 6,
               "offset" : 0
            }
         ],
         "place_id" : "ChIJJX5my-8Bjj8RfAUG71zqw8s",
         "reference" : "ClREAAAABs4mvt65BUJ7Z2arVA_cv7V0tdPJKoVy010IOFrlS-L6VfhrEmIQAuxTXVQhnAA19fjEtVbPag3lfb-UrsmnMROnzvXiffA7MKUvgASMwvwSEGx-aGYRXyP1Q9Bxr7HmMVIaFKaxQEb8tg4L7IlRIbITWpG4F5Mf",
         "structured_formatting" : {
            "main_text" : "Tehran Bazaar",
            "main_text_matched_substrings" : [
               {
                  "length" : 6,
                  "offset" : 0
               }
            ],
            "secondary_text" : "Tehran, Tehran Province, Iran"
         },
         "terms" : [
            {
               "offset" : 0,
               "value" : "Tehran Bazaar"
            },
            {
               "offset" : 15,
               "value" : "Tehran"
            },
            {
               "offset" : 23,
               "value" : "Tehran Province"
            },
            {
               "offset" : 40,
               "value" : "Iran"
            }
         ],
         "types" : [ "neighborhood", "political", "geocode" ]
      }
   ],
   "status" : "OK"
}
</code>```

Now I need to make an autocomplete list of the result. I mean I need to make such a thing:

```<code><ul>
  <li>Tehran Province, Iran</li>
  <li>Tehran, Tehran Province, Iran</li>
  <li>Tehranpars, Tehran, Tehran Province, Iran</li>
  <li>Tehran Bazaar, Tehran, Tehran Province, Iran</li>
</ul>
</code>```

But I don't know how can I select the value of description of the result. Here is my code:

```<code>var html = "<ul>";
$.each(locations.output, function (index, value) {
    console.log(value);
})
var html += "</ul>";

/*
"
p
r
e
d
.
.
.
</code>```

As you can see, the result is lots of single characters. How can I get that values?

答:
Jsfiddle link

HTML :

```<code><div id="myListDiv">

</div>
</code>```

Your result data :

```<code>var result = {
   "predictions" : [
      {
         "description" : "Tehran Province, Iran",
         "id" : "4c45c924b261e2bb262360fb5a25d4b9a94088a7",
         "matched_substrings" : [
            {
               "length" : 6,
               "offset" : 0
            }
         ],
         "place_id" : "ChIJf5Us9YQBjj8R0OohvHQms1U",
         "reference" : "CjQtAAAA6j_9DtMr30DQ9h8dzemfD2NaWEWBgf5yFlQ92XW4EZvHXqZ8Ob6wGkedetO1xNiZEhCGeIk7jBXCQP_ad4V0R-YeGhSIcGtxcxPh-G4e2DMT97Be4xdfkg",
         "structured_formatting" : {
            "main_text" : "Tehran Province",
            "main_text_matched_substrings" : [
               {
                  "length" : 6,
                  "offset" : 0
               }
            ],
            "secondary_text" : "Iran"
         },
         "terms" : [
            {
               "offset" : 0,
               "value" : "Tehran Province"
            },
            {
               "offset" : 17,
               "value" : "Iran"
            }
         ],
         "types" : [ "administrative_area_level_1", "political", "geocode" ]
      },
      {
         "description" : "Tehran, Tehran Province, Iran",
         "id" : "14788d031b564588682273730e2e16d2617d3548",
         "matched_substrings" : [
            {
               "length" : 6,
               "offset" : 0
            }
         ],
         "place_id" : "ChIJ2dzzH0kAjj8RvCRwVnxps_A",
         "reference" : "CkQ1AAAAGXsNCFct3XK9JukMD-C7D7j1f0b-Rk0uBZFULZ9TKziZVKz2HWeNWZ5xWU-aNIceYEioJRxHmYS_O7DhMW32YBIQzGS_zTt6aijJx_onRU9DTRoU-cPuoOF16KrzlFY_4EGlwVf1Izk",
         "structured_formatting" : {
            "main_text" : "Tehran",
            "main_text_matched_substrings" : [
               {
                  "length" : 6,
                  "offset" : 0
               }
            ],
            "secondary_text" : "Tehran Province, Iran"
         },
         "terms" : [
            {
               "offset" : 0,
               "value" : "Tehran"
            },
            {
               "offset" : 8,
               "value" : "Tehran Province"
            },
            {
               "offset" : 25,
               "value" : "Iran"
            }
         ],
         "types" : [ "locality", "political", "geocode" ]
      },
      {
         "description" : "Tehranpars, Tehran, Tehran Province, Iran",
         "id" : "09a979a1ac286c1ff2ee94c5d36258910d7f6ec6",
         "matched_substrings" : [
            {
               "length" : 6,
               "offset" : 0
            }
         ],
         "place_id" : "ChIJX5PM9hwdjj8R6zn_mu5suoE",
         "reference" : "ClRBAAAACKbtLWiAm5kV0JzYtPOLhQTuMxlMMIXxPGRmuLUF7xuAlx7Mueo91OuJmB4mTwo3T0NhnNhamVDUsKFE0fNffkZi1Bv-ZQs1TcXLNx195C0SELOTSsOMn6pYeSnFMtvVqsIaFCxWipFk_wIxDKVoLi8Cd8g993cG",
         "structured_formatting" : {
            "main_text" : "Tehranpars",
            "main_text_matched_substrings" : [
               {
                  "length" : 6,
                  "offset" : 0
               }
            ],
            "secondary_text" : "Tehran, Tehran Province, Iran"
         },
         "terms" : [
            {
               "offset" : 0,
               "value" : "Tehranpars"
            },
            {
               "offset" : 12,
               "value" : "Tehran"
            },
            {
               "offset" : 20,
               "value" : "Tehran Province"
            },
            {
               "offset" : 37,
               "value" : "Iran"
            }
         ],
         "types" : [ "neighborhood", "political", "geocode" ]
      },
      {
         "description" : "Tehran Now, Tehran, Tehran Province, Iran",
         "id" : "1f7583f258e7e92f03b818ba10c48e20d2bd9f59",
         "matched_substrings" : [
            {
               "length" : 6,
               "offset" : 0
            }
         ],
         "place_id" : "ChIJ61k7RLICjj8RnvjuZpbZeEM",
         "reference" : "ClRBAAAAydlnsS8Fjw9ibBXXX-XS4xuY4-7yEqMSZNTz66Q-4hRNnGdEGyOICqFbm4VQ4-ZV7O8fftoznes6-u-6sZyvz8Gp3N3hPLASFvtoWeJBPS8SEE8pPnxD20v8_NPnWLANDG8aFPfquA7RBNHvpEgiH5Q0eIqmtl5k",
         "structured_formatting" : {
            "main_text" : "Tehran Now",
            "main_text_matched_substrings" : [
               {
                  "length" : 6,
                  "offset" : 0
               }
            ],
            "secondary_text" : "Tehran, Tehran Province, Iran"
         },
         "terms" : [
            {
               "offset" : 0,
               "value" : "Tehran Now"
            },
            {
               "offset" : 12,
               "value" : "Tehran"
            },
            {
               "offset" : 20,
               "value" : "Tehran Province"
            },
            {
               "offset" : 37,
               "value" : "Iran"
            }
         ],
         "types" : [ "sublocality_level_1", "sublocality", "political", "geocode" ]
      },
      {
         "description" : "Tehran Bazaar, Tehran, Tehran Province, Iran",
         "id" : "7a97ba4c05dcb1b11c2153bd39673b6737aa5748",
         "matched_substrings" : [
            {
               "length" : 6,
               "offset" : 0
            }
         ],
         "place_id" : "ChIJJX5my-8Bjj8RfAUG71zqw8s",
         "reference" : "ClREAAAABs4mvt65BUJ7Z2arVA_cv7V0tdPJKoVy010IOFrlS-L6VfhrEmIQAuxTXVQhnAA19fjEtVbPag3lfb-UrsmnMROnzvXiffA7MKUvgASMwvwSEGx-aGYRXyP1Q9Bxr7HmMVIaFKaxQEb8tg4L7IlRIbITWpG4F5Mf",
         "structured_formatting" : {
            "main_text" : "Tehran Bazaar",
            "main_text_matched_substrings" : [
               {
                  "length" : 6,
                  "offset" : 0
               }
            ],
            "secondary_text" : "Tehran, Tehran Province, Iran"
         },
         "terms" : [
            {
               "offset" : 0,
               "value" : "Tehran Bazaar"
            },
            {
               "offset" : 15,
               "value" : "Tehran"
            },
            {
               "offset" : 23,
               "value" : "Tehran Province"
            },
            {
               "offset" : 40,
               "value" : "Iran"
            }
         ],
         "types" : [ "neighborhood", "political", "geocode" ]
      }
   ],
   "status" : "OK"
};
</code>```

The part extracting data :

```<code>var html = "<ul>";

for (i = 0; i < result.predictions.length; i++) {
   html += "<li>"+result.predictions[i].description+"</li>";
}

html += "</ul>";

var mydiv = document.getElementById('myListDiv').innerHTML = html;
</code>```

Body:
Here is the result of ajax request:

console.log(locations.output);
/*
{
   "predictions" : [
      {
         "description" : "Tehran Province, Iran",
         "id" : "4c45c924b261e2bb262360fb5a25d4b9a94088a7",
         "matched_substrings" : [
            {
               "length" : 6,
               "offset" : 0
            }
         ],
         "place_id" : "ChIJf5Us9YQBjj8R0OohvHQms1U",
         "reference" : "CjQtAAAA6j_9DtMr30DQ9h8dzemfD2NaWEWBgf5yFlQ92XW4EZvHXqZ8Ob6wGkedetO1xNiZEhCGeIk7jBXCQP_ad4V0R-YeGhSIcGtxcxPh-G4e2DMT97Be4xdfkg",
         "structured_formatting" : {
            "main_text" : "Tehran Province",
            "main_text_matched_substrings" : [
               {
                  "length" : 6,
                  "offset" : 0
               }
            ],
            "secondary_text" : "Iran"
         },
         "terms" : [
            {
               "offset" : 0,
               "value" : "Tehran Province"
            },
            {
               "offset" : 17,
               "value" : "Iran"
            }
         ],
         "types" : [ "administrative_area_level_1", "political", "geocode" ]
      },
      {
         "description" : "Tehran, Tehran Province, Iran",
         "id" : "14788d031b564588682273730e2e16d2617d3548",
         "matched_substrings" : [
            {
               "length" : 6,
               "offset" : 0
            }
         ],
         "place_id" : "ChIJ2dzzH0kAjj8RvCRwVnxps_A",
         "reference" : "CkQ1AAAAGXsNCFct3XK9JukMD-C7D7j1f0b-Rk0uBZFULZ9TKziZVKz2HWeNWZ5xWU-aNIceYEioJRxHmYS_O7DhMW32YBIQzGS_zTt6aijJx_onRU9DTRoU-cPuoOF16KrzlFY_4EGlwVf1Izk",
         "structured_formatting" : {
            "main_text" : "Tehran",
            "main_text_matched_substrings" : [
               {
                  "length" : 6,
                  "offset" : 0
               }
            ],
            "secondary_text" : "Tehran Province, Iran"
         },
         "terms" : [
            {
               "offset" : 0,
               "value" : "Tehran"
            },
            {
               "offset" : 8,
               "value" : "Tehran Province"
            },
            {
               "offset" : 25,
               "value" : "Iran"
            }
         ],
         "types" : [ "locality", "political", "geocode" ]
      },
      {
         "description" : "Tehranpars, Tehran, Tehran Province, Iran",
         "id" : "09a979a1ac286c1ff2ee94c5d36258910d7f6ec6",
         "matched_substrings" : [
            {
               "length" : 6,
               "offset" : 0
            }
         ],
         "place_id" : "ChIJX5PM9hwdjj8R6zn_mu5suoE",
         "reference" : "ClRBAAAACKbtLWiAm5kV0JzYtPOLhQTuMxlMMIXxPGRmuLUF7xuAlx7Mueo91OuJmB4mTwo3T0NhnNhamVDUsKFE0fNffkZi1Bv-ZQs1TcXLNx195C0SELOTSsOMn6pYeSnFMtvVqsIaFCxWipFk_wIxDKVoLi8Cd8g993cG",
         "structured_formatting" : {
            "main_text" : "Tehranpars",
            "main_text_matched_substrings" : [
               {
                  "length" : 6,
                  "offset" : 0
               }
            ],
            "secondary_text" : "Tehran, Tehran Province, Iran"
         },
         "terms" : [
            {
               "offset" : 0,
               "value" : "Tehranpars"
            },
            {
               "offset" : 12,
               "value" : "Tehran"
            },
            {
               "offset" : 20,
               "value" : "Tehran Province"
            },
            {
               "offset" : 37,
               "value" : "Iran"
            }
         ],
         "types" : [ "neighborhood", "political", "geocode" ]
      },
      {
         "description" : "Tehran Now, Tehran, Tehran Province, Iran",
         "id" : "1f7583f258e7e92f03b818ba10c48e20d2bd9f59",
         "matched_substrings" : [
            {
               "length" : 6,
               "offset" : 0
            }
         ],
         "place_id" : "ChIJ61k7RLICjj8RnvjuZpbZeEM",
         "reference" : "ClRBAAAAydlnsS8Fjw9ibBXXX-XS4xuY4-7yEqMSZNTz66Q-4hRNnGdEGyOICqFbm4VQ4-ZV7O8fftoznes6-u-6sZyvz8Gp3N3hPLASFvtoWeJBPS8SEE8pPnxD20v8_NPnWLANDG8aFPfquA7RBNHvpEgiH5Q0eIqmtl5k",
         "structured_formatting" : {
            "main_text" : "Tehran Now",
            "main_text_matched_substrings" : [
               {
                  "length" : 6,
                  "offset" : 0
               }
            ],
            "secondary_text" : "Tehran, Tehran Province, Iran"
         },
         "terms" : [
            {
               "offset" : 0,
               "value" : "Tehran Now"
            },
            {
               "offset" : 12,
               "value" : "Tehran"
            },
            {
               "offset" : 20,
               "value" : "Tehran Province"
            },
            {
               "offset" : 37,
               "value" : "Iran"
            }
         ],
         "types" : [ "sublocality_level_1", "sublocality", "political", "geocode" ]
      },
      {
         "description" : "Tehran Bazaar, Tehran, Tehran Province, Iran",
         "id" : "7a97ba4c05dcb1b11c2153bd39673b6737aa5748",
         "matched_substrings" : [
            {
               "length" : 6,
               "offset" : 0
            }
         ],
         "place_id" : "ChIJJX5my-8Bjj8RfAUG71zqw8s",
         "reference" : "ClREAAAABs4mvt65BUJ7Z2arVA_cv7V0tdPJKoVy010IOFrlS-L6VfhrEmIQAuxTXVQhnAA19fjEtVbPag3lfb-UrsmnMROnzvXiffA7MKUvgASMwvwSEGx-aGYRXyP1Q9Bxr7HmMVIaFKaxQEb8tg4L7IlRIbITWpG4F5Mf",
         "structured_formatting" : {
            "main_text" : "Tehran Bazaar",
            "main_text_matched_substrings" : [
               {
                  "length" : 6,
                  "offset" : 0
               }
            ],
            "secondary_text" : "Tehran, Tehran Province, Iran"
         },
         "terms" : [
            {
               "offset" : 0,
               "value" : "Tehran Bazaar"
            },
            {
               "offset" : 15,
               "value" : "Tehran"
            },
            {
               "offset" : 23,
               "value" : "Tehran Province"
            },
            {
               "offset" : 40,
               "value" : "Iran"
            }
         ],
         "types" : [ "neighborhood", "political", "geocode" ]
      }
   ],
   "status" : "OK"
}

Now I need to make an autocomplete list of the result. I mean I need to make such a thing:

Tehran Province, Iran

Tehran, Tehran Province, Iran

Tehranpars, Tehran, Tehran Province, Iran

Tehran Bazaar, Tehran, Tehran Province, Iran

But I don't know how can I select the value of description of the result. Here is my code:

var html = "
";
$.each(locations.output, function (index, value) {
    console.log(value);
})
var html += "
";

/*
"
p
r
e
d
.
.
.

As you can see, the result is lots of single characters. How can I get that values?

Body:
Jsfiddle link

HTML :

<div id="myListDiv">

</div>

Your result data :

var result = {
   "predictions" : [
      {
         "description" : "Tehran Province, Iran",
         "id" : "4c45c924b261e2bb262360fb5a25d4b9a94088a7",
         "matched_substrings" : [
            {
               "length" : 6,
               "offset" : 0
            }
         ],
         "place_id" : "ChIJf5Us9YQBjj8R0OohvHQms1U",
         "reference" : "CjQtAAAA6j_9DtMr30DQ9h8dzemfD2NaWEWBgf5yFlQ92XW4EZvHXqZ8Ob6wGkedetO1xNiZEhCGeIk7jBXCQP_ad4V0R-YeGhSIcGtxcxPh-G4e2DMT97Be4xdfkg",
         "structured_formatting" : {
            "main_text" : "Tehran Province",
            "main_text_matched_substrings" : [
               {
                  "length" : 6,
                  "offset" : 0
               }
            ],
            "secondary_text" : "Iran"
         },
         "terms" : [
            {
               "offset" : 0,
               "value" : "Tehran Province"
            },
            {
               "offset" : 17,
               "value" : "Iran"
            }
         ],
         "types" : [ "administrative_area_level_1", "political", "geocode" ]
      },
      {
         "description" : "Tehran, Tehran Province, Iran",
         "id" : "14788d031b564588682273730e2e16d2617d3548",
         "matched_substrings" : [
            {
               "length" : 6,
               "offset" : 0
            }
         ],
         "place_id" : "ChIJ2dzzH0kAjj8RvCRwVnxps_A",
         "reference" : "CkQ1AAAAGXsNCFct3XK9JukMD-C7D7j1f0b-Rk0uBZFULZ9TKziZVKz2HWeNWZ5xWU-aNIceYEioJRxHmYS_O7DhMW32YBIQzGS_zTt6aijJx_onRU9DTRoU-cPuoOF16KrzlFY_4EGlwVf1Izk",
         "structured_formatting" : {
            "main_text" : "Tehran",
            "main_text_matched_substrings" : [
               {
                  "length" : 6,
                  "offset" : 0
               }
            ],
            "secondary_text" : "Tehran Province, Iran"
         },
         "terms" : [
            {
               "offset" : 0,
               "value" : "Tehran"
            },
            {
               "offset" : 8,
               "value" : "Tehran Province"
            },
            {
               "offset" : 25,
               "value" : "Iran"
            }
         ],
         "types" : [ "locality", "political", "geocode" ]
      },
      {
         "description" : "Tehranpars, Tehran, Tehran Province, Iran",
         "id" : "09a979a1ac286c1ff2ee94c5d36258910d7f6ec6",
         "matched_substrings" : [
            {
               "length" : 6,
               "offset" : 0
            }
         ],
         "place_id" : "ChIJX5PM9hwdjj8R6zn_mu5suoE",
         "reference" : "ClRBAAAACKbtLWiAm5kV0JzYtPOLhQTuMxlMMIXxPGRmuLUF7xuAlx7Mueo91OuJmB4mTwo3T0NhnNhamVDUsKFE0fNffkZi1Bv-ZQs1TcXLNx195C0SELOTSsOMn6pYeSnFMtvVqsIaFCxWipFk_wIxDKVoLi8Cd8g993cG",
         "structured_formatting" : {
            "main_text" : "Tehranpars",
            "main_text_matched_substrings" : [
               {
                  "length" : 6,
                  "offset" : 0
               }
            ],
            "secondary_text" : "Tehran, Tehran Province, Iran"
         },
         "terms" : [
            {
               "offset" : 0,
               "value" : "Tehranpars"
            },
            {
               "offset" : 12,
               "value" : "Tehran"
            },
            {
               "offset" : 20,
               "value" : "Tehran Province"
            },
            {
               "offset" : 37,
               "value" : "Iran"
            }
         ],
         "types" : [ "neighborhood", "political", "geocode" ]
      },
      {
         "description" : "Tehran Now, Tehran, Tehran Province, Iran",
         "id" : "1f7583f258e7e92f03b818ba10c48e20d2bd9f59",
         "matched_substrings" : [
            {
               "length" : 6,
               "offset" : 0
            }
         ],
         "place_id" : "ChIJ61k7RLICjj8RnvjuZpbZeEM",
         "reference" : "ClRBAAAAydlnsS8Fjw9ibBXXX-XS4xuY4-7yEqMSZNTz66Q-4hRNnGdEGyOICqFbm4VQ4-ZV7O8fftoznes6-u-6sZyvz8Gp3N3hPLASFvtoWeJBPS8SEE8pPnxD20v8_NPnWLANDG8aFPfquA7RBNHvpEgiH5Q0eIqmtl5k",
         "structured_formatting" : {
            "main_text" : "Tehran Now",
            "main_text_matched_substrings" : [
               {
                  "length" : 6,
                  "offset" : 0
               }
            ],
            "secondary_text" : "Tehran, Tehran Province, Iran"
         },
         "terms" : [
            {
               "offset" : 0,
               "value" : "Tehran Now"
            },
            {
               "offset" : 12,
               "value" : "Tehran"
            },
            {
               "offset" : 20,
               "value" : "Tehran Province"
            },
            {
               "offset" : 37,
               "value" : "Iran"
            }
         ],
         "types" : [ "sublocality_level_1", "sublocality", "political", "geocode" ]
      },
      {
         "description" : "Tehran Bazaar, Tehran, Tehran Province, Iran",
         "id" : "7a97ba4c05dcb1b11c2153bd39673b6737aa5748",
         "matched_substrings" : [
            {
               "length" : 6,
               "offset" : 0
            }
         ],
         "place_id" : "ChIJJX5my-8Bjj8RfAUG71zqw8s",
         "reference" : "ClREAAAABs4mvt65BUJ7Z2arVA_cv7V0tdPJKoVy010IOFrlS-L6VfhrEmIQAuxTXVQhnAA19fjEtVbPag3lfb-UrsmnMROnzvXiffA7MKUvgASMwvwSEGx-aGYRXyP1Q9Bxr7HmMVIaFKaxQEb8tg4L7IlRIbITWpG4F5Mf",
         "structured_formatting" : {
            "main_text" : "Tehran Bazaar",
            "main_text_matched_substrings" : [
               {
                  "length" : 6,
                  "offset" : 0
               }
            ],
            "secondary_text" : "Tehran, Tehran Province, Iran"
         },
         "terms" : [
            {
               "offset" : 0,
               "value" : "Tehran Bazaar"
            },
            {
               "offset" : 15,
               "value" : "Tehran"
            },
            {
               "offset" : 23,
               "value" : "Tehran Province"
            },
            {
               "offset" : 40,
               "value" : "Iran"
            }
         ],
         "types" : [ "neighborhood", "political", "geocode" ]
      }
   ],
   "status" : "OK"
};

The part extracting data :

var html = "<ul>";

for (i = 0; i < result.predictions.length; i++) {
   html += "<li>"+result.predictions[i].description+"</li>";
}

html += "</ul>";

var mydiv = document.getElementById('myListDiv').innerHTML = html;


来源: stackexchange

问:
python key in dict.keys() performance for large dictionaries
I was wondering if you guys might be able to give me some advice in regards to making the performance of my code much better.

I have a set of for loops which look to see if a key is in a dictionary of which its values are a list, if the key exists, it appends to the list and if it doesnt it adds a new list in for that key

```<code>dict={}
for value in value_list:
   if value.key in dict.keys():
      temp_list = dict[value.key]
      temp_list.append(value.val)
      dict[value.key] = temp_list
   else:
      dict[value.key] = [value.val]
</code>```

Now this code works fine, but evenrually as the dictionary starts to fill up the line value.key in dict.keys() becomes more and more cumbersome.

Is there a better way of doing this?

Thanks,

Mike

答:
Don't do this:

```<code>value.key in dict.keys()
</code>```

That--in Python 2, at least--creates a list containing every key.  That gets more and more expensive as the dictionary gets larger, and performs an O(n) search on the list to find the key, which defeats the purpose of using a dict.

Instead, just do:

```<code>value.key in dict
</code>```

which doesn't create a temporary list, and does a hash table lookup for the key rather than a linear search.

setdefault, as mentioned elsewhere, is the cleaner way to do this, but it's very important to understand the above.

ContentLicense: CC BY-SA 2.5

Body:
I was wondering if you guys might be able to give me some advice in regards to making the performance of my code much better.

I have a set of for loops which look to see if a key is in a dictionary of which its values are a list, if the key exists, it appends to the list and if it doesnt it adds a new list in for that key

dict={}
for value in value_list:
   if value.key in dict.keys():
      temp_list = dict[value.key]
      temp_list.append(value.val)
      dict[value.key] = temp_list
   else:
      dict[value.key] = [value.val]

Now this code works fine, but evenrually as the dictionary starts to fill up the line value.key in dict.keys() becomes more and more cumbersome.

Is there a better way of doing this?

Thanks,

Mike

Body:
Don't do this:

value.key in dict.keys()

That--in Python 2, at least--creates a list containing every key.  That gets more and more expensive as the dictionary gets larger, and performs an O(n) search on the list to find the key, which defeats the purpose of using a dict.

Instead, just do:

value.key in dict

which doesn't create a temporary list, and does a hash table lookup for the key rather than a linear search.

setdefault, as mentioned elsewhere, is the cleaner way to do this, but it's very important to understand the above.


问:
pass vars from javascript ajax to php
I just search around web without found solution :

I have a script where I have this code to reload a query resident in ftp_logs_table2.php without manually refresh the script.

```<code><div id="show"></div>

<script type="text/javascript">
  $(document).ready(function() {
    setInterval(function() {
      $('#show').load('ftp_logs_table2.php')
    }, 1000);
  });
</script>
</code>```

the problem is that I have to pass 2 vars to the query on ftp_logs_table2.php and I don't know howto :
thanks

答:
You need to set up for jQuery ajax function like this.  To pass parameters to the server, user the data attribute:

```<code><div id="show"></div>

<script type="text/javascript">
        $(document).ready(function() {
                setInterval(function () {
                        $.ajax({
                            url: 'ftp_logs_table2.php',
                            data: { var1: 'data', var2: 'data' },
                            method: 'POST',
                            success: function(data) {
                                $('#show').html(data);
                            }
                        })
                }, 1000);
        });
</script>
</code>```

That is a very basic example.  There is great jQuery documentation and examples, as always http://api.jquery.com/jquery.ajax/

ContentLicense: CC BY-SA 3.0

Title: pass vars from javascript ajax to php

Body:
I just search around web without found solution :

I have a script where I have this code to reload a query resident in ftp_logs_table2.php without manually refresh the script.

the problem is that I have to pass 2 vars to the query on ftp_logs_table2.php and I don't know howto :
thanks

Body:
You need to set up for jQuery ajax function like this.  To pass parameters to the server, user the data attribute:

<div id="show"></div>

<script type="text/javascript">
        $(document).ready(function() {
                setInterval(function () {
                        $.ajax({
                            url: 'ftp_logs_table2.php',
                            data: { var1: 'data', var2: 'data' },
                            method: 'POST',
                            success: function(data) {
                                $('#show').html(data);
                            }
                        })
                }, 1000);
        });
</script>

That is a very basic example.  There is great jQuery documentation and examples, as always http://api.jquery.com/jquery.ajax/


答:
It looks like you're already using jQuery, so you can use the $.ajax function from that library.

With passing data to your PHP file your code will look something like the following;

```<code>$.ajax({
  method: "POST",
  url: "ftp_logs_table2.php",
  data: { this: "that", foo: "bar" }
})
.done(function( msg ) {
  alert( "Data Saved: " + msg );
});
</code>```

The docs for it can be found here: http://api.jquery.com/jquery.ajax/

Title: pass vars from javascript ajax to php

Body:
It looks like you're already using jQuery, so you can use the $.ajax function from that library.

With passing data to your PHP file your code will look something like the following;

$.ajax({
  method: "POST",
  url: "ftp_logs_table2.php",
  data: { this: "that", foo: "bar" }
})
.done(function( msg ) {
  alert( "Data Saved: " + msg );
});

The docs for it can be found here: http://api.jquery.com/jquery.ajax/


问:
How to make a button Visible when RecyclerView has items in it?
i'm making a note taking app.
There's a button to clear all the items in RecyclerView and its Visibility is set to Gone. But I want it to be Visible only when there are Notes in the app.
 I don't know why using
 if (notesList.size()>0){
            removeAllButton.setVisibility(View.VISIBLE);
 doesn't work! How can i do this?

 Edit: Added the Adapter code.

Here's my Main Class:

```<code>public class MainActivity extends AppCompatActivity {
private List<Notes> notesList = new ArrayList<>();
private static final int REQUEST_CODE = 1001;
final NoteAdapter adapter = new NoteAdapter(this);

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    final RecyclerView recyclerView = findViewById(R.id.rv_recyclerView);
    LinearLayoutManager layoutManager = new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false);
    recyclerView.setLayoutManager(layoutManager);
    recyclerView.setAdapter(adapter);
    Button addNoteButton = findViewById(R.id.button_main_addNote);
    final Button removeAllButton = findViewById(R.id.button_main_deleteAll);
    addNoteButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Intent intent = new Intent(MainActivity.this, NoteEdit.class);
            startActivityForResult(intent, REQUEST_CODE);
        }
    });

    removeAllButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            adapter.removeAll();
            removeAllButton.setVisibility(View.GONE);
        }
    });
    if (adapter.getItemCount()>=1){
        removeAllButton.setVisibility(View.VISIBLE);
    }
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    if (requestCode == REQUEST_CODE &&
            resultCode == RESULT_OK &&
            data != null) {
        String noteTitle = data.getStringExtra(NoteEdit.Result_Key_Title);
        String noteDescription = data.getStringExtra(NoteEdit.Result_Key_Description);
        Notes notes = new Notes();
        notes.setNoteTitle(noteTitle);
        notes.setNoteDescription(noteDescription);
        adapter.addNote(notes);
        adapter.getItemCount();
    }
}}
</code>```

Adapter Class :

```<code>public class NoteAdapter extends RecyclerView.Adapter<NoteAdapter.SimpleItemViewHolder> {

private Context context;
private List<Notes> notes = new ArrayList<>();

public NoteAdapter(Context context) {

    this.context = context;
}

@Override
public SimpleItemViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
    LayoutInflater layoutInflater = LayoutInflater.from(context);
    View view = layoutInflater.inflate(R.layout.item_sample, parent, false);
    return new SimpleItemViewHolder(view);
}

@Override
public void onBindViewHolder(SimpleItemViewHolder holder, int position) {
    holder.bindNote(notes.get(position));

}

@Override
public int getItemCount() {
    return notes.size();
}

public void addNote(Notes note) {
    notes.add(note);
    notifyItemInserted(notes.size() - 1);
}

public void removeAll () {
    notes.clear();
    notifyDataSetChanged();
}

private TextView titleTextView;
private TextView descriptionTextView;

public class SimpleItemViewHolder extends RecyclerView.ViewHolder {

    public SimpleItemViewHolder(View itemView) {
        super(itemView);
        titleTextView = itemView.findViewById(R.id.tv_itemSample_title);
        descriptionTextView = itemView.findViewById(R.id.tv_itemSample_description);
    }

    public void bindNote(Notes note) {
        titleTextView.setText(note.getNoteTitle());
        descriptionTextView.setText(note.getNoteDescription());
    }

}}
</code>```

答:
According to your Code, You should try with getItemCount()

Returns the total number of items in the data set held by the
  adapter.

```<code>  if(adapter.getItemCount() != 0)
    {
    // VISIBLE
    }
</code>```

Body:
i'm making a note taking app.
There's a button to clear all the items in RecyclerView and its Visibility is set to Gone. But I want it to be Visible only when there are Notes in the app.
 I don't know why using
 if (notesList.size()>0){
            removeAllButton.setVisibility(View.VISIBLE);
 doesn't work! How can i do this?

 Edit: Added the Adapter code.

Here's my Main Class:

public class MainActivity extends AppCompatActivity {
private List<Notes> notesList = new ArrayList<>();
private static final int REQUEST_CODE = 1001;
final NoteAdapter adapter = new NoteAdapter(this);

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    final RecyclerView recyclerView = findViewById(R.id.rv_recyclerView);
    LinearLayoutManager layoutManager = new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false);
    recyclerView.setLayoutManager(layoutManager);
    recyclerView.setAdapter(adapter);
    Button addNoteButton = findViewById(R.id.button_main_addNote);
    final Button removeAllButton = findViewById(R.id.button_main_deleteAll);
    addNoteButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Intent intent = new Intent(MainActivity.this, NoteEdit.class);
            startActivityForResult(intent, REQUEST_CODE);
        }
    });

    removeAllButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            adapter.removeAll();
            removeAllButton.setVisibility(View.GONE);
        }
    });
    if (adapter.getItemCount()>=1){
        removeAllButton.setVisibility(View.VISIBLE);
    }
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    if (requestCode == REQUEST_CODE &&
            resultCode == RESULT_OK &&
            data != null) {
        String noteTitle = data.getStringExtra(NoteEdit.Result_Key_Title);
        String noteDescription = data.getStringExtra(NoteEdit.Result_Key_Description);
        Notes notes = new Notes();
        notes.setNoteTitle(noteTitle);
        notes.setNoteDescription(noteDescription);
        adapter.addNote(notes);
        adapter.getItemCount();
    }
}}

Adapter Class :

public class NoteAdapter extends RecyclerView.Adapter<NoteAdapter.SimpleItemViewHolder> {

private Context context;
private List<Notes> notes = new ArrayList<>();

public NoteAdapter(Context context) {

    this.context = context;
}

@Override
public SimpleItemViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
    LayoutInflater layoutInflater = LayoutInflater.from(context);
    View view = layoutInflater.inflate(R.layout.item_sample, parent, false);
    return new SimpleItemViewHolder(view);
}

@Override
public void onBindViewHolder(SimpleItemViewHolder holder, int position) {
    holder.bindNote(notes.get(position));

}

@Override
public int getItemCount() {
    return notes.size();
}

public void addNote(Notes note) {
    notes.add(note);
    notifyItemInserted(notes.size() - 1);
}

public void removeAll () {
    notes.clear();
    notifyDataSetChanged();
}

private TextView titleTextView;
private TextView descriptionTextView;

public class SimpleItemViewHolder extends RecyclerView.ViewHolder {

    public SimpleItemViewHolder(View itemView) {
        super(itemView);
        titleTextView = itemView.findViewById(R.id.tv_itemSample_title);
        descriptionTextView = itemView.findViewById(R.id.tv_itemSample_description);
    }

    public void bindNote(Notes note) {
        titleTextView.setText(note.getNoteTitle());
        descriptionTextView.setText(note.getNoteDescription());
    }

}}

Body:
According to your Code, You should try with getItemCount()

Returns the total number of items in the data set held by the
  adapter.

  if(adapter.getItemCount() != 0)
    {
    // VISIBLE
    }


问:
How to access Class member variables from SpringApplication in Spring Boot
How do you access a member variable when starting the application using SpringApplication in SpringBoot ?

In the below code I am getting compilation errors on the assignment to Environment and BuildProperties. I think there must be a way to reference these properties via the SpringApplication or ConfigurableApplicationContext but I don't know how.

The compile error I am getting is,
non-static variable environment cannot be referenced from a static context
which I understand its just how to get around it.

I think my question really is - does SpringApplication return a Class level reference in the same way as doing a normal java MyClass myClass = new MyClass() does ?

```<code>@Slf4j
@EnableIntegration
@EnableLoaderApplication
@SpringBootApplication
@EnableDiscoveryClient
public class ExampleApplication {

    private Environment environment;
    private BuildProperties buildProperties;

    public ExampleApplication(Environment env, BuildProperties buildProp) {
        environment = env;
        buildProperties = buildProp;
    }

    public static void main(String[] args) {
        SpringApplication app = new SpringApplication(ExampleApplication.class);
        ConfigurableApplicationContext context = app.run(args);

        environment = context.getEnvironment();  //compile error
        buildProperties = context.getBean(BuildProperties.class); //compile error

    DisplaySysInfo displaySysInfo = new DisplaySysInfo(environment, buildProperties, log);
    displaySysInfo.splash();

    }

}
</code>```

答:
Here I am answering to your question

"I think my question really is - does SpringApplication return a Class level reference in the same way as doing a normal java MyClass myClass = new MyClass() does ?"

Short Answer is No, Spring doesn't return the reference to object instance like new MyClass() does. When you use spring context you get references to Beans that are actually proxies to something like normal classes.
I suggest you read more about DI and spring components, here there is a spring_bean_definition mini tutorial. The tutorial is a bit old, and make use of the xml notation to declare beans, but concepts and definition are still valid.

Hope this could help.

Body:
How do you access a member variable when starting the application using SpringApplication in SpringBoot ?

In the below code I am getting compilation errors on the assignment to Environment and BuildProperties. I think there must be a way to reference these properties via the SpringApplication or ConfigurableApplicationContext but I don't know how.

The compile error I am getting is,
non-static variable environment cannot be referenced from a static context
which I understand its just how to get around it.

I think my question really is - does SpringApplication return a Class level reference in the same way as doing a normal java MyClass myClass = new MyClass() does ?

@Slf4j
@EnableIntegration
@EnableLoaderApplication
@SpringBootApplication
@EnableDiscoveryClient
public class ExampleApplication {

    private Environment environment;
    private BuildProperties buildProperties;

    public ExampleApplication(Environment env, BuildProperties buildProp) {
        environment = env;
        buildProperties = buildProp;
    }

    public static void main(String[] args) {
        SpringApplication app = new SpringApplication(ExampleApplication.class);
        ConfigurableApplicationContext context = app.run(args);

        environment = context.getEnvironment();  //compile error
        buildProperties = context.getBean(BuildProperties.class); //compile error

    DisplaySysInfo displaySysInfo = new DisplaySysInfo(environment, buildProperties, log);
    displaySysInfo.splash();

    }

}


问:
Bash change number to another value on specific line
i'm new with bash scripting , and i looking for solution to change a number to another value on specific line.
I have file named foo.config and in this file i have about 100 lines of configuration.
For example i have

<UpdateInterval>2</UpdateInterval>

and i need to find this line on foo.config and replace number(this can be number for 0 to 10 and for my example is 2) for 0 as always.

Like this :
<UpdateInterval>0</UpdateInterval>

How can i do it with sed ? please suggest

the part of lines:

```<code><InstallUrl />
<TargetCulture>en</TargetCulture>
<ApplicationVersion>1.0.1.8</ApplicationVersion>
<AutoIncrementApplicationRevision>true</AutoIncrementApplicationRevision>
<UpdateEnabled>true</UpdateEnabled>
<UpdateInterval>2</UpdateInterval>
<UpdateIntervalUnits>hours</UpdateIntervalUnits>
<ProductName>xxxxxxxxxxxx</ProductName>
<PublisherName />
<SupportUrl />
<FriendlyName>xxxxxxxxxxxx</FriendlyName>
<OfficeApplicationDescription />
<LoadBehavior>3</LoadBehavior>
</code>```

答:
In a very simple way, you may try:

```<code>sed -E 's/^<UpdateInterval>[0-9]+/<UpdateInterval>0/' foo.config
</code>```

This will search for <UpdateInterval> at the beginning of a line (note the ^) and then a number ([0-9] stands for a digit and + for a repetition of one or more). This bit will be replaced with <UpdateInterval>0. The / characters separate what you search and what will replace it. The s command is a search and replace.

It will take the file foo.config as input and you will get the output on standard output. If you want your output on the same file, you may do:

```<code>sed -E 's/^<UpdateInterval>[0-9]+/<UpdateInterval>0/' foo.config >foo.temp
mv foo.temp foo.config
</code>```

Or more simply:

```<code>sed -i -E 's/^<UpdateInterval>[0-9]+/<UpdateInterval>0/' foo.config
</code>```

Note that this is not a good way to do the substitution if your config file contains general XML. It will only work in the simplest of cases (but will do for your example.) If your XML bit may be in the middle of a line, remove the ^ character. The search and replace expression assumes that there is no whitespace around the XML tags.

Body:
i'm new with bash scripting , and i looking for solution to change a number to another value on specific line.
I have file named foo.config and in this file i have about 100 lines of configuration.
For example i have

<UpdateInterval>2</UpdateInterval>

and i need to find this line on foo.config and replace number(this can be number for 0 to 10 and for my example is 2) for 0 as always.

Like this :
<UpdateInterval>0</UpdateInterval>

How can i do it with sed ? please suggest

the part of lines:

<InstallUrl />
<TargetCulture>en</TargetCulture>
<ApplicationVersion>1.0.1.8</ApplicationVersion>
<AutoIncrementApplicationRevision>true</AutoIncrementApplicationRevision>
<UpdateEnabled>true</UpdateEnabled>
<UpdateInterval>2</UpdateInterval>
<UpdateIntervalUnits>hours</UpdateIntervalUnits>
<ProductName>xxxxxxxxxxxx</ProductName>
<PublisherName />
<SupportUrl />
<FriendlyName>xxxxxxxxxxxx</FriendlyName>
<OfficeApplicationDescription />
<LoadBehavior>3</LoadBehavior>

Body:
In a very simple way, you may try:

sed -E 's/^<UpdateInterval>[0-9]+/<UpdateInterval>0/' foo.config

This will search for <UpdateInterval> at the beginning of a line (note the ^) and then a number ([0-9] stands for a digit and + for a repetition of one or more). This bit will be replaced with <UpdateInterval>0. The / characters separate what you search and what will replace it. The s command is a search and replace.

It will take the file foo.config as input and you will get the output on standard output. If you want your output on the same file, you may do:

sed -E 's/^<UpdateInterval>[0-9]+/<UpdateInterval>0/' foo.config >foo.temp
mv foo.temp foo.config

Or more simply:

sed -i -E 's/^<UpdateInterval>[0-9]+/<UpdateInterval>0/' foo.config

Note that this is not a good way to do the substitution if your config file contains general XML. It will only work in the simplest of cases (but will do for your example.) If your XML bit may be in the middle of a line, remove the ^ character. The search and replace expression assumes that there is no whitespace around the XML tags.


问:
Check if a given key already exists in a dictionary and increment it
How do I find out if a key in a dictionary has already been set to a non-None value?

I want to increment the value if there's already one there, or set it to 1 otherwise:

```<code>my_dict = {}

if my_dict[key] is not None:
  my_dict[key] = 1
else:
  my_dict[key] += 1
</code>```

答:
You are looking for collections.defaultdict (available for Python 2.5+). This

```<code>from collections import defaultdict

my_dict = defaultdict(int)
my_dict[key] += 1
</code>```

will do what you want.

For regular Python dicts, if there is no value for a given key, you will not get None when accessing the dict -- a KeyError will be raised. So if you want to use a regular dict, instead of your code you would use

```<code>if key in my_dict:
    my_dict[key] += 1
else:
    my_dict[key] = 1
</code>```

OwnerDisplayName: Ben

ContentLicense: CC BY-SA 4.0

Body:
How do I find out if a key in a dictionary has already been set to a non-None value?

I want to increment the value if there's already one there, or set it to 1 otherwise:

my_dict = {}

if my_dict[key] is not None:
  my_dict[key] = 1
else:
  my_dict[key] += 1

Body:
You are looking for collections.defaultdict (available for Python 2.5+). This

from collections import defaultdict

my_dict = defaultdict(int)
my_dict[key] += 1

will do what you want.

For regular Python dicts, if there is no value for a given key, you will not get None when accessing the dict -- a KeyError will be raised. So if you want to use a regular dict, instead of your code you would use

if key in my_dict:
    my_dict[key] += 1
else:
    my_dict[key] = 1

OwnerDisplayName: dF

LastEditorDisplayName: dF


问:
.next() and .prev() to loop through divs
I want to use simple jQuery to perform slide through div elements. But how do I use next() and prev() to go through slide items?

The problem is when you go next, next, next, next. The div finally stops and doesn't show; it doesn't loop round back to the first div.

This is what I've got so far:

$("p.right").click(function() {
  $(".item.active").removeClass("active").next(".item").addClass("active").show();
});
$("p.left").click(function() {
  $(".item.active").removeClass("active").prev(".item").addClass("active").show();
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>Section {
  position: relative;
  height: 200px;
  width: 200px;
  text-align: center;
}

p {
  position: absolute;
  margin: 0px;
  padding: 5px 10px;
  background: blue;
  color: #ffffff;
  border-radius: 100%;
}

p.left {
  top: 0px;
  left: 20px;
}

p.right {
  top: 0px;
  right: 20px;
}

div {
  display: none;
}

div.active {
  display: block;
}</code>```

First Item

Second Item

Third Item

Last Item

N

P

```

答:
You'll need to check if the index of .active is the first or last item.

$(function() {
  var numSlides = $('div.active').parent().find('div').length;

  $("p.right").click(function() {
    if( $('div.active').index()+1 == numSlides ) {
      $('div.active').removeClass('active').parent().find('div:first').addClass('active');
    }
    else {
      $("div.active").removeClass("active").next("div").addClass("active");
    }
  });
  $("p.left").click(function() {
    if( $('div.active').index() == 0 ) {
      $('div.active').removeClass('active').parent().find('div:last').addClass('active');
    }
    else {
      $("div.active").removeClass("active").prev("div").addClass("active").show();
    }
  });
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>Section {
  position: relative;
  height: 200px;
  width: 200px;
  text-align: center;
}

p {
  position: absolute;
  margin: 0px;
  padding: 5px 10px;
  background: blue;
  color: #ffffff;
  border-radius: 100%;
}

p.left {
  top: 0px;
  left: 20px;
}

p.right {
  top: 0px;
  right: 20px;
}

div {
  display: none;
}

div.active {
  display: block;
}</code>```

First Item

Second Item

Third Item

Last Item

N

P

```

Body:
I want to use simple jQuery to perform slide through div elements. But how do I use next() and prev() to go through slide items?

The problem is when you go next, next, next, next. The div finally stops and doesn't show; it doesn't loop round back to the first div.

This is what I've got so far:

$("p.right").click(function() {
  $(".item.active").removeClass("active").next(".item").addClass("active").show();
});
$("p.left").click(function() {
  $(".item.active").removeClass("active").prev(".item").addClass("active").show();
});

Section {
  position: relative;
  height: 200px;
  width: 200px;
  text-align: center;
}

p {
  position: absolute;
  margin: 0px;
  padding: 5px 10px;
  background: blue;
  color: #ffffff;
  border-radius: 100%;
}

p.left {
  top: 0px;
  left: 20px;
}

p.right {
  top: 0px;
  right: 20px;
}

div {
  display: none;
}

div.active {
  display: block;
}

First Item

Second Item

Third Item

Last Item

N

P

Body:
You'll need to check if the index of .active is the first or last item.

$(function() {
  var numSlides = $('div.active').parent().find('div').length;

  $("p.right").click(function() {
    if( $('div.active').index()+1 == numSlides ) {
      $('div.active').removeClass('active').parent().find('div:first').addClass('active');
    }
    else {
      $("div.active").removeClass("active").next("div").addClass("active");
    }
  });
  $("p.left").click(function() {
    if( $('div.active').index() == 0 ) {
      $('div.active').removeClass('active').parent().find('div:last').addClass('active');
    }
    else {
      $("div.active").removeClass("active").prev("div").addClass("active").show();
    }
  });
});

Section {
  position: relative;
  height: 200px;
  width: 200px;
  text-align: center;
}

p {
  position: absolute;
  margin: 0px;
  padding: 5px 10px;
  background: blue;
  color: #ffffff;
  border-radius: 100%;
}

p.left {
  top: 0px;
  left: 20px;
}

p.right {
  top: 0px;
  right: 20px;
}

div {
  display: none;
}

div.active {
  display: block;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<section>
  <div class="active">First Item</div>
  <div>Second Item</div>
  <div>Third Item</div>
  <div>Last Item</div>
  <p class="right">N</p>
  <p class="left">P</p>
</section>


问:
c# mongodb driver how to cast a mongo double value to a c# decimal one
I have this bson document which I read from mongodb, using c# mongodb driver v2.4.4. I just need to convert some field in it to decimal in a c# code. I know there is a double value there, therefore I try to convert to a decimal value using:

```<code>monto = Convert.ToDecimal(document["monto"].AsDouble)
</code>```

But, as the value is 39330000, I suppose the driver assumes it is a Int32 and throws this exception:

Unable to cast object of type 'MongoDB.Bson.BsonInt32' to type
  'MongoDB.Bson.BsonDouble'.

Maybe because it doesn't come with the dot (.) in it.

So, I'm using this to convert to decimal:

```<code>monto = Convert.ToDecimal(document["monto"].ToString())
</code>```

And it works because c# can convert to decimal any string that contains a number.

My question is: is there a better way to convert a bson double to c# decimal, without converting it to a string first ?

Thanks and bye ...

答:
The best option would probably to go with this:

```<code>monto = document["monto"].ToDecimal();
</code>```

The reason why this works so nicely is that the abstract BsonValue type implements a method that looks like this:

```<code>public virtual decimal ToDecimal()
</code>```

The concrete implementations of BsonValue (e.g. BsonInt32, BsonInt64, BsonDouble etc.) override this member with the below method which gives you precisely what you want, no matter if the driver deserializes an int, a long or a double from a stored document:

```<code>public override decimal ToDecimal()
{
    return (decimal)_value;
}
</code>```

Alternatively, in your specific case (and if all documents in scope have an int stored in their "monto" field) you can simply write:

```<code>monto = Convert.ToDecimal(document["monto"].AsInt32)
</code>```

or even just

```<code>monto = (decimal)(document["monto"].AsInt32)
</code>```

which are semantically identical.

Body:
I have this bson document which I read from mongodb, using c# mongodb driver v2.4.4. I just need to convert some field in it to decimal in a c# code. I know there is a double value there, therefore I try to convert to a decimal value using:

monto = Convert.ToDecimal(document["monto"].AsDouble)

But, as the value is 39330000, I suppose the driver assumes it is a Int32 and throws this exception:

Unable to cast object of type 'MongoDB.Bson.BsonInt32' to type
  'MongoDB.Bson.BsonDouble'.

Maybe because it doesn't come with the dot (.) in it.

So, I'm using this to convert to decimal:

monto = Convert.ToDecimal(document["monto"].ToString())

And it works because c# can convert to decimal any string that contains a number.

My question is: is there a better way to convert a bson double to c# decimal, without converting it to a string first ?

Thanks and bye ...

Body:
The best option would probably to go with this:

monto = document["monto"].ToDecimal();

The reason why this works so nicely is that the abstract BsonValue type implements a method that looks like this:

public virtual decimal ToDecimal()

The concrete implementations of BsonValue (e.g. BsonInt32, BsonInt64, BsonDouble etc.) override this member with the below method which gives you precisely what you want, no matter if the driver deserializes an int, a long or a double from a stored document:

public override decimal ToDecimal()
{
    return (decimal)_value;
}

Alternatively, in your specific case (and if all documents in scope have an int stored in their "monto" field) you can simply write:

monto = Convert.ToDecimal(document["monto"].AsInt32)

or even just

monto = (decimal)(document["monto"].AsInt32)

which are semantically identical.


问:
Rowmeans for N sequential columns
In a dataframe with n*3 columns, how to calculate row means for every three (or any other number) sequential columns, e.g. for columns (1,2,3), (4,5,6), (7,8,9), etc?

There is a solution here on Code Review-Mean of many subsets of a dataframe, but I wonder if there is a more elegant method.

答:
Base R solution (specify by how many columns to apply function and iterate over those groups):</p>

```<code># Generate dummy data (matrix 2 x 9)
foo <- matrix(rnorm(18), 2)
# By how many columns apply function
BY <- 3
# Apply rowmeans by rows and columns
sapply(1:(ncol(foo)/BY), function(x) rowMeans(foo[, ((x * BY) - BY + 1):(x * BY)]))
</code>```

Title: Rowmeans for N sequential columns

Body:
Base R solution (specify by how many columns to apply function and iterate over those groups):

# Generate dummy data (matrix 2 x 9)
foo <- matrix(rnorm(18), 2)
# By how many columns apply function
BY <- 3
# Apply rowmeans by rows and columns
sapply(1:(ncol(foo)/BY), function(x) rowMeans(foo[, ((x * BY) - BY + 1):(x * BY)]))


答:
Try some iteration of this:</p>

```<code>if (this.is('div:last-child')) {
   //Start carousel over at first child
}else {
   // On to the next one
}
</code>```

Title: .next() and .prev() to loop through divs

Body:
Try some iteration of this:

if (this.is('div:last-child')) {
   //Start carousel over at first child
}else {
   // On to the next one
}


问:
How to count all groups returned by a group by query in JPQL?
If I have a group by query

```<code>Select e.field1, e.field2...
from Entity w
group by e.field1, e.field2...
</code>```

How can I count the number of rows not using NativeQuery?
I need to do something like this:

```<code>select count(*) from
(Select e.field1, e.field2...
from Entity w
group by e.field1, e.field2...)
</code>```

Is there any way to do with JPQL?

答:
in oracle you can this hql

```<code>Select sum(count(*) - count(*) + 1)
from Entity e
group by e.field1, e.field2...
</code>```

but dose not work in postgres

Body:
If I have a group by query

Select e.field1, e.field2...
from Entity w
group by e.field1, e.field2...

How can I count the number of rows not using NativeQuery?
I need to do something like this:

select count(*) from
(Select e.field1, e.field2...
from Entity w
group by e.field1, e.field2...)

Is there any way to do with JPQL?

Body:
in oracle you can this hql

Select sum(count(*) - count(*) + 1)
from Entity e
group by e.field1, e.field2...

but dose not work in postgres


问:
ORA-01722 invalid number on using the expression in select and while joining
```<code>CASE WHEN (r.code_value4 = 0 AND LENGTH(ltrim(rtrim(xx.AFFILIATE_CODE))) > 0) AND
          r_intercompany.code_value1 is not null AND
          ltrim(rtrim(xx.AFFILIATE_CODE)) <> (CASE WHEN xx.COMPANY_CODE_JE_EXCEPTION_FLAG = 1
                                                   THEN r.code_value3 ELSE r.code_value1 END)
     THEN r_intercompany.code_value1
     ELSE NVL(r_mga_acct.code_value2, xx.ACCOUNT_NUMBER) END
</code>```

I have view in which the above part of the sql is being used in select statement and as well as to compare with a field while joining. When I run the view after making this change, it is throwing the error ORA-01722 invalid number.

Please let me know on how to correct this.

Thanks

答:
" it is throwing the error ORA-01722 invalid number."

It is likely somewhere you are comparing a numeric column with a string column . Oracle is implicitly casting the string to a number but the column contains values which cannot be converted, so it hurls.

"Please let me know on how to correct this."

Don't rely on implicit data conversion. Go through your code, check the data types of all the columns. Where you find a varchar2 column being compared to a number you need to cast the number to a string. For literals that means quoting them - '1' instead of 1 - and for columns that means wrapping them in to_char() calls.

Body:
CASE WHEN (r.code_value4 = 0 AND LENGTH(ltrim(rtrim(xx.AFFILIATE_CODE))) > 0) AND
          r_intercompany.code_value1 is not null AND
          ltrim(rtrim(xx.AFFILIATE_CODE)) <> (CASE WHEN xx.COMPANY_CODE_JE_EXCEPTION_FLAG = 1
                                                   THEN r.code_value3 ELSE r.code_value1 END)
     THEN r_intercompany.code_value1
     ELSE NVL(r_mga_acct.code_value2, xx.ACCOUNT_NUMBER) END

I have view in which the above part of the sql is being used in select statement and as well as to compare with a field while joining. When I run the view after making this change, it is throwing the error ORA-01722 invalid number.

Please let me know on how to correct this.

Thanks


问:
Whitespace Matching Regex - Java
The Java API for regular expressions states that \s will match whitespace. So the regex \\s\\s should match two spaces.

```<code>Pattern whitespace = Pattern.compile("\\s\\s");
matcher = whitespace.matcher(modLine);
while (matcher.find()) matcher.replaceAll(" ");
</code>```

The aim of this is to replace all instances of two consecutive whitespace with a single space. However this does not actually work.

Am I having a grave misunderstanding of regexes or the term "whitespace"?

答:
Seems to work for me:

```<code>String s = "  a   b      c";
System.out.println("\""  + s.replaceAll("\\s\\s", " ") + "\"");
</code>```

will print:

```<code>" a  b   c"
</code>```

I think you intended to do this instead of your code:

```<code>Pattern whitespace = Pattern.compile("\\s\\s");
Matcher matcher = whitespace.matcher(s);
String result = "";
if (matcher.find()) {
    result = matcher.replaceAll(" ");
}

System.out.println(result);
</code>```

Title: Whitespace Matching Regex - Java

Body:
The Java API for regular expressions states that \s will match whitespace. So the regex \\s\\s should match two spaces.

Pattern whitespace = Pattern.compile("\\s\\s");
matcher = whitespace.matcher(modLine);
while (matcher.find()) matcher.replaceAll(" ");

The aim of this is to replace all instances of two consecutive whitespace with a single space. However this does not actually work.

Am I having a grave misunderstanding of regexes or the term "whitespace"?

Body:
Seems to work for me:

String s = "  a   b      c";
System.out.println("\""  + s.replaceAll("\\s\\s", " ") + "\"");

will print:

" a  b   c"

I think you intended to do this instead of your code:

Pattern whitespace = Pattern.compile("\\s\\s");
Matcher matcher = whitespace.matcher(s);
String result = "";
if (matcher.find()) {
    result = matcher.replaceAll(" ");
}

System.out.println(result);


答:
Try using typed objects then you won't need to bother with converting them yourself.

Here I have a Product with that have a few different types for the price but in this model I want them all to come back as a decimal:

```<code>public class Product
{
    public ObjectId Id { get; set; }

    public string Name { get; set; }

    public decimal Int32Price { get; set; }

    public decimal StringPrice { get; set; }

    public decimal Decimal128Price { get; set; }
}
</code>```

We can then push some data in to mongodb

```<code>var mongoDatabase = new MongoClient().GetDatabase("test");
var untypedCollection = mongoDatabase.GetCollection<BsonDocument>("products");
var doc = new BsonDocument()
{
    {"Name", "Shampoo" },
    {"Int32Price", BsonInt32.Create(33) },
    {"StringPrice", BsonString.Create("33.45") },
    {"Decimal128Price", BsonDecimal128.Create(33.45m) },
};
untypedCollection.InsertOne(doc);
</code>```

then get it back out using our typed object:

```<code>var productCollection = mongoDatabase.GetCollection<Product>("products");

var product = productCollection.Find(x => x.Id == doc["_id"]).First();

Console.WriteLine(product.Id);
Console.WriteLine(product.Name);
Console.WriteLine(product.Int32Price);
Console.WriteLine(product.StringPrice);
Console.WriteLine(product.Decimal128Price);

// 5a0c581b1a1c8f310049815a
// Shampoo
// 33
// 33.45
// 33.45
</code>```

Title: c# mongodb driver how to cast a mongo double value to a c# decimal one

Body:
Try using typed objects then you won't need to bother with converting them yourself.

Here I have a Product with that have a few different types for the price but in this model I want them all to come back as a decimal:

public class Product
{
    public ObjectId Id { get; set; }

    public string Name { get; set; }

    public decimal Int32Price { get; set; }

    public decimal StringPrice { get; set; }

    public decimal Decimal128Price { get; set; }
}

We can then push some data in to mongodb

var mongoDatabase = new MongoClient().GetDatabase("test");
var untypedCollection = mongoDatabase.GetCollection<BsonDocument>("products");
var doc = new BsonDocument()
{
    {"Name", "Shampoo" },
    {"Int32Price", BsonInt32.Create(33) },
    {"StringPrice", BsonString.Create("33.45") },
    {"Decimal128Price", BsonDecimal128.Create(33.45m) },
};
untypedCollection.InsertOne(doc);

then get it back out using our typed object:

var productCollection = mongoDatabase.GetCollection<Product>("products");

var product = productCollection.Find(x => x.Id == doc["_id"]).First();

Console.WriteLine(product.Id);
Console.WriteLine(product.Name);
Console.WriteLine(product.Int32Price);
Console.WriteLine(product.StringPrice);
Console.WriteLine(product.Decimal128Price);

// 5a0c581b1a1c8f310049815a
// Shampoo
// 33
// 33.45
// 33.45


问:
Change class of a element when clicking on a button
To be more specific, i have an div which has an icon in it. I want it to be so when you click on the div the class in a nav changes but i'm new to javascript so i dont know how to set the javascript to however it might work. And internet got me too confused and all of the answers were for changing the class in the same div/element.

Here's my html code:

```<code><div class="nav-container">
            <nav id="navdrop" class="top-bar">

!-- Code in between --!

    <div id="mobileNav" class="mobile-toggle">
      <i class="icon icon_menu"></i>
    </div>
</code>```

Here's my Javascript:

```<code>document.getElementById('mobileNav').onclick = function(){
    var className = '' + navdrop.className + '';
    if ( ~className.indexOf('open-nav') ) {
        this.className = className.replace(' open-nav', '');
    } else {
        this.className += ' open-nav';
    }
}
</code>```

答:
Use document.getElementById('navdrop') instead of just navdrop

document.getElementById('mobileNav').onclick = function(){
     var className = '' + document.getElementById('navdrop').className + '';
     if ( className.indexOf('open-nav') > -1 ) {
      document.getElementById('navdrop').className = className.replace('open-nav', ' ');
     } else {
      document.getElementById('navdrop').className += ' open-nav';
     }
    }```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.open-nav{
  color : red
}</code>```

Nav

    Test

```

Body:
To be more specific, i have an div which has an icon in it. I want it to be so when you click on the div the class in a nav changes but i'm new to javascript so i dont know how to set the javascript to however it might work. And internet got me too confused and all of the answers were for changing the class in the same div/element.

Here's my html code:

!-- Code in between --!

Here's my Javascript:

document.getElementById('mobileNav').onclick = function(){
    var className = '' + navdrop.className + '';
    if ( ~className.indexOf('open-nav') ) {
        this.className = className.replace(' open-nav', '');
    } else {
        this.className += ' open-nav';
    }
}

Body:
Use document.getElementById('navdrop') instead of just navdrop

document.getElementById('mobileNav').onclick = function(){
     var className = '' + document.getElementById('navdrop').className + '';
     if ( className.indexOf('open-nav') > -1 ) {
      document.getElementById('navdrop').className = className.replace('open-nav', ' ');
     } else {
      document.getElementById('navdrop').className += ' open-nav';
     }
    }

.open-nav{
  color : red
}

<div class="nav-container">
            <nav id="navdrop" class="top-bar">
Nav
</nav>

    <div id="mobileNav" class="mobile-toggle">
    Test
      <i class="icon icon_menu"></i>
    </div>


答:
Okay with some thinking about this, I've finally come up with the answer myself. Here it is if anybody would like to know how I've done it.

I was inspired by Erik Grosskurth post

$("p.right").click(function(){
  if ($(".item.active").next(".item").length){
   $(".item.active").removeClass("active").next(".item").addClass("active");
  } else {
   $(".item.active").removeClass("active");
   $(".item:first").addClass("active");
  }
 });

 $("p.left").click(function(){
  if ($(".item.active").prev(".item").length){
   $(".item.active").removeClass("active").prev(".item").addClass("active");
  } else {
   $(".item.active").removeClass("active");
   $(".item").last().addClass("active");
  }
 });```
<pre class="snippet-code-css lang-css prettyprint-override"><code>Section{
position: relative;
height: 200px;
width: 200px;
text-align: center;
}
p{
position: absolute;
margin: 0px;
padding: 5px 10px;
background: blue;
color: #ffffff;
border-radius: 100%;
}
p.left{
  top: 0px;
  left: 20px;
}
p.right{
  top: 0px;
  right: 20px;
}

div{
 display: none;
}
div.active{
 display: block;
}</code>```

First Item

Second Item

Third Item

Last Item

N

P

```

Body:
Okay with some thinking about this, I've finally come up with the answer myself. Here it is if anybody would like to know how I've done it.

I was inspired by Erik Grosskurth post

$("p.right").click(function(){
  if ($(".item.active").next(".item").length){
   $(".item.active").removeClass("active").next(".item").addClass("active");
  } else {
   $(".item.active").removeClass("active");
   $(".item:first").addClass("active");
  }
 });

 $("p.left").click(function(){
  if ($(".item.active").prev(".item").length){
   $(".item.active").removeClass("active").prev(".item").addClass("active");
  } else {
   $(".item.active").removeClass("active");
   $(".item").last().addClass("active");
  }
 });

Section{
position: relative;
height: 200px;
width: 200px;
text-align: center;
}
p{
position: absolute;
margin: 0px;
padding: 5px 10px;
background: blue;
color: #ffffff;
border-radius: 100%;
}
p.left{
  top: 0px;
  left: 20px;
}
p.right{
  top: 0px;
  right: 20px;
}

div{
 display: none;
}
div.active{
 display: block;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<section>
  <div class="item active">First Item</div>
  <div class="item">Second Item</div>
  <div class="item">Third Item</div>
  <div class="item">Last Item</div>
  <p class="right">N</p>
  <p class="left">P</p>
</section>


问:
blogdown::serve_site() throws 'html_dependency not found' error | htmlwidgets threejs
While trying to re-build an old .Rmd file, with (only) an updated header-info i.e. blog-categories, I'm getting this error:

Error: path for html_dependency not found: C:/Users/Username/Documents/R/win-library/3.4/threejs/htmlwidgets/lib/threejs-83

The same .Rmd file, prior to updating header-info now, generated html-content successfully months ago, with no issues. I think, the updated blogdown package isn't able to locate the dependency libraries i.e. three.js v83 vs three.js v85

If this is the issue, I'd really appreciate if someone could advise which file I need to update to fix this. Below snapshot shows the error message, and also the Windows file-location of required library.

答:
It turned out that you cached the code chunk that generated the HTML widget. When caching HTML widgets, you need to be careful about the versions of HTML dependencies. If you cache a widget, basically the next time it will not be created again but directly loaded from the cache database. It will not know any changes outside in the future, such as an update in a certain JS library. When it is loaded from cache, it will still use all paths stored from the last time. In your case, threejs-83 was changed to threejs-85, but your cached widget didn't know it, and was still looking for threejs-83 (hence the error).

In general, I don't recommend that you cache HTML widgets, due to the other caching mechanism in blogdown, which should make it fast enough to build a website locally, plus that caching HTML widgets can be tricky.


答:
I've got a partial solution to detect whether you are going past the last div (or before the first div) here:

https://jsfiddle.net/cewqotsv/1/

Essentially, you can detect whether there are any divs after the "active" one as such

```<code>if($("div.active").next("div").length == 0){
  //do nothing
}
</code>```

Body:
I've got a partial solution to detect whether you are going past the last div (or before the first div) here:

https://jsfiddle.net/cewqotsv/1/

Essentially, you can detect whether there are any divs after the "active" one as such

if($("div.active").next("div").length == 0){
  //do nothing
}


问:
Have a Laravel model have a relationship with 2 different models
My setup so far is a customer contact portal, and there is an Organization, Contact and Note models. A Contact belongs to an Organization, and an Organization has many Contacts. I have no problems with that, however I am having an issue trying to tie the Notes model to be able to have a relationship with both the Organization and Contact. Basically so I can leave a Note on an Organization but also leave another note on the Contact, and be able to search for Notes that belong to a given Contact or Organization.

I first thought of a pivot table that stored the ids of the models as well as the model type. Which I think is the same as a polymorphic pivot table? However I have not played with that yet, and not sure where to start.

Is the pivot table the way to do it? Or is there an easier way so I don't have additional tables all in my database?

答:
You can try to use Polymorphic Relations.

From the docs:

Table Structure

Polymorphic relations allow a model to belong to more than one other model on a single association. For example, imagine users of your application can "comment" both posts and videos. Using polymorphic relationships, you can use a single comments table for both of these scenarios. First, let's examine the table structure required to build this relationship:

```<code>posts
    id - integer
    title - string
    body - text

videos
    id - integer
    title - string
    url - string

comments
    id - integer
    body - text
    commentable_id - integer
    commentable_type - string
</code>```

Two important columns to note are the commentable_id and commentable_type columns on the  comments table. The commentable_id column will contain the ID value of the post or video, while the commentable_type column will contain the class name of the owning model. The  commentable_type column is how the ORM determines which "type" of owning model to return when accessing the commentable relation.

```<code><?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Comment extends Model
{
    /**
     * Get all of the owning commentable models.
     */
    public function commentable()
    {
        return $this->morphTo();
    }
}

class Post extends Model
{
    /**
     * Get all of the post's comments.
     */
    public function comments()
    {
        return $this->morphMany('App\Comment', 'commentable');
    }
}

class Video extends Model
{
    /**
     * Get all of the video's comments.
     */
    public function comments()
    {
        return $this->morphMany('App\Comment', 'commentable');
    }
}
</code>```

In your case, the "Comment" model corresponds with your "Note" model and the other ones (Video and Post) with your Organization and Contact models.

Give it a try.

In relationships, Laravel does not create the intermediate tables, you should add them using Migrations. Your Notes table should have, at least, the following fields:

- id: (or note_id) the key of the table.

- notable_id: Indicates the foreign key of Organization or Contact.

- notable_type: Indicates to what model the Note object is refering to. (so the previous field know in wich table should look to find the correct object).

- The rest of your Note fields like title or description ...

Body:
You can try to use Polymorphic Relations.

From the docs:

Table Structure

Polymorphic relations allow a model to belong to more than one other model on a single association. For example, imagine users of your application can "comment" both posts and videos. Using polymorphic relationships, you can use a single comments table for both of these scenarios. First, let's examine the table structure required to build this relationship:

posts
    id - integer
    title - string
    body - text

videos
    id - integer
    title - string
    url - string

comments
    id - integer
    body - text
    commentable_id - integer
    commentable_type - string

Two important columns to note are the commentable_id and commentable_type columns on the  comments table. The commentable_id column will contain the ID value of the post or video, while the commentable_type column will contain the class name of the owning model. The  commentable_type column is how the ORM determines which "type" of owning model to return when accessing the commentable relation.

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Comment extends Model
{
    /**
     * Get all of the owning commentable models.
     */
    public function commentable()
    {
        return $this->morphTo();
    }
}

class Post extends Model
{
    /**
     * Get all of the post's comments.
     */
    public function comments()
    {
        return $this->morphMany('App\Comment', 'commentable');
    }
}

class Video extends Model
{
    /**
     * Get all of the video's comments.
     */
    public function comments()
    {
        return $this->morphMany('App\Comment', 'commentable');
    }
}

In your case, the "Comment" model corresponds with your "Note" model and the other ones (Video and Post) with your Organization and Contact models.

Give it a try.

In relationships, Laravel does not create the intermediate tables, you should add them using Migrations. Your Notes table should have, at least, the following fields:

- id: (or note_id) the key of the table.

- notable_id: Indicates the foreign key of Organization or Contact.

- notable_type: Indicates to what model the Note object is refering to. (so the previous field know in wich table should look to find the correct object).

- The rest of your Note fields like title or description ...


问:
missing dependencies in latest spring security test
I need to resolve certain methods (status, jsonPath, content) mentioned in code shown below -

```<code>mockMvc.perform(MockMvcRequestBuilders.get("/api/token")
            .with(getAuthentication(getOauthTestAuthentication()))
            .sessionAttr("scopedTarget.oauth2ClientContext", getOauth2ClientContext()))
            .andExpect(status().isOk())
            .andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8))
            .andExpect(jsonPath("$.username").value("cominventor"))
            .andExpect(jsonPath("$.token").value("my-fun-token"));
</code>```

When I searched for related projects containing these methods, many of them are importing the following

```<code>import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
</code>```

The problem is that I am unable to find a counterpart in package spring-security-test with version 4.2.2.RELEASE

The closest options that could have worked but haven't are

```<code>import static org.springframework.test.web.servlet.ResultMatcher.*;
import static org.springframework.security.test.web.servlet.response.SecurityMockMvcResultMatchers.*;
</code>```

The above don't contain the methods I am looking for. Any idea where should I look for these methods or their newer counterparts.

答:
I had the same problem, and I solved it importing the artifact

```<code>org.springframework.security:spring-security-test:4.2.3.RELEASE
</code>```

I am using spring-boot-starter-test:1.5.3, and for some reason the folks at Spring decided not to include spring-security-test in its POM.

Body:
I need to resolve certain methods (status, jsonPath, content) mentioned in code shown below -

mockMvc.perform(MockMvcRequestBuilders.get("/api/token")
            .with(getAuthentication(getOauthTestAuthentication()))
            .sessionAttr("scopedTarget.oauth2ClientContext", getOauth2ClientContext()))
            .andExpect(status().isOk())
            .andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8))
            .andExpect(jsonPath("$.username").value("cominventor"))
            .andExpect(jsonPath("$.token").value("my-fun-token"));

When I searched for related projects containing these methods, many of them are importing the following

import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;

The problem is that I am unable to find a counterpart in package spring-security-test with version 4.2.2.RELEASE

The closest options that could have worked but haven't are

import static org.springframework.test.web.servlet.ResultMatcher.*;
import static org.springframework.security.test.web.servlet.response.SecurityMockMvcResultMatchers.*;

The above don't contain the methods I am looking for. Any idea where should I look for these methods or their newer counterparts.

Body:
I had the same problem, and I solved it importing the artifact

org.springframework.security:spring-security-test:4.2.3.RELEASE

I am using spring-boot-starter-test:1.5.3, and for some reason the folks at Spring decided not to include spring-security-test in its POM.


问:
How To Remove Multiple Spaces from String jQuery
I have an excel spreadsheet that has 3 columns.

```<code>    1st        |    2nd    |    3rd
----------------------------------------
  xxxxxxxx           x        xxxxxxxx
</code>```

When I copy all 3 of those cells and paste them into my textbox I get a value that looks likes this:

I need to eliminate the spaces, but what I have researched isn't working.

Here is what I have:

```<code>$(document).ready(function() {
    $("#MyTextBox").blur(function() {
        var myValue = $(this).val();
        alert(myValue);
        var test = myValue.replace(' ', '');
        alert(test);
        $("#MyTextBox").val(test);

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

When I alert test it looks the exact same as the original and the value for MyTextBox isn't being replaced.

I have a JSFiddle where I'm trying to replicate the issue, but in this instance, only the 1st space is replaced but the new value is populating into the textbox.

What am I doing wrong?

Any help is appreciated.

答:
I've changed your replace with a regex. This removes all the spaces

```<code>$("#MyTextBox").blur(function(){
    var myValue = $(this).val();
    alert(myValue);
    var test = myValue.replace(/\s/g, '');
    alert(test);
    $("#MyTextBox").val(test);
});
</code>```

Body:
I have an excel spreadsheet that has 3 columns.

    1st        |    2nd    |    3rd
----------------------------------------
  xxxxxxxx           x        xxxxxxxx

When I copy all 3 of those cells and paste them into my textbox I get a value that looks likes this:

I need to eliminate the spaces, but what I have researched isn't working.

Here is what I have:

$(document).ready(function() {
    $("#MyTextBox").blur(function() {
        var myValue = $(this).val();
        alert(myValue);
        var test = myValue.replace(' ', '');
        alert(test);
        $("#MyTextBox").val(test);

    });
});

When I alert test it looks the exact same as the original and the value for MyTextBox isn't being replaced.

I have a JSFiddle where I'm trying to replicate the issue, but in this instance, only the 1st space is replaced but the new value is populating into the textbox.

What am I doing wrong?

Any help is appreciated.

Body:
I've changed your replace with a regex. This removes all the spaces

$("#MyTextBox").blur(function(){
    var myValue = $(this).val();
    alert(myValue);
    var test = myValue.replace(/\s/g, '');
    alert(test);
    $("#MyTextBox").val(test);
});


问:
How to use Polymer lifecycle hooks
I have a component that contains video. My component is nested in a dom-if and can disappear. When this happens the video (and it sound) keep playing.

Is there a way in which my component can detect that is has  disappeared from the DOM? I have tried to use the 'detached' callback as described here: https://www.polymer-project.org/1.0/docs/devguide/registering-elements

```<code>Polymer({
  is: 'my-component-with-video',

  properties: {
     // some properties
  },

  detached: function() {
    console.log('Component detached');
    // more code to stop video
  },
</code>```

but when my element is removed by the dom-if nothing happens, I don't see the console.log message. What am I doing wrong?

答:
There are two scenarios possible here:

You want your element to be discarded and recreated fresh when the condition changes.

You want to keep it in the dom but freeze it.

In the first case you need to add the restamp attribute to the dom-if to make sure the template DOM is destroyed, not hidden. By default the dom-if stamps the template at first initialization and then hides it from the view if the condition becomes falsy.

In the second case, the suggestion given by Intervalia will not work, because the dom-if in "hide" mode does not detach anything from the DOM. Setting restamp attribute will make the detached callback run but then no point in pausing anything since the element will be discarded.
If you want to keep it in the DOM and freeze it's state you need to listen to dom-change event on the dom-if and run the .pause() accordingly.

Title: How to use Polymer lifecycle hooks

Body:
I have a component that contains video. My component is nested in a dom-if and can disappear. When this happens the video (and it sound) keep playing.

Is there a way in which my component can detect that is has  disappeared from the DOM? I have tried to use the 'detached' callback as described here: https://www.polymer-project.org/1.0/docs/devguide/registering-elements

Polymer({
  is: 'my-component-with-video',

  properties: {
     // some properties
  },

  detached: function() {
    console.log('Component detached');
    // more code to stop video
  },

but when my element is removed by the dom-if nothing happens, I don't see the console.log message. What am I doing wrong?


问:
Hanoi assembly code from tanenbaum computer architecture 6th book
I'm trying to run the code presented in tanenbaum computer architecture 6th book. I typed exactly the same code as the book. here is the code:

```<code>        .686
.MODEL FLAT
PUBLIC _towers
EXTERN _printf:NEAR
.CODE
_towers:
    push ebp
    mov ebp, esp
    cmp [ebp + 8], 1
    jne L1
    mov eax, [ebp + 16]
    push eax
    mov eax, [ebp + 12]
    push eax
    push OFFSET FLAT:format
    call _printf
    add esp, 12
    jmp Done
    mov eax, 6
    jmp Done
L1:
    mov eax, 6
    sub eax, [ebp + 12]
    sub eax, [ebp + 16]
    mov [ebp + 20], eax
    push eax
    mov eax, [ebp + 12]
    push eax
    mov eax, [ebp + 8]
    dec eax
    push eax
    call _towers
    add esp, 12
    mov eax, [ebp + 16]
    push eax
    mov eax, [ebp + 12]
    push eax
    push 1
    call _towers
    add esp, 12
    call _towers
    add esp, 12
    mov eax, [ebp + 12]
    push eax
    mov eax, [ebp + 20]
    push eax
    mov eax, [ebp + 8]
    dec eax
    push eax
    call _towers
    add esp, 12
Done:
    leave
    ret 0
.data
    format db "Move disk from %d to %d\n"
END
</code>```

But it has some errors:

```<code>Hanoi.asm:2: error: attempt to define a local label before any non-local labels
Hanoi.asm:3: error: attempt to define a local label before any non-local labels
Hanoi.asm:3: error: parser: instruction expected
Hanoi.asm:4: error: parser: instruction expected
Hanoi.asm:5: error: no special symbol features supported here
Hanoi.asm:16: error: comma, colon, decorator or end of line expected after operand
</code>```

I'm totally new to this language. I'm using NASM as the assembler on x86_68 linux ubuntu like:

```<code>nasm -f elf64 -o Hanoi.o Hanoi.asm
</code>```

答:
nasm has slightly different syntax than whatever assembler this was created with, so the following changes must be made:

nasm doesn't need any of these directives, so remove them:

```<code>END
.686
.MODEL FLAT
</code>```

The first directive instructs the assembler to end assembling, this is done implicitly in nasm when the file ends, so the directive is not needed. .686 selects an instruction set, again unneeded in nasm. .MODEL FLAT selects the flat model, which is always the case in nasm (nasm doesn't support other models), so get rid of it too.

In nasm, PUBLIC is spelled GLOBAL, .CODE and .DATA are spelled section .text and section .data.  Furthermore, qualifiers such as NEAR or FAR are not needed as nasm doesn't know segmentation. The offset keyword needs to be removed, too. nasm distinguishes memory operands from immediates using brackets, an operand foo is always seen as an immediate regardless of type. To make it a memory operand, you need to write [foo].

The instruction

```<code> cmp [ebp + 8], 1
</code>```

lacks a size qualifier.  Fix this by adding DWORD:

```<code>cmp dword [ebp + 8], 1
</code>```

Another thing you need to fix is the symbol decoration.  On Windows, C functions are decorated with a leading underscore.  This is not the case on Linux, so just remove all the underscores so your code links correctly.  As a result of this, you need to prepend . to all local symbols as without a leading underscore, they cannot be distinguished from external symbols.  The resulting program looks like this:

```<code>    global towers
    extern printf

    section .text

towers:
    push ebp
    mov ebp, esp
    cmp dword [ebp + 8], 1
    jne .L1
    mov eax, [ebp + 16]
    push eax
    mov eax, [ebp + 12]
    push eax
    push .format
    call printf
    add esp, 12
    jmp .Done
    mov eax, 6
    jmp .Done
.L1:
    mov eax, 6
    sub eax, [ebp + 12]
    sub eax, [ebp + 16]
    mov [ebp + 20], eax
    push eax
    mov eax, [ebp + 12]
    push eax
    mov eax, [ebp + 8]
    dec eax
    push eax
    call towers
    add esp, 12
    mov eax, [ebp + 16]
    push eax
    mov eax, [ebp + 12]
    push eax
    push 1
    call towers
    add esp, 12
    call towers
    add esp, 12
    mov eax, [ebp + 12]
    push eax
    mov eax, [ebp + 20]
    push eax
    mov eax, [ebp + 8]
    dec eax
    push eax
    call towers
    add esp, 12
.Done:
    leave
    ret 0

    section .data

.format db "Move disk from %d to %d\n"
</code>```

and assembles with

```<code>nasm -f elf Hanoi.asm
</code>```

Note that because this is clearly meant to be 32 bit code, -f elf instead of -f elf64 is needed.

Body:
I'm trying to run the code presented in tanenbaum computer architecture 6th book. I typed exactly the same code as the book. here is the code:

        .686
.MODEL FLAT
PUBLIC _towers
EXTERN _printf:NEAR
.CODE
_towers:
    push ebp
    mov ebp, esp
    cmp [ebp + 8], 1
    jne L1
    mov eax, [ebp + 16]
    push eax
    mov eax, [ebp + 12]
    push eax
    push OFFSET FLAT:format
    call _printf
    add esp, 12
    jmp Done
    mov eax, 6
    jmp Done
L1:
    mov eax, 6
    sub eax, [ebp + 12]
    sub eax, [ebp + 16]
    mov [ebp + 20], eax
    push eax
    mov eax, [ebp + 12]
    push eax
    mov eax, [ebp + 8]
    dec eax
    push eax
    call _towers
    add esp, 12
    mov eax, [ebp + 16]
    push eax
    mov eax, [ebp + 12]
    push eax
    push 1
    call _towers
    add esp, 12
    call _towers
    add esp, 12
    mov eax, [ebp + 12]
    push eax
    mov eax, [ebp + 20]
    push eax
    mov eax, [ebp + 8]
    dec eax
    push eax
    call _towers
    add esp, 12
Done:
    leave
    ret 0
.data
    format db "Move disk from %d to %d\n"
END

But it has some errors:

Hanoi.asm:2: error: attempt to define a local label before any non-local labels
Hanoi.asm:3: error: attempt to define a local label before any non-local labels
Hanoi.asm:3: error: parser: instruction expected
Hanoi.asm:4: error: parser: instruction expected
Hanoi.asm:5: error: no special symbol features supported here
Hanoi.asm:16: error: comma, colon, decorator or end of line expected after operand

I'm totally new to this language. I'm using NASM as the assembler on x86_68 linux ubuntu like:

nasm -f elf64 -o Hanoi.o Hanoi.asm

Body:
nasm has slightly different syntax than whatever assembler this was created with, so the following changes must be made:

nasm doesn't need any of these directives, so remove them:

END
.686
.MODEL FLAT

The first directive instructs the assembler to end assembling, this is done implicitly in nasm when the file ends, so the directive is not needed. .686 selects an instruction set, again unneeded in nasm. .MODEL FLAT selects the flat model, which is always the case in nasm (nasm doesn't support other models), so get rid of it too.

In nasm, PUBLIC is spelled GLOBAL, .CODE and .DATA are spelled section .text and section .data.  Furthermore, qualifiers such as NEAR or FAR are not needed as nasm doesn't know segmentation. The offset keyword needs to be removed, too. nasm distinguishes memory operands from immediates using brackets, an operand foo is always seen as an immediate regardless of type. To make it a memory operand, you need to write [foo].

The instruction

 cmp [ebp + 8], 1

lacks a size qualifier.  Fix this by adding DWORD:

cmp dword [ebp + 8], 1

Another thing you need to fix is the symbol decoration.  On Windows, C functions are decorated with a leading underscore.  This is not the case on Linux, so just remove all the underscores so your code links correctly.  As a result of this, you need to prepend . to all local symbols as without a leading underscore, they cannot be distinguished from external symbols.  The resulting program looks like this:

    global towers
    extern printf

    section .text

towers:
    push ebp
    mov ebp, esp
    cmp dword [ebp + 8], 1
    jne .L1
    mov eax, [ebp + 16]
    push eax
    mov eax, [ebp + 12]
    push eax
    push .format
    call printf
    add esp, 12
    jmp .Done
    mov eax, 6
    jmp .Done
.L1:
    mov eax, 6
    sub eax, [ebp + 12]
    sub eax, [ebp + 16]
    mov [ebp + 20], eax
    push eax
    mov eax, [ebp + 12]
    push eax
    mov eax, [ebp + 8]
    dec eax
    push eax
    call towers
    add esp, 12
    mov eax, [ebp + 16]
    push eax
    mov eax, [ebp + 12]
    push eax
    push 1
    call towers
    add esp, 12
    call towers
    add esp, 12
    mov eax, [ebp + 12]
    push eax
    mov eax, [ebp + 20]
    push eax
    mov eax, [ebp + 8]
    dec eax
    push eax
    call towers
    add esp, 12
.Done:
    leave
    ret 0

    section .data

.format db "Move disk from %d to %d\n"

and assembles with

nasm -f elf Hanoi.asm

Note that because this is clearly meant to be 32 bit code, -f elf instead of -f elf64 is needed.