问:
How to get a list as JSON with Struts2
I'm searching for get a list as JSON page. I'm currently using Hibernate+Struts, I've added to my build path JSON Struts2 plugin.

I simply configured my struts.xml but I always obtain same ERRORS, how can I make login via JSON?

These are my classes:

```<code>    /////// Anagrafica.hbm.xml    ///////
    <?xml version="1.0" encoding="utf-8"?>
    <!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
    "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
    <hibernate-mapping>
        <class name="it.unirc.pjam.Anagrafica.Model.Anagrafica" table="ANAGRAFICA">
            <id name="ID_Anagrafica" type="java.lang.Integer">
                <column name="ID_Anagrafica" />
                <generator class="identity" />
            </id>
            <property name="Nome" type="string">
                <column name="Nome" not-null="true" />
            </property>
            <property name="Cognome" type="string">
                <column name="Cognome" not-null="true" />
            </property>
            <property name="Provincia" type="string">
                <column name="Provincia" not-null="true" />
            </property>
            <property name="Codice_fiscale" type="string">
                <column name="Codice_fiscale" not-null="true" />
            </property>
            <many-to-one name="ruolo" class="it.unirc.pjam.Ruolo.Model.Ruolo" lazy="false">
                <column name="ID_Tipo_Anagrafica" not-null="true" />
            </many-to-one>
            <one-to-one name="utenza" class="it.unirc.pjam.Utenza.Model.Utenza"
                cascade="save-update" property-ref="anagrafica" foreign-key="anagrafica">
            </one-to-one>

            <set name="scontrini" inverse="true" cascade="save-update" lazy="false" >
                <key column="ID_Anagrafica" not-null="false" unique="true" />
                <one-to-many class="it.unirc.pjam.Scontrino.Model.Scontrino" />
            </set>

            <one-to-one name="tessera" class="it.unirc.pjam.Tessera.Model.Tessera"
                cascade="save-update" property-ref="anagrafica" foreign-key="anagrafica">
            </one-to-one>
        </class>
    </hibernate-mapping>

/////// method of AnagraficaStruts.java    ///////
public String AnagraficheJSON(){
        Ruoli = ruoloDAO.getRuoli();
        anagrafiche = dao.getAnagrafiche();
        return "success";
    }

/////// action in struts.xml    ///////
        <!-- JSON -->
        <action name="listAnagrafiche1" method="listAnagrafiche"
            class="it.unirc.pjam.Action.AnagraficaStruts">
            <result type="json">
                <param name="ignoreHierarchy">false</param>
            </result>
        </action>
        <!-- FINE JSON -->
</code>```

EDIT: I succeeded to obtain JSON, but I have unwanted fields like Ruolo, Scontrino, Catalogo, etc, and I have a null object at start of JSON file. How can I fix?

```<code>{
  "ID_Anagrafica": 0,
  "anagrafica": {
    "ID_Anagrafica": 0,
    "ID_Tipo_Anagrafica": 0,
    "codice_fiscale": null,
    "cognome": null,
    "nome": null,
    "provincia": null,
    "ruolo": null,
    "scontrini": [

    ],
    "tessera": null,
    "utenza": null
  },
  "anagrafiche": [
    {
      "ID_Anagrafica": 4,
      "ID_Tipo_Anagrafica": 0,
      "codice_fiscale": "123123",
      "cognome": "prova",
      "nome": "manlio",
      "provincia": "r",
      "ruolo": {
        "anagrafiche": [
          null
        ],
        "descrizione": "Cassiere",
        "id": 2
      },
      "scontrini": [
        {
          "anagrafica": null,
          "data": null,
          "id": 7,
          "importoTotale": 1300.0,
          "iva": 22.0,
          "prodotti": [
            {
              "catalogo": [
                {
                  "descrizione": "mac",
                  "id": 5,
                  "prodotti": [
                    null
                  ]
                }
              ],
              "descrizione": "macbook air",
              "id": 7,
              "nPezziDisponbili": 1,
              "nPezziVenduti": 1,
              "prezzo": 800.0,
              "prezzoAcquistato": 10.0,
              "prezzoScontato": 10.0,
              "scontrini": null,
              "tipo": "mac"
            },
            {
              "catalogo": [
                {
                  "descrizione": "notebook",
                  "id": 6,
                  "prodotti": [
                    null
                  ]
                }
              ],
              "descrizione": "asus",
              "id": 6,
              "nPezziDisponbili": 1,
              "nPezziVenduti": 1,
              "prezzo": 500.0,
              "prezzoAcquistato": 10.0,
              "prezzoScontato": 10.0,
              "scontrini": null,
              "tipo": "note"
            }
          ],
          "totalePezzi": 2
        },
        {
          "anagrafica": null,
          "data": null,
          "id": 3,
          "importoTotale": 6300.0,
          "iva": 22.0,
          "prodotti": [
            {
              "catalogo": [
                {
                  "descrizione": "mac",
                  "id": 5,
                  "prodotti": [
                    null
                  ]
                }
              ],
              "descrizione": "macbook air",
              "id": 7,
              "nPezziDisponbili": 1,
              "nPezziVenduti": 1,
              "prezzo": 800.0,
              "prezzoAcquistato": 10.0,
              "prezzoScontato": 10.0,
              "scontrini": null,
              "tipo": "mac"
            },
            {
              "catalogo": [
                {
                  "descrizione": "notebook",
                  "id": 6,
                  "prodotti": [
                    null
                  ]
                }
              ],
              "descrizione": "asus",
              "id": 6,
              "nPezziDisponbili": 1,
              "nPezziVenduti": 1,
              "prezzo": 500.0,
              "prezzoAcquistato": 10.0,
              "prezzoScontato": 10.0,
              "scontrini": null,
              "tipo": "note"
            },
            {
              "catalogo": [

              ],
              "descrizione": "macbook pro",
              "id": 8,
              "nPezziDisponbili": 1,
              "nPezziVenduti": 1,
              "prezzo": 1000.0,
              "prezzoAcquistato": 500.0,
              "prezzoScontato": 200.0,
              "scontrini": [
                null
              ],
              "tipo": "mac"
            }
          ],
          "totalePezzi": 7
        },
        {
          "anagrafica": null,
          "data": null,
          "id": 4,
          "importoTotale": 45800.0,
          "iva": 22.0,
          "prodotti": [
            {
              "catalogo": [
                {
                  "descrizione": "mac",
                  "id": 5,
                  "prodotti": [
                    null
                  ]
                }
              ],
              "descrizione": "macbook air",
              "id": 7,
              "nPezziDisponbili": 1,
              "nPezziVenduti": 1,
              "prezzo": 800.0,
              "prezzoAcquistato": 10.0,
              "prezzoScontato": 10.0,
              "scontrini": null,
              "tipo": "mac"
            },
            {
              "catalogo": [
                {
                  "descrizione": "notebook",
                  "id": 6,
                  "prodotti": [
                    null
                  ]
                }
              ],
              "descrizione": "asus",
              "id": 6,
              "nPezziDisponbili": 1,
              "nPezziVenduti": 1,
              "prezzo": 500.0,
              "prezzoAcquistato": 10.0,
              "prezzoScontato": 10.0,
              "scontrini": null,
              "tipo": "note"
            }
          ],
          "totalePezzi": 91
        },
        {
          "anagrafica": null,
          "data": null,
          "id": 1,
          "importoTotale": 4900.0,
          "iva": 22.0,
          "prodotti": [
            {
              "catalogo": [
                {
                  "descrizione": "mac",
                  "id": 5,
                  "prodotti": [
                    null
                  ]
                }
              ],
              "descrizione": "macbook air",
              "id": 7,
              "nPezziDisponbili": 1,
              "nPezziVenduti": 1,
              "prezzo": 800.0,
              "prezzoAcquistato": 10.0,
              "prezzoScontato": 10.0,
              "scontrini": null,
              "tipo": "mac"
            },
            {
              "catalogo": [
                {
                  "descrizione": "notebook",
                  "id": 6,
                  "prodotti": [
                    null
                  ]
                }
              ],
              "descrizione": "asus",
              "id": 6,
              "nPezziDisponbili": 1,
              "nPezziVenduti": 1,
              "prezzo": 500.0,
              "prezzoAcquistato": 10.0,
              "prezzoScontato": 10.0,
              "scontrini": null,
              "tipo": "note"
            }
          ],
          "totalePezzi": 8
        },
        {
          "anagrafica": null,
          "data": null,
          "id": 2,
          "importoTotale": 1300.0,
          "iva": 22.0,
          "prodotti": [
            {
              "catalogo": [
                {
                  "descrizione": "mac",
                  "id": 5,
                  "prodotti": [
                    null
                  ]
                }
              ],
              "descrizione": "macbook air",
              "id": 7,
              "nPezziDisponbili": 1,
              "nPezziVenduti": 1,
              "prezzo": 800.0,
              "prezzoAcquistato": 10.0,
              "prezzoScontato": 10.0,
              "scontrini": null,
              "tipo": "mac"
            },
            {
              "catalogo": [
                {
                  "descrizione": "notebook",
                  "id": 6,
                  "prodotti": [
                    null
                  ]
                }
              ],
              "descrizione": "asus",
              "id": 6,
              "nPezziDisponbili": 1,
              "nPezziVenduti": 1,
              "prezzo": 500.0,
              "prezzoAcquistato": 10.0,
              "prezzoScontato": 10.0,
              "scontrini": null,
              "tipo": "note"
            }
          ],
          "totalePezzi": 2
        }
      ],
      "tessera": {
        "anagrafica": null,
        "id": 4,
        "n_tessera": 12,
        "punti": 5.0
      },
      "utenza": {
        "anagrafica": null,
        "password": "admin",
        "stato_Utenza": "attiva",
        "username": "admin"
      }
    },
    {
      "ID_Anagrafica": 5,
      "ID_Tipo_Anagrafica": 0,
      "codice_fiscale": "boh",
      "cognome": "fiore",
      "nome": "fiore",
      "provincia": "rm",
      "ruolo": {
        "anagrafiche": [
          null
        ],
        "descrizione": "Proprietario",
        "id": 1
      },
      "scontrini": [

      ],
      "tessera": {
        "anagrafica": null,
        "id": 5,
        "n_tessera": 200,
        "punti": 0.0
      },
      "utenza": {
        "anagrafica": null,
        "password": "fiore",
        "stato_Utenza": "disattiva",
        "username": "fiore"
      }
    }
  ],
  "codice_fiscale": null,
  "cognome": null,
  "idRuolo": 0,
  "nome": null,
  "provincia": null,
  "ruoli": [
    {
      "anagrafiche": [

      ],
      "descrizione": "CapoMastrogiulia Gioia",
      "id": 4
    },
    {
      "anagrafiche": [
        {
          "ID_Anagrafica": 4,
          "ID_Tipo_Anagrafica": 0,
          "codice_fiscale": "123123",
          "cognome": "prova",
          "nome": "manlio",
          "provincia": "r",
          "ruolo": null,
          "scontrini": [
            {
              "anagrafica": null,
              "data": null,
              "id": 2,
              "importoTotale": 1300.0,
              "iva": 22.0,
              "prodotti": [
                {
                  "catalogo": [
                    {
                      "descrizione": "notebook",
                      "id": 6,
                      "prodotti": [
                        null
                      ]
                    }
                  ],
                  "descrizione": "asus",
                  "id": 6,
                  "nPezziDisponbili": 1,
                  "nPezziVenduti": 1,
                  "prezzo": 500.0,
                  "prezzoAcquistato": 10.0,
                  "prezzoScontato": 10.0,
                  "scontrini": null,
                  "tipo": "note"
                },
                {
                  "catalogo": [
                    {
                      "descrizione": "mac",
                      "id": 5,
                      "prodotti": [
                        null
                      ]
                    }
                  ],
                  "descrizione": "macbook air",
                  "id": 7,
                  "nPezziDisponbili": 1,
                  "nPezziVenduti": 1,
                  "prezzo": 800.0,
                  "prezzoAcquistato": 10.0,
                  "prezzoScontato": 10.0,
                  "scontrini": null,
                  "tipo": "mac"
                }
              ],
              "totalePezzi": 2
            },
            {
              "anagrafica": null,
              "data": null,
              "id": 3,
              "importoTotale": 6300.0,
              "iva": 22.0,
              "prodotti": [
                {
                  "catalogo": [

                  ],
                  "descrizione": "macbook pro",
                  "id": 8,
                  "nPezziDisponbili": 1,
                  "nPezziVenduti": 1,
                  "prezzo": 1000.0,
                  "prezzoAcquistato": 500.0,
                  "prezzoScontato": 200.0,
                  "scontrini": [
                    null
                  ],
                  "tipo": "mac"
                },
                {
                  "catalogo": [
                    {
                      "descrizione": "notebook",
                      "id": 6,
                      "prodotti": [
                        null
                      ]
                    }
                  ],
                  "descrizione": "asus",
                  "id": 6,
                  "nPezziDisponbili": 1,
                  "nPezziVenduti": 1,
                  "prezzo": 500.0,
                  "prezzoAcquistato": 10.0,
                  "prezzoScontato": 10.0,
                  "scontrini": null,
                  "tipo": "note"
                },
                {
                  "catalogo": [
                    {
                      "descrizione": "mac",
                      "id": 5,
                      "prodotti": [
                        null
                      ]
                    }
                  ],
                  "descrizione": "macbook air",
                  "id": 7,
                  "nPezziDisponbili": 1,
                  "nPezziVenduti": 1,
                  "prezzo": 800.0,
                  "prezzoAcquistato": 10.0,
                  "prezzoScontato": 10.0,
                  "scontrini": null,
                  "tipo": "mac"
                }
              ],
              "totalePezzi": 7
            },
            {
              "anagrafica": null,
              "data": null,
              "id": 4,
              "importoTotale": 45800.0,
              "iva": 22.0,
              "prodotti": [
                {
                  "catalogo": [
                    {
                      "descrizione": "notebook",
                      "id": 6,
                      "prodotti": [
                        null
                      ]
                    }
                  ],
                  "descrizione": "asus",
                  "id": 6,
                  "nPezziDisponbili": 1,
                  "nPezziVenduti": 1,
                  "prezzo": 500.0,
                  "prezzoAcquistato": 10.0,
                  "prezzoScontato": 10.0,
                  "scontrini": null,
                  "tipo": "note"
                },
                {
                  "catalogo": [
                    {
                      "descrizione": "mac",
                      "id": 5,
                      "prodotti": [
                        null
                      ]
                    }
                  ],
                  "descrizione": "macbook air",
                  "id": 7,
                  "nPezziDisponbili": 1,
                  "nPezziVenduti": 1,
                  "prezzo": 800.0,
                  "prezzoAcquistato": 10.0,
                  "prezzoScontato": 10.0,
                  "scontrini": null,
                  "tipo": "mac"
                }
              ],
              "totalePezzi": 91
            },
            {
              "anagrafica": null,
              "data": null,
              "id": 1,
              "importoTotale": 4900.0,
              "iva": 22.0,
              "prodotti": [
                {
                  "catalogo": [
                    {
                      "descrizione": "notebook",
                      "id": 6,
                      "prodotti": [
                        null
                      ]
                    }
                  ],
                  "descrizione": "asus",
                  "id": 6,
                  "nPezziDisponbili": 1,
                  "nPezziVenduti": 1,
                  "prezzo": 500.0,
                  "prezzoAcquistato": 10.0,
                  "prezzoScontato": 10.0,
                  "scontrini": null,
                  "tipo": "note"
                },
                {
                  "catalogo": [
                    {
                      "descrizione": "mac",
                      "id": 5,
                      "prodotti": [
                        null
                      ]
                    }
                  ],
                  "descrizione": "macbook air",
                  "id": 7,
                  "nPezziDisponbili": 1,
                  "nPezziVenduti": 1,
                  "prezzo": 800.0,
                  "prezzoAcquistato": 10.0,
                  "prezzoScontato": 10.0,
                  "scontrini": null,
                  "tipo": "mac"
                }
              ],
              "totalePezzi": 8
            },
            {
              "anagrafica": null,
              "data": null,
              "id": 7,
              "importoTotale": 1300.0,
              "iva": 22.0,
              "prodotti": [
                {
                  "catalogo": [
                    {
                      "descrizione": "notebook",
                      "id": 6,
                      "prodotti": [
                        null
                      ]
                    }
                  ],
                  "descrizione": "asus",
                  "id": 6,
                  "nPezziDisponbili": 1,
                  "nPezziVenduti": 1,
                  "prezzo": 500.0,
                  "prezzoAcquistato": 10.0,
                  "prezzoScontato": 10.0,
                  "scontrini": null,
                  "tipo": "note"
                },
                {
                  "catalogo": [
                    {
                      "descrizione": "mac",
                      "id": 5,
                      "prodotti": [
                        null
                      ]
                    }
                  ],
                  "descrizione": "macbook air",
                  "id": 7,
                  "nPezziDisponbili": 1,
                  "nPezziVenduti": 1,
                  "prezzo": 800.0,
                  "prezzoAcquistato": 10.0,
                  "prezzoScontato": 10.0,
                  "scontrini": null,
                  "tipo": "mac"
                }
              ],
              "totalePezzi": 2
            }
          ],
          "tessera": {
            "anagrafica": null,
            "id": 4,
            "n_tessera": 12,
            "punti": 5.0
          },
          "utenza": {
            "anagrafica": null,
            "password": "admin",
            "stato_Utenza": "attiva",
            "username": "admin"
          }
        }
      ],
      "descrizione": "Cassiere",
      "id": 2
    },
    {
      "anagrafiche": [
        {
          "ID_Anagrafica": 5,
          "ID_Tipo_Anagrafica": 0,
          "codice_fiscale": "boh",
          "cognome": "fiore",
          "nome": "fiore",
          "provincia": "rm",
          "ruolo": null,
          "scontrini": [

          ],
          "tessera": {
            "anagrafica": null,
            "id": 5,
            "n_tessera": 200,
            "punti": 0.0
          },
          "utenza": {
            "anagrafica": null,
            "password": "fiore",
            "stato_Utenza": "disattiva",
            "username": "fiore"
          }
        }
      ],
      "descrizione": "Proprietario",
      "id": 1
    },
    {
      "anagrafiche": [

      ],
      "descrizione": "supervisore",
      "id": 3
    }
  ]
}
</code>```

答:
You should configure json result to include only properties that you want to return, not all properties needed for json result. By default JSON plugin uses the action bean as root object to serialize to JSON.

You should configure properties manually that you want to include/exclude from the result.

Java:

```<code>public List getAnagraficheList(){ return anagrafiche; }
</code>```

Xml:

<result type="json">
  <param name="includeProperties">

    ^anagraficheList\[\d+\]\.property1,
    ^anagraficheList\[\d+\]\.property2,
    ^anagrapfcheList\[\d+\]\.property3
  </param>
  <param name="excludeNullProperties">true</param>
</result>
```

Title: How to get a list as JSON with Struts2

Body:
I'm searching for get a list as JSON page. I'm currently using Hibernate+Struts, I've added to my build path JSON Struts2 plugin.

I simply configured my struts.xml but I always obtain same ERRORS, how can I make login via JSON?

These are my classes:

    /////// Anagrafica.hbm.xml    ///////
    <?xml version="1.0" encoding="utf-8"?>
    <!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
    "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
    <hibernate-mapping>
        <class name="it.unirc.pjam.Anagrafica.Model.Anagrafica" table="ANAGRAFICA">
            <id name="ID_Anagrafica" type="java.lang.Integer">
                <column name="ID_Anagrafica" />
                <generator class="identity" />
            </id>
            <property name="Nome" type="string">
                <column name="Nome" not-null="true" />
            </property>
            <property name="Cognome" type="string">
                <column name="Cognome" not-null="true" />
            </property>
            <property name="Provincia" type="string">
                <column name="Provincia" not-null="true" />
            </property>
            <property name="Codice_fiscale" type="string">
                <column name="Codice_fiscale" not-null="true" />
            </property>
            <many-to-one name="ruolo" class="it.unirc.pjam.Ruolo.Model.Ruolo" lazy="false">
                <column name="ID_Tipo_Anagrafica" not-null="true" />
            </many-to-one>
            <one-to-one name="utenza" class="it.unirc.pjam.Utenza.Model.Utenza"
                cascade="save-update" property-ref="anagrafica" foreign-key="anagrafica">
            </one-to-one>

            <set name="scontrini" inverse="true" cascade="save-update" lazy="false" >
                <key column="ID_Anagrafica" not-null="false" unique="true" />
                <one-to-many class="it.unirc.pjam.Scontrino.Model.Scontrino" />
            </set>

            <one-to-one name="tessera" class="it.unirc.pjam.Tessera.Model.Tessera"
                cascade="save-update" property-ref="anagrafica" foreign-key="anagrafica">
            </one-to-one>
        </class>
    </hibernate-mapping>

/////// method of AnagraficaStruts.java    ///////
public String AnagraficheJSON(){
        Ruoli = ruoloDAO.getRuoli();
        anagrafiche = dao.getAnagrafiche();
        return "success";
    }

/////// action in struts.xml    ///////

        <action name="listAnagrafiche1" method="listAnagrafiche"
            class="it.unirc.pjam.Action.AnagraficaStruts">
            <result type="json">
                <param name="ignoreHierarchy">false</param>
            </result>
        </action>

EDIT: I succeeded to obtain JSON, but I have unwanted fields like Ruolo, Scontrino, Catalogo, etc, and I have a null object at start of JSON file. How can I fix?

{
  "ID_Anagrafica": 0,
  "anagrafica": {
    "ID_Anagrafica": 0,
    "ID_Tipo_Anagrafica": 0,
    "codice_fiscale": null,
    "cognome": null,
    "nome": null,
    "provincia": null,
    "ruolo": null,
    "scontrini": [

    ],
    "tessera": null,
    "utenza": null
  },
  "anagrafiche": [
    {
      "ID_Anagrafica": 4,
      "ID_Tipo_Anagrafica": 0,
      "codice_fiscale": "123123",
      "cognome": "prova",
      "nome": "manlio",
      "provincia": "r",
      "ruolo": {
        "anagrafiche": [
          null
        ],
        "descrizione": "Cassiere",
        "id": 2
      },
      "scontrini": [
        {
          "anagrafica": null,
          "data": null,
          "id": 7,
          "importoTotale": 1300.0,
          "iva": 22.0,
          "prodotti": [
            {
              "catalogo": [
                {
                  "descrizione": "mac",
                  "id": 5,
                  "prodotti": [
                    null
                  ]
                }
              ],
              "descrizione": "macbook air",
              "id": 7,
              "nPezziDisponbili": 1,
              "nPezziVenduti": 1,
              "prezzo": 800.0,
              "prezzoAcquistato": 10.0,
              "prezzoScontato": 10.0,
              "scontrini": null,
              "tipo": "mac"
            },
            {
              "catalogo": [
                {
                  "descrizione": "notebook",
                  "id": 6,
                  "prodotti": [
                    null
                  ]
                }
              ],
              "descrizione": "asus",
              "id": 6,
              "nPezziDisponbili": 1,
              "nPezziVenduti": 1,
              "prezzo": 500.0,
              "prezzoAcquistato": 10.0,
              "prezzoScontato": 10.0,
              "scontrini": null,
              "tipo": "note"
            }
          ],
          "totalePezzi": 2
        },
        {
          "anagrafica": null,
          "data": null,
          "id": 3,
          "importoTotale": 6300.0,
          "iva": 22.0,
          "prodotti": [
            {
              "catalogo": [
                {
                  "descrizione": "mac",
                  "id": 5,
                  "prodotti": [
                    null
                  ]
                }
              ],
              "descrizione": "macbook air",
              "id": 7,
              "nPezziDisponbili": 1,
              "nPezziVenduti": 1,
              "prezzo": 800.0,
              "prezzoAcquistato": 10.0,
              "prezzoScontato": 10.0,
              "scontrini": null,
              "tipo": "mac"
            },
            {
              "catalogo": [
                {
                  "descrizione": "notebook",
                  "id": 6,
                  "prodotti": [
                    null
                  ]
                }
              ],
              "descrizione": "asus",
              "id": 6,
              "nPezziDisponbili": 1,
              "nPezziVenduti": 1,
              "prezzo": 500.0,
              "prezzoAcquistato": 10.0,
              "prezzoScontato": 10.0,
              "scontrini": null,
              "tipo": "note"
            },
            {
              "catalogo": [

              ],
              "descrizione": "macbook pro",
              "id": 8,
              "nPezziDisponbili": 1,
              "nPezziVenduti": 1,
              "prezzo": 1000.0,
              "prezzoAcquistato": 500.0,
              "prezzoScontato": 200.0,
              "scontrini": [
                null
              ],
              "tipo": "mac"
            }
          ],
          "totalePezzi": 7
        },
        {
          "anagrafica": null,
          "data": null,
          "id": 4,
          "importoTotale": 45800.0,
          "iva": 22.0,
          "prodotti": [
            {
              "catalogo": [
                {
                  "descrizione": "mac",
                  "id": 5,
                  "prodotti": [
                    null
                  ]
                }
              ],
              "descrizione": "macbook air",
              "id": 7,
              "nPezziDisponbili": 1,
              "nPezziVenduti": 1,
              "prezzo": 800.0,
              "prezzoAcquistato": 10.0,
              "prezzoScontato": 10.0,
              "scontrini": null,
              "tipo": "mac"
            },
            {
              "catalogo": [
                {
                  "descrizione": "notebook",
                  "id": 6,
                  "prodotti": [
                    null
                  ]
                }
              ],
              "descrizione": "asus",
              "id": 6,
              "nPezziDisponbili": 1,
              "nPezziVenduti": 1,
              "prezzo": 500.0,
              "prezzoAcquistato": 10.0,
              "prezzoScontato": 10.0,
              "scontrini": null,
              "tipo": "note"
            }
          ],
          "totalePezzi": 91
        },
        {
          "anagrafica": null,
          "data": null,
          "id": 1,
          "importoTotale": 4900.0,
          "iva": 22.0,
          "prodotti": [
            {
              "catalogo": [
                {
                  "descrizione": "mac",
                  "id": 5,
                  "prodotti": [
                    null
                  ]
                }
              ],
              "descrizione": "macbook air",
              "id": 7,
              "nPezziDisponbili": 1,
              "nPezziVenduti": 1,
              "prezzo": 800.0,
              "prezzoAcquistato": 10.0,
              "prezzoScontato": 10.0,
              "scontrini": null,
              "tipo": "mac"
            },
            {
              "catalogo": [
                {
                  "descrizione": "notebook",
                  "id": 6,
                  "prodotti": [
                    null
                  ]
                }
              ],
              "descrizione": "asus",
              "id": 6,
              "nPezziDisponbili": 1,
              "nPezziVenduti": 1,
              "prezzo": 500.0,
              "prezzoAcquistato": 10.0,
              "prezzoScontato": 10.0,
              "scontrini": null,
              "tipo": "note"
            }
          ],
          "totalePezzi": 8
        },
        {
          "anagrafica": null,
          "data": null,
          "id": 2,
          "importoTotale": 1300.0,
          "iva": 22.0,
          "prodotti": [
            {
              "catalogo": [
                {
                  "descrizione": "mac",
                  "id": 5,
                  "prodotti": [
                    null
                  ]
                }
              ],
              "descrizione": "macbook air",
              "id": 7,
              "nPezziDisponbili": 1,
              "nPezziVenduti": 1,
              "prezzo": 800.0,
              "prezzoAcquistato": 10.0,
              "prezzoScontato": 10.0,
              "scontrini": null,
              "tipo": "mac"
            },
            {
              "catalogo": [
                {
                  "descrizione": "notebook",
                  "id": 6,
                  "prodotti": [
                    null
                  ]
                }
              ],
              "descrizione": "asus",
              "id": 6,
              "nPezziDisponbili": 1,
              "nPezziVenduti": 1,
              "prezzo": 500.0,
              "prezzoAcquistato": 10.0,
              "prezzoScontato": 10.0,
              "scontrini": null,
              "tipo": "note"
            }
          ],
          "totalePezzi": 2
        }
      ],
      "tessera": {
        "anagrafica": null,
        "id": 4,
        "n_tessera": 12,
        "punti": 5.0
      },
      "utenza": {
        "anagrafica": null,
        "password": "admin",
        "stato_Utenza": "attiva",
        "username": "admin"
      }
    },
    {
      "ID_Anagrafica": 5,
      "ID_Tipo_Anagrafica": 0,
      "codice_fiscale": "boh",
      "cognome": "fiore",
      "nome": "fiore",
      "provincia": "rm",
      "ruolo": {
        "anagrafiche": [
          null
        ],
        "descrizione": "Proprietario",
        "id": 1
      },
      "scontrini": [

      ],
      "tessera": {
        "anagrafica": null,
        "id": 5,
        "n_tessera": 200,
        "punti": 0.0
      },
      "utenza": {
        "anagrafica": null,
        "password": "fiore",
        "stato_Utenza": "disattiva",
        "username": "fiore"
      }
    }
  ],
  "codice_fiscale": null,
  "cognome": null,
  "idRuolo": 0,
  "nome": null,
  "provincia": null,
  "ruoli": [
    {
      "anagrafiche": [

      ],
      "descrizione": "CapoMastrogiulia Gioia",
      "id": 4
    },
    {
      "anagrafiche": [
        {
          "ID_Anagrafica": 4,
          "ID_Tipo_Anagrafica": 0,
          "codice_fiscale": "123123",
          "cognome": "prova",
          "nome": "manlio",
          "provincia": "r",
          "ruolo": null,
          "scontrini": [
            {
              "anagrafica": null,
              "data": null,
              "id": 2,
              "importoTotale": 1300.0,
              "iva": 22.0,
              "prodotti": [
                {
                  "catalogo": [
                    {
                      "descrizione": "notebook",
                      "id": 6,
                      "prodotti": [
                        null
                      ]
                    }
                  ],
                  "descrizione": "asus",
                  "id": 6,
                  "nPezziDisponbili": 1,
                  "nPezziVenduti": 1,
                  "prezzo": 500.0,
                  "prezzoAcquistato": 10.0,
                  "prezzoScontato": 10.0,
                  "scontrini": null,
                  "tipo": "note"
                },
                {
                  "catalogo": [
                    {
                      "descrizione": "mac",
                      "id": 5,
                      "prodotti": [
                        null
                      ]
                    }
                  ],
                  "descrizione": "macbook air",
                  "id": 7,
                  "nPezziDisponbili": 1,
                  "nPezziVenduti": 1,
                  "prezzo": 800.0,
                  "prezzoAcquistato": 10.0,
                  "prezzoScontato": 10.0,
                  "scontrini": null,
                  "tipo": "mac"
                }
              ],
              "totalePezzi": 2
            },
            {
              "anagrafica": null,
              "data": null,
              "id": 3,
              "importoTotale": 6300.0,
              "iva": 22.0,
              "prodotti": [
                {
                  "catalogo": [

                  ],
                  "descrizione": "macbook pro",
                  "id": 8,
                  "nPezziDisponbili": 1,
                  "nPezziVenduti": 1,
                  "prezzo": 1000.0,
                  "prezzoAcquistato": 500.0,
                  "prezzoScontato": 200.0,
                  "scontrini": [
                    null
                  ],
                  "tipo": "mac"
                },
                {
                  "catalogo": [
                    {
                      "descrizione": "notebook",
                      "id": 6,
                      "prodotti": [
                        null
                      ]
                    }
                  ],
                  "descrizione": "asus",
                  "id": 6,
                  "nPezziDisponbili": 1,
                  "nPezziVenduti": 1,
                  "prezzo": 500.0,
                  "prezzoAcquistato": 10.0,
                  "prezzoScontato": 10.0,
                  "scontrini": null,
                  "tipo": "note"
                },
                {
                  "catalogo": [
                    {
                      "descrizione": "mac",
                      "id": 5,
                      "prodotti": [
                        null
                      ]
                    }
                  ],
                  "descrizione": "macbook air",
                  "id": 7,
                  "nPezziDisponbili": 1,
                  "nPezziVenduti": 1,
                  "prezzo": 800.0,
                  "prezzoAcquistato": 10.0,
                  "prezzoScontato": 10.0,
                  "scontrini": null,
                  "tipo": "mac"
                }
              ],
              "totalePezzi": 7
            },
            {
              "anagrafica": null,
              "data": null,
              "id": 4,
              "importoTotale": 45800.0,
              "iva": 22.0,
              "prodotti": [
                {
                  "catalogo": [
                    {
                      "descrizione": "notebook",
                      "id": 6,
                      "prodotti": [
                        null
                      ]
                    }
                  ],
                  "descrizione": "asus",
                  "id": 6,
                  "nPezziDisponbili": 1,
                  "nPezziVenduti": 1,
                  "prezzo": 500.0,
                  "prezzoAcquistato": 10.0,
                  "prezzoScontato": 10.0,
                  "scontrini": null,
                  "tipo": "note"
                },
                {
                  "catalogo": [
                    {
                      "descrizione": "mac",
                      "id": 5,
                      "prodotti": [
                        null
                      ]
                    }
                  ],
                  "descrizione": "macbook air",
                  "id": 7,
                  "nPezziDisponbili": 1,
                  "nPezziVenduti": 1,
                  "prezzo": 800.0,
                  "prezzoAcquistato": 10.0,
                  "prezzoScontato": 10.0,
                  "scontrini": null,
                  "tipo": "mac"
                }
              ],
              "totalePezzi": 91
            },
            {
              "anagrafica": null,
              "data": null,
              "id": 1,
              "importoTotale": 4900.0,
              "iva": 22.0,
              "prodotti": [
                {
                  "catalogo": [
                    {
                      "descrizione": "notebook",
                      "id": 6,
                      "prodotti": [
                        null
                      ]
                    }
                  ],
                  "descrizione": "asus",
                  "id": 6,
                  "nPezziDisponbili": 1,
                  "nPezziVenduti": 1,
                  "prezzo": 500.0,
                  "prezzoAcquistato": 10.0,
                  "prezzoScontato": 10.0,
                  "scontrini": null,
                  "tipo": "note"
                },
                {
                  "catalogo": [
                    {
                      "descrizione": "mac",
                      "id": 5,
                      "prodotti": [
                        null
                      ]
                    }
                  ],
                  "descrizione": "macbook air",
                  "id": 7,
                  "nPezziDisponbili": 1,
                  "nPezziVenduti": 1,
                  "prezzo": 800.0,
                  "prezzoAcquistato": 10.0,
                  "prezzoScontato": 10.0,
                  "scontrini": null,
                  "tipo": "mac"
                }
              ],
              "totalePezzi": 8
            },
            {
              "anagrafica": null,
              "data": null,
              "id": 7,
              "importoTotale": 1300.0,
              "iva": 22.0,
              "prodotti": [
                {
                  "catalogo": [
                    {
                      "descrizione": "notebook",
                      "id": 6,
                      "prodotti": [
                        null
                      ]
                    }
                  ],
                  "descrizione": "asus",
                  "id": 6,
                  "nPezziDisponbili": 1,
                  "nPezziVenduti": 1,
                  "prezzo": 500.0,
                  "prezzoAcquistato": 10.0,
                  "prezzoScontato": 10.0,
                  "scontrini": null,
                  "tipo": "note"
                },
                {
                  "catalogo": [
                    {
                      "descrizione": "mac",
                      "id": 5,
                      "prodotti": [
                        null
                      ]
                    }
                  ],
                  "descrizione": "macbook air",
                  "id": 7,
                  "nPezziDisponbili": 1,
                  "nPezziVenduti": 1,
                  "prezzo": 800.0,
                  "prezzoAcquistato": 10.0,
                  "prezzoScontato": 10.0,
                  "scontrini": null,
                  "tipo": "mac"
                }
              ],
              "totalePezzi": 2
            }
          ],
          "tessera": {
            "anagrafica": null,
            "id": 4,
            "n_tessera": 12,
            "punti": 5.0
          },
          "utenza": {
            "anagrafica": null,
            "password": "admin",
            "stato_Utenza": "attiva",
            "username": "admin"
          }
        }
      ],
      "descrizione": "Cassiere",
      "id": 2
    },
    {
      "anagrafiche": [
        {
          "ID_Anagrafica": 5,
          "ID_Tipo_Anagrafica": 0,
          "codice_fiscale": "boh",
          "cognome": "fiore",
          "nome": "fiore",
          "provincia": "rm",
          "ruolo": null,
          "scontrini": [

          ],
          "tessera": {
            "anagrafica": null,
            "id": 5,
            "n_tessera": 200,
            "punti": 0.0
          },
          "utenza": {
            "anagrafica": null,
            "password": "fiore",
            "stato_Utenza": "disattiva",
            "username": "fiore"
          }
        }
      ],
      "descrizione": "Proprietario",
      "id": 1
    },
    {
      "anagrafiche": [

      ],
      "descrizione": "supervisore",
      "id": 3
    }
  ]
}

Body:
You should configure json result to include only properties that you want to return, not all properties needed for json result. By default JSON plugin uses the action bean as root object to serialize to JSON.

You should configure properties manually that you want to include/exclude from the result.

Java:

public List getAnagraficheList(){ return anagrafiche; }

Xml:

<!-- Result config -->
<result type="json">
  <param name="includeProperties">
    <!-- include only properties that aren't loaded lazy -->
    ^anagraficheList\[\d+\]\.property1,
    ^anagraficheList\[\d+\]\.property2,
    ^anagrapfcheList\[\d+\]\.property3
  </param>
  <param name="excludeNullProperties">true</param>
</result>


来源: stackexchange

问:
how to change the version of eclispe from 1.8 to 1.7?
I was change the current java machine to 1.8 and the eclipse work fine , Now i want to back to 1.7 so i do this steps :

down vote

In the START menu type "regedit" to open the Registry editor

Go to "HKEY_LOCAL_MACHINE" on the left-hand side registry explorer/tree menu

Click "SOFTWARE" within the "HKEY_LOCAL_MACHINE" registries

Click "JavaSoft" within the "SOFTWARE" registries

Click "Java Runtime Environment" within the "JavaSoft" list of registries here you can see different versions of installed java

Click "Java Runtime Environment"- On right hand side you will get 4-5 rows . Please select "CurrentVersion" and right Click( select modify option) Change version to "1.7"

now when I run the eclipse it did not run and show the error message :
Registry key 'Software\JavaSoft\Java Runtime Environment\CurrentVersion'
has value '1.7', but '1.8' is required.
Error: could not find java.dll
Error: could not find Java SE Runtime Environment.

so what I can do ?

答:
Recent versions of Eclipse (Neon and Oxygen) must be run using Java 8.

Programs you run from within Eclipse can use any Java you have installed.

First you must tell Eclipse about each Java you have installed. Do this in the Preferences in 'Java > Installed JREs'.

You can then set the Java used for a particular project in the Properties for the project. In the 'Java Build Path' property page on the 'Libraries' tab change the 'JRE System Library' entry to the Java you want to use.

You can also choose the Java used when running the program in the 'Run > Run Configurations' dialog by setting the JRE on the Main tab in the entry for your program.

ContentLicense: CC BY-SA 3.0


问:
Why does SQL Management Studio add a cross join?
I sometimes need to run basic updates on a join. For example:

```<code>UPDATE t1 SET col1 = 'val1'
FROM table1 as t1
INNER JOIN table2 as t2
ON t1.ID = t2.t1_id
WHERE t2.col3 = 'val3'
</code>```

This works perfectly, but for some reason, in MS SQL Management Studio Express, it wants to convert this to

```<code>UPDATE t1 SET col1 = 'val1'
FROM table1 as t1
INNER JOIN table2 as t2
ON t1.ID = t2.t1_id
CROSS JOIN t2
WHERE t2.col3 = 'val3'
</code>```

It adds a crossjoin for some reason that I don't understand.

Now my question is: Why does Management Studio think this is what I meant? It must have a genuine use, otherwise it wouldn't suggest it. Yet I have no idea how and when (and why).

答:
It must be a bug, because your fist code is rigth.

Try

Update t1 set col1 = 'val1'
from table1 t1, table2 t2
where t1.id = t2.t1_id and t2.col3='val3'

It throws the same result, but it could be less efficient.
Does your SQL-MS add any code?
Strange...

Body:
I sometimes need to run basic updates on a join. For example:

UPDATE t1 SET col1 = 'val1'
FROM table1 as t1
INNER JOIN table2 as t2
ON t1.ID = t2.t1_id
WHERE t2.col3 = 'val3'

This works perfectly, but for some reason, in MS SQL Management Studio Express, it wants to convert this to

UPDATE t1 SET col1 = 'val1'
FROM table1 as t1
INNER JOIN table2 as t2
ON t1.ID = t2.t1_id
CROSS JOIN t2
WHERE t2.col3 = 'val3'

It adds a crossjoin for some reason that I don't understand.

Now my question is: Why does Management Studio think this is what I meant? It must have a genuine use, otherwise it wouldn't suggest it. Yet I have no idea how and when (and why).

ContentLicense: CC BY-SA 2.5


问:
qt 5.8 sql connection error:QMYSQL driver not loaded on windows 10
When i tried to connect to mysql, there is a error:

```<code>QSqlDatabase: QMYSQL driver not loaded
QSqlDatabase: available drivers: QSQLITE QMYSQL QMYSQL3 QODBC QODBC3 QPSQL QPSQL7
"Driver not loaded Driver not loaded"
</code>```

So i googled it, and i tried :

1.Copy sqldrivers folders to C:\Qt\Qt5.8.0\5.8\mingw53_32\plugins

2.Copy libmysql.dll to C:\Qt\Qt5.8.0\5.8\mingw53_32\bin

but the error is still there.

Is there anything i am missing?

答:
You must rebuild mysql driver.

Follow this guide

Note: you need 3 things:

a. qt-opensource-xxx-mingw492-xxx.exe for Qt Creator and Qt command
    Prompt.

b.qt-everywhere-opensource-src-xxx.zip for Qt source code, needed for mysql.pro file.
c.mysql-connector-c-6.1.10-win32.zip needed for lib and include folder.

Body:
When i tried to connect to mysql, there is a error:

QSqlDatabase: QMYSQL driver not loaded
QSqlDatabase: available drivers: QSQLITE QMYSQL QMYSQL3 QODBC QODBC3 QPSQL QPSQL7
"Driver not loaded Driver not loaded"

So i googled it, and i tried :

1.Copy sqldrivers folders to C:\Qt\Qt5.8.0\5.8\mingw53_32\plugins

2.Copy libmysql.dll to C:\Qt\Qt5.8.0\5.8\mingw53_32\bin

but the error is still there.

Is there anything i am missing?


问:
for loop within a false If (Python)
Why is the following code go into the for loop on line 6 when i = 3? I was thinking of if the If on line 4 is false, it shouldn't go into the for loop. </p>

```<code>b = ['Lorem', 'Ipsum', 'is', 'lorem', 'dummy', 'impsum', 'is', 'the', 'printing', 'and', 'Industry', 'typesetting', 'industry.', 'Lorem', 'has', 'been']
count = 0
c = []
for i in range(len(b)):
    if b[i].lower() not in c:
        for j in range(len(b)):
            if b[i].lower() == b[j].lower():
                count += 1
        c.append(b[i].lower())
        print b[i], count
        count = 0
print c
</code>```

答:
It doesn't. I get the following output when I run your code.

```<code>Lorem 3
Ipsum 1
is 2
dummy 1
impsum 1
the 1
printing 1
and 1
Industry 1
typesetting 1
industry. 1
has 1
been 1
['lorem', 'ipsum', 'is', 'dummy', 'impsum', 'the', 'printing', 'and', 'industry', 'typesetting', 'industry.', 'has', 'been']
</code>```

You can see that it skipped printing "lorem" when i is 3.

Try printing i on the line print b[i], count if you're not convinced.

Title: for loop within a false If (Python)

Body:
Why is the following code go into the for loop on line 6 when i = 3? I was thinking of if the If on line 4 is false, it shouldn't go into the for loop.

b = ['Lorem', 'Ipsum', 'is', 'lorem', 'dummy', 'impsum', 'is', 'the', 'printing', 'and', 'Industry', 'typesetting', 'industry.', 'Lorem', 'has', 'been']
count = 0
c = []
for i in range(len(b)):
    if b[i].lower() not in c:
        for j in range(len(b)):
            if b[i].lower() == b[j].lower():
                count += 1
        c.append(b[i].lower())
        print b[i], count
        count = 0
print c

Body:
It doesn't. I get the following output when I run your code.

Lorem 3
Ipsum 1
is 2
dummy 1
impsum 1
the 1
printing 1
and 1
Industry 1
typesetting 1
industry. 1
has 1
been 1
['lorem', 'ipsum', 'is', 'dummy', 'impsum', 'the', 'printing', 'and', 'industry', 'typesetting', 'industry.', 'has', 'been']

You can see that it skipped printing "lorem" when i is 3.

Try printing i on the line print b[i], count if you're not convinced.


问:
Transferring a MySQL database from a shared host to a cloud provider
I am currently using a shared hosting provider for my database. It's about 15GB and would like to start to use something more robust (thinking of going with Digitalocean). Eventually I'll switch my site over as well, but for now I thought of just moving the database, then pointing my site (still on the shared hosting provider) to the new digital ocean server. After I believe things are good I'll eventually move the code over too.

I was reviewing this article here:
https://www.digitalocean.com/community/tutorials/how-to-migrate-a-mysql-database-between-two-servers

and the idea seems good but I was concerned about missing some data and the whole strategy. I think my db is big enough that in the time it takes to copy the db and set it up, I'll miss the new transactions that take place (probably about 300 records nothing too much)

Would the solution be:

Copy database over, and set it up to make sure it's working

Update my PHP code to point to the new database

Run a MySQL script on the old database to get any records whose creation date is greater than x (I still think i'll get duplicate records here) or maybe any records whose primary key is >= x and <= y (so I can get the few hundred records that were added inbetween db xfers)

Is there a better way to do this? Maybe I fork the data so it goes to two databases at the same time temporarily, and then I can work on safely getting legacy data into the new db and only when everything is equal do I cut over?

Any suggestions and help would be appreciated!

答:
The only way to keep both of them in sync, while the page is still running, would be a Master-Slave Setup, with the master being the old db until you switch your PHP-Code.

If you can't do that, you need to disable all write requests to your old db, while you are moving the data. Mysql can start in --read-only mode for that. You could of course just put up a maintenance page and block all access to the database.

Then get a fresh dump after the last write request, copy it over, and then point the PHP to the new DB. After that you can remove the maintenance mode.

You could use the approach you mention in 3., but that is risky. You would need to adjust auto-increment values, to make room for the missing entries.

Funny, just as I was about to edit this. SO got in read-only mode for a database transfer ;-)


问:
What is a channel exit in IBM websphere MQ?
What is a channel exit in IBM MQ? On my research I found three types of channel exits.

WMQSendExit

WMQReceiveExit

WMQSecurityExit

Can someone explain this?

答:
An "exit" or "exit program" in IBM-speak is the same thing that non-IBM software might call a "callback" or a "listener". It is a way to hook in your custom code into an event generated by the software.

https://www.ibm.com/support/knowledgecenter/en/SSFKSJ_7.1.0/com.ibm.mq.javadoc.doc/WMQJavaClasses/com/ibm/mq/exits/WMQSendExit.html

The send exit interface allows you to examine, and possibly alter, the
  data sent to the queue manager by the WebSphere MQ Client for Java.
  Note: This interface does not apply when connecting directly to
  WebSphere MQ in bindings mode.

To provide your own send exit, define a class that implements this
  interface.


问:
WPF Binding - StringFormat - Not Formatting
I have a ToolTip with a value set as:

```<code>Value="{Binding Path=DataItem.EquitySold, StringFormat=Reserved (Equity Share: \{0\}%)}"
</code>```

The toolip is displaying as:

72

But I expect it to be:

Reserved (Equity Share: 72%)

What is wrong with my binding?

答:
You don't need to escape the brackets. Try this (i like to put the format in single quotes): </p>

```<code>Value="{Binding Path=DataItem.EquitySold, StringFormat='Reserved (Equity Share: {0}%)'}"
</code>```

Body:
I have a ToolTip with a value set as:

Value="{Binding Path=DataItem.EquitySold, StringFormat=Reserved (Equity Share: \{0\}%)}"

The toolip is displaying as:

72

But I expect it to be:

Reserved (Equity Share: 72%)

What is wrong with my binding?

Body:
You don't need to escape the brackets. Try this (i like to put the format in single quotes):

Value="{Binding Path=DataItem.EquitySold, StringFormat='Reserved (Equity Share: {0}%)'}"


问:
Negative dimension size on MaxPool
I've implemented the following model with Keras. Underneath, I am using Tensorflow.

```<code>from keras.models import Sequential
from keras.layers import Conv2D, MaxPooling2D
from keras.layers import Activation, Dropout, Flatten, Dense

model = Sequential()
model.add(Conv2D(32, (2, 2), input_shape=(3, 150, 150), padding='SAME'))
model.add(Activation('relu'))
# model.add(MaxPooling2D(pool_size=(2, 2)))
model.add(MaxPooling2D(pool_size=(2, 2), data_format="channels_last"))

model.add(Conv2D(32, (2, 2), padding='SAME'))
model.add(Activation('relu'))
model.add(MaxPooling2D(pool_size=(2, 2)))

model.add(Conv2D(64, (2, 2), padding='SAME'))
model.add(Activation('relu'))
model.add(MaxPooling2D(pool_size=(2, 2)))
</code>```

However, I get this exception:

```<code>tensorflow.python.framework.errors_impl.InvalidArgumentError: Negative dimension size caused by subtracting 2 from 1 for 'max_pooling2d_2/MaxPool' (op: 'MaxPool') with input shapes: [?,1,75,32].
</code>```

I am using SAME padding, and a convolution of 2*2, so the output should be 2*2 and I should be able to run MaxPooling on it.

I just can't understand how the input can get to the shape [?,1,75,32].

答:
The problem is the input size of your first convolution.

You're using tensorflow and the "channels-last" layout.
Therefore, you need to specify the x and y resolution before the channels.

```<code>model.add(Conv2D(32, (2, 2), input_shape=(150, 150, 3), padding='SAME'))
</code>```

Your initial shape is [?, 3, 150, 150], pooling applies to the second and third item, that's how the shape [?, 1, 75, 32] was created.
The 32 is the number of filters in your convolution.

If you want to keep your filters along the first axis, Keras has a configuration file, under Linux this should be in /home/user/.keras/keras.json. In this configuration file you can change the channel layout, the option is called image_data_format. There you can switch between channels_first and channels_last.

Title: Negative dimension size on MaxPool

Body:
I've implemented the following model with Keras. Underneath, I am using Tensorflow.

from keras.models import Sequential
from keras.layers import Conv2D, MaxPooling2D
from keras.layers import Activation, Dropout, Flatten, Dense

model = Sequential()
model.add(Conv2D(32, (2, 2), input_shape=(3, 150, 150), padding='SAME'))
model.add(Activation('relu'))
# model.add(MaxPooling2D(pool_size=(2, 2)))
model.add(MaxPooling2D(pool_size=(2, 2), data_format="channels_last"))

model.add(Conv2D(32, (2, 2), padding='SAME'))
model.add(Activation('relu'))
model.add(MaxPooling2D(pool_size=(2, 2)))

model.add(Conv2D(64, (2, 2), padding='SAME'))
model.add(Activation('relu'))
model.add(MaxPooling2D(pool_size=(2, 2)))

However, I get this exception:

tensorflow.python.framework.errors_impl.InvalidArgumentError: Negative dimension size caused by subtracting 2 from 1 for 'max_pooling2d_2/MaxPool' (op: 'MaxPool') with input shapes: [?,1,75,32].

I am using SAME padding, and a convolution of 2*2, so the output should be 2*2 and I should be able to run MaxPooling on it.

I just can't understand how the input can get to the shape [?,1,75,32].

Body:
The problem is the input size of your first convolution.

You're using tensorflow and the "channels-last" layout.
Therefore, you need to specify the x and y resolution before the channels.

model.add(Conv2D(32, (2, 2), input_shape=(150, 150, 3), padding='SAME'))

Your initial shape is [?, 3, 150, 150], pooling applies to the second and third item, that's how the shape [?, 1, 75, 32] was created.
The 32 is the number of filters in your convolution.

If you want to keep your filters along the first axis, Keras has a configuration file, under Linux this should be in /home/user/.keras/keras.json. In this configuration file you can change the channel layout, the option is called image_data_format. There you can switch between channels_first and channels_last.


问:
How to drop first row using pandas?
I've searched at other questions related to dropping rows but could not find one that worked:

I have a CSV file exported from the tool screaming frog that looks like this:

Internal - HTML |               |             |
--------------- | --------------|-------------|
   Address      |   Content     | Status Code |
----------------|---------------|-------------|
www.example.com |   text/html   |   200       |
```

<p>I want to remove the first row that contains 'Internal - HTML'. When analyzing it with <code>df.keys()</code> I get this information" <code>Index(['Internal - HTML'], dtype='object')</code>.</p>

<p>I want to use the second row as the Index, which contains the correct column labels.</p>

<p>When I use the code:</p>

```a = pandas.read_csv("internal_html.csv", encoding="utf-8")
a.drop('Internal - HTML')
a.head(3)
```

<p>I get this error: <code>KeyError: 'Internal - HTML'</code></p>

<p>I also tried what was suggested here Remove index name in pandas and also tried resetting the index:</p>

```a = pandas.read_csv("internal_html.csv", encoding="utf-8")
a.reset_index(level=0, drop=True)
a.head(3)
```

None of the options above worked.

答:
You can add header as a parameter in the first call, to use column names and start of data :

```<code>a = pandas.read_csv("internal_html.csv", encoding="utf-8", header=1)
</code>```

Title: How to drop first row using pandas?

Body:
I've searched at other questions related to dropping rows but could not find one that worked:

I have a CSV file exported from the tool screaming frog that looks like this:

Internal - HTML |               |             |
--------------- | --------------|-------------|
   Address      |   Content     | Status Code |
----------------|---------------|-------------|
www.example.com |   text/html   |   200       |

I want to remove the first row that contains 'Internal - HTML'. When analyzing it with df.keys() I get this information" Index(['Internal - HTML'], dtype='object').

I want to use the second row as the Index, which contains the correct column labels.

When I use the code:

a = pandas.read_csv("internal_html.csv", encoding="utf-8")
a.drop('Internal - HTML')
a.head(3)

I get this error: KeyError: 'Internal - HTML'

I also tried what was suggested here Remove index name in pandas and also tried resetting the index:

a = pandas.read_csv("internal_html.csv", encoding="utf-8")
a.reset_index(level=0, drop=True)
a.head(3)

None of the options above worked.

Body:
You can add header as a parameter in the first call, to use column names and start of data :

a = pandas.read_csv("internal_html.csv", encoding="utf-8", header=1)


问:
Changing states with  instead of  using ui-router
I'm using AngularJs V1.6. Ui- Router V 1.0.3

I've been trying to learn how to work with ui-router for the past few eeks and I came upon this code today which has me totally confused :-

Html side -

```<code><ul ng-if="!isAuthenticated()" class="nav navbar-nav pull-right">
    <li><a href="/#/login">Login</a></li>
    <li><a href="/#/signup">Sign up</a></li>
</ul>
</code>```

JS -

```<code>$stateProvider
  .state('home', {
    url: '/',
    controller: 'HomeCtrl',
    templateUrl: 'partials/home.html'
  })
  .state('login', {
    url: '/login',
    templateUrl: 'partials/login.html',
    controller: 'LoginCtrl',
    resolve: {
      skipIfLoggedIn: skipIfLoggedIn
    }
  })
</code>```

This is code from Satellizer.

I tried replicating it but all it did was end up showing me the folder structure of my working directory in the browser.
However, I was using ui-router visualizer and upon clicking the route in that, it worked properly. I can't find any samples where ui-router is used this way, how exactly is this above snippet working?

I also read here that typing

```<code><a ui-sref="party">Go To Party</a>
</code>```

will turn it into

```<code><a href="/party" ui-sref="party">Go To Party</a>
</code>```

in our browser. However, in the example I posted intially, there is no ui-sref with the href. Once again, how exactly or what exactly is happening? Is it only working because it's retrieving a separate html file?

答:
When use you are write this routing sample

```<code><a href="/home">Home </a>
</code>```

You must be write this code in the routing

```<code> $locationProvider.html5Mode(true)
</code>```

This link can help you

Body:
I'm using AngularJs V1.6. Ui- Router V 1.0.3

I've been trying to learn how to work with ui-router for the past few eeks and I came upon this code today which has me totally confused :-

Html side -

Login

Sign up

JS -

$stateProvider
  .state('home', {
    url: '/',
    controller: 'HomeCtrl',
    templateUrl: 'partials/home.html'
  })
  .state('login', {
    url: '/login',
    templateUrl: 'partials/login.html',
    controller: 'LoginCtrl',
    resolve: {
      skipIfLoggedIn: skipIfLoggedIn
    }
  })

This is code from Satellizer.

I tried replicating it but all it did was end up showing me the folder structure of my working directory in the browser.
However, I was using ui-router visualizer and upon clicking the route in that, it worked properly. I can't find any samples where ui-router is used this way, how exactly is this above snippet working?

I also read here that typing

Go To Party

will turn it into

Go To Party

in our browser. However, in the example I posted intially, there is no ui-sref with the href. Once again, how exactly or what exactly is happening? Is it only working because it's retrieving a separate html file?

Body:
When use you are write this routing sample

<a href="/home">Home </a>

You must be write this code in the routing

 $locationProvider.html5Mode(true)

This link can help you


问:
Cocoa - detect event when camera started recording
In my OSX application I'm using code below to show preview from camera.

```<code>  [[self session] beginConfiguration];

  NSError *error = nil;
  AVCaptureDeviceInput *newVideoDeviceInput = [AVCaptureDeviceInput deviceInputWithDevice:captureDevice error:&error];

  if (captureDevice != nil) {
    [[self session] removeInput: [self videoDeviceInput]];
    if([[self session] canAddInput: newVideoDeviceInput]) {
      [[self session] addInput:newVideoDeviceInput];
      [self setVideoDeviceInput:newVideoDeviceInput];
    } else {
      DLog(@"WTF?");
    }
  }

  [[self session] commitConfiguration];
</code>```

Yet, I need to detect the exact time when the preview from the camera becomes available.

In other words I'm trying to detect the same moment like in Facetime under OSX, where animation starts once the camera provides the preview.

What is the best way to achieve this?

答:
The previous answer from the user jer is definitely the correct answer, but I just wanted to add one additional important information.

If a listener block is registered with CMIOObjectAddPropertyListenerBlock, the current run loop must be run, otherwise no event will be received and the listener block will never fire.

Body:
In my OSX application I'm using code below to show preview from camera.

  [[self session] beginConfiguration];

  NSError *error = nil;
  AVCaptureDeviceInput *newVideoDeviceInput = [AVCaptureDeviceInput deviceInputWithDevice:captureDevice error:&error];

  if (captureDevice != nil) {
    [[self session] removeInput: [self videoDeviceInput]];
    if([[self session] canAddInput: newVideoDeviceInput]) {
      [[self session] addInput:newVideoDeviceInput];
      [self setVideoDeviceInput:newVideoDeviceInput];
    } else {
      DLog(@"WTF?");
    }
  }

  [[self session] commitConfiguration];

Yet, I need to detect the exact time when the preview from the camera becomes available.

In other words I'm trying to detect the same moment like in Facetime under OSX, where animation starts once the camera provides the preview.

What is the best way to achieve this?


问:
Referencing a static class from an array?
I have a list of numbers, and each number that is the same should act exactly the same. So I have static classes for each number so that if I change the class, so do all of the numbers it references to.

The way the numbers are accessed is via a wrapper function, so that I'm not referencing the array directly, e.g.:

```<code>Map.GetBlock(x,y).AccessToStaticClassMembers;
</code>```

So, how would I go about this?

答:
I'm not really sure what you want. But it sounds like you're trying to ensure that there is only one instance in memory for each number. If that's the case, what's wrong with something like this:

```<code>static public class ObjectMapping
{
    static Dictionary<int, object> dictionary = new Dictionary<int, object>();

    static public object GetObjectForNumber(int x)
    {
        object o;
        if (!dictionary.ContainsKey(x))
        {
            o = CreateObjectForNumberTheFirstTime(x);
            dictionary.Add(x, o);
            return o;
        }
        return dictionary[x];
    }
}
</code>```

Of course, I left out things such as thread safety and creation of the objects in the first access, for you to do on your own.

Body:
I have a list of numbers, and each number that is the same should act exactly the same. So I have static classes for each number so that if I change the class, so do all of the numbers it references to.

The way the numbers are accessed is via a wrapper function, so that I'm not referencing the array directly, e.g.:

Map.GetBlock(x,y).AccessToStaticClassMembers;

So, how would I go about this?

Body:
I'm not really sure what you want. But it sounds like you're trying to ensure that there is only one instance in memory for each number. If that's the case, what's wrong with something like this:

static public class ObjectMapping
{
    static Dictionary<int, object> dictionary = new Dictionary<int, object>();

    static public object GetObjectForNumber(int x)
    {
        object o;
        if (!dictionary.ContainsKey(x))
        {
            o = CreateObjectForNumberTheFirstTime(x);
            dictionary.Add(x, o);
            return o;
        }
        return dictionary[x];
    }
}

Of course, I left out things such as thread safety and creation of the objects in the first access, for you to do on your own.


问:
How to make Node.js app under IIS on azure VM public?
I installed my Node.js app on Azure VM, and currently it's working under IIS.
Everything looks good but now I need to make it public, accessible by www.mysite.com

I've registered mysite.com domain but I don't know how to connect the VM, Node.js app and this domain name together?

(I remember I found some very useful article for asp.net mvc app, doing the same but unfortunately I can't find it anymore and I'm stuck).

Thanks

UPD:
1) Set up somehow that your app works on localhost:80

2) Firewall set up? (Not sure)

3) Set up the domain pointing to your VM at your provider (usually through CNAME)

Profit! (If you are masochist :)

答:
Go to your domain hoster's admin panel (be that GoDaddy, Namecheap, etc) and add an A record pointing to your VM:

$ dig example.com

www.example.com.   3600     IN   CNAME   example.com.
example.com.       3600     IN   A       PUBLIC.IP.ADDR.OF.YOUR.VM
```

Make sure you are using a reserved public IP address, thus making sure the IP address stays if you Stop Deallocate your VM.

If you'd rather not spin up and manage a VM with IIS (which is like buying a hotel chain just to take a shower), you may want to look into hosting your Node app on App Service.

The walkthrough uses azure-cli but you can do all that from the Portal UI as well if you're not comfortable with the CLI stuff.

You need to be aware of this gotcha in Azure App Service with Node: don't hardcode a port number to listen on, use process.env.PORT instead (which becomes a named pipe at runtime). See this answer for more.

You can use your own domain with App Service.

Body:
Go to your domain hoster's admin panel (be that GoDaddy, Namecheap, etc) and add an A record pointing to your VM:

$ dig example.com

www.example.com.   3600     IN   CNAME   example.com.
example.com.       3600     IN   A       PUBLIC.IP.ADDR.OF.YOUR.VM

Make sure you are using a reserved public IP address, thus making sure the IP address stays if you Stop Deallocate your VM.

If you'd rather not spin up and manage a VM with IIS (which is like buying a hotel chain just to take a shower), you may want to look into hosting your Node app on App Service.

The walkthrough uses azure-cli but you can do all that from the Portal UI as well if you're not comfortable with the CLI stuff.

You need to be aware of this gotcha in Azure App Service with Node: don't hardcode a port number to listen on, use process.env.PORT instead (which becomes a named pipe at runtime). See this answer for more.

You can use your own domain with App Service.


问:
web data having unequal length arrays python 3
Below is my code to scrape a website. i have to create a DataFrame with arrays of unequal length, for instance property_Type has varying length, soe listings have one property_type , some has two & some has three. Similarly , Agency name also has varying length.

```<code>import requests
from bs4 import BeautifulSoup
import pandas as pd
import numpy as np

urls = []

for i in range(1,3):
    pages = "http://www.realcommercial.com.au/for-sale/property-offices-retail-in-vic/list-{0}?includePropertiesWithin=includesurrounding&activeSort=list-date&autoSuggest=true".format(i)
    urls.append(pages)

Data = []

for info in urls:
    page = requests.get(info)
    soup = BeautifulSoup(page.content, 'html.parser')
    links = soup.find_all('a', attrs ={'class' :'details-panel'})
    hrefs = [link['href'] for link in links]

    for href in hrefs:
        pages = requests.get(href)
        soup_2 =BeautifulSoup(pages.content, 'html.parser')
        Address_1 = soup_2.find_all('p', attrs={'class' :'full-address'})
        Address = [Address.text.strip() for Address in Address_1]
        Prop_Type = soup_2.find_all('div', attrs={'class' :'propType ellipsis'})
        Property_Type = [Property_Type.text.strip() for Property_Type in Prop_Type]
        Agency_1=soup_2.find_all('div', attrs={'class' :'agencyName ellipsis'})
        Agency_Name=[Agency_Name.text.strip() for Agency_Name in Agency_1]
        Agent_1=soup_2.find_all('div', attrs={'class' :'agentName ellipsis'})
        Agent_Name=[Agent_Name.text.strip() for Agent_Name in Agent_1]
        raw_data = dict(A=np.array(Address),B=np.array(Property_Type),C=np.array(Agency_Name),D=np.array(Agent_Name))
        raw_df = pd.DataFrame(dict([ k,series(v) for k,v in raw_data.iteritems() ]))
</code>```

The error i am getting is

```<code>File "<ipython-input-8-3a7c5fc4fb93>", line 32
    raw_df = pd.DataFrame(dict([ k,series(v) for k,v in raw_data.iteritems() ]))
                                               ^
SyntaxError: invalid syntax
</code>```

What should i do to have a dataframe where only the relevant values fall under relevant columns, like property type should be in property type and not fall in agency name.

Any help would be highly appreciated,
Thanks !!!

答:
series appears to do nothing -- perhaps you mean to turn each v into a pandas Series with pd.Series. Also, the syntax inside dict([...]) appears to be way off. If you want to create key:value pairs where each value is a Series, and then to use the key:value pairs to create a DataFrame, you can do it with a dictionary comprehension, like so:

raw_df = pd.DataFrame.from_dict({k:pd.Series(v) for k,v in raw_data.iteritems()})

Body:
Below is my code to scrape a website. i have to create a DataFrame with arrays of unequal length, for instance property_Type has varying length, soe listings have one property_type , some has two & some has three. Similarly , Agency name also has varying length.

import requests
from bs4 import BeautifulSoup
import pandas as pd
import numpy as np

urls = []

for i in range(1,3):
    pages = "http://www.realcommercial.com.au/for-sale/property-offices-retail-in-vic/list-{0}?includePropertiesWithin=includesurrounding&activeSort=list-date&autoSuggest=true".format(i)
    urls.append(pages)

Data = []

for info in urls:
    page = requests.get(info)
    soup = BeautifulSoup(page.content, 'html.parser')
    links = soup.find_all('a', attrs ={'class' :'details-panel'})
    hrefs = [link['href'] for link in links]

    for href in hrefs:
        pages = requests.get(href)
        soup_2 =BeautifulSoup(pages.content, 'html.parser')
        Address_1 = soup_2.find_all('p', attrs={'class' :'full-address'})
        Address = [Address.text.strip() for Address in Address_1]
        Prop_Type = soup_2.find_all('div', attrs={'class' :'propType ellipsis'})
        Property_Type = [Property_Type.text.strip() for Property_Type in Prop_Type]
        Agency_1=soup_2.find_all('div', attrs={'class' :'agencyName ellipsis'})
        Agency_Name=[Agency_Name.text.strip() for Agency_Name in Agency_1]
        Agent_1=soup_2.find_all('div', attrs={'class' :'agentName ellipsis'})
        Agent_Name=[Agent_Name.text.strip() for Agent_Name in Agent_1]
        raw_data = dict(A=np.array(Address),B=np.array(Property_Type),C=np.array(Agency_Name),D=np.array(Agent_Name))
        raw_df = pd.DataFrame(dict([ k,series(v) for k,v in raw_data.iteritems() ]))

The error i am getting is

File "<ipython-input-8-3a7c5fc4fb93>", line 32
    raw_df = pd.DataFrame(dict([ k,series(v) for k,v in raw_data.iteritems() ]))
                                               ^
SyntaxError: invalid syntax

What should i do to have a dataframe where only the relevant values fall under relevant columns, like property type should be in property type and not fall in agency name.

Any help would be highly appreciated,
Thanks !!!


问:
Animated mask and hide circle on hover with css
I wanna make info box with this design.

This design is important to me. When mouse is over the circle, I need some animation and transform design to this...

jsFiddle Example :

.wrapper{
    width:400px;
    height:200px;
    background: white;
    position: relative;
}
.mask {
    width: 100%;
    height: 100%;
    background: green;
    background-size: cover;
    transition: 0.4s ease;
    clip-path: circle(80px at 50% 50%);
    position: relative;
}
.mask:hover {
    clip-path:  circle(100% at 50% 50%);
}
.wrapper:after {
    content: ' ';
    display: block;
    position: relative;
    width: 160px;
    height: 160px;
    top: calc(-50% - 83px);
    left: calc(50% - 83px);
    border-radius: 50%;
    background:transparent;
    border: 3px solid #fff;
    box-shadow: 0px 0px 6px #aaa;
    pointer-events: none;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="wrapper">
    <div id="map-canvas" class="mask">

    </div>
</div></code>```

But I don't know how to hide the circle.

Is there any solution how to make and hide that circle with border and shadow ?

答:
Try use transition and opacity for wrapper:after

You would want to transparent pseudo element after on hover and target it with .wrapper:hover:after.

.wrapper{
  width:400px;
  height:200px;
  background: white;
  position: relative;
}
.mask {
  width: 100%;
  height: 100%;
  background: green;
  background-size: cover;
  transition: 0.4s ease;
  clip-path: circle(80px at 50% 50%);
  position: relative;
}
.mask:hover {
  clip-path:  circle(100% at 50% 50%);
}
.wrapper:after {
  content: ' ';
  display: block;
  position: relative;
  width: 160px;
  height: 160px;
  top: calc(-50% - 83px);
  left: calc(50% - 83px);
  border-radius: 50%;
  background:transparent;
  border: 3px solid #fff;
  box-shadow: 0px 0px 6px #aaa;
  pointer-events: none;
  opacity:1;
  transition: all 0.5s forwards ;   /*added */
}
.wrapper:hover:after{
  opacity:0 ;                      /*added */
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="wrapper">
  <div id="map-canvas" class="mask">

  </div>
</div></code>```

also if you want some animation on hover out you can use bellow code:

.wrapper{
  width:400px;
  height:200px;
  background: white;
  position: relative;
}
.mask {
  width: 100%;
  height: 100%;
  background: green;
  background-size: cover;
  transition: 0.4s ease;
  clip-path: circle(80px at 50% 50%);
  position: relative;
}
.mask:hover {
  clip-path:  circle(100% at 50% 50%);
}
.wrapper:after {
  content: ' ';
  display: block;
  position: relative;
  width: 160px;
  height: 160px;
  top: calc(-50% - 83px);
  left: calc(50% - 83px);
  border-radius: 50%;
  background:transparent;
  border: 3px solid #fff;
  box-shadow: 0px 0px 6px #aaa;
  pointer-events: none;
  transition: all 0.5s ease-in ;

}
.wrapper:hover:after{
  opacity:0 ;
  transition: all 0.5s forwards ; /* added */
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="wrapper">
  <div id="map-canvas" class="mask">

  </div>
</div></code>```

Body:
I wanna make info box with this design.

This design is important to me. When mouse is over the circle, I need some animation and transform design to this...

jsFiddle Example :

.wrapper{
    width:400px;
    height:200px;
    background: white;
    position: relative;
}
.mask {
    width: 100%;
    height: 100%;
    background: green;
    background-size: cover;
    transition: 0.4s ease;
    clip-path: circle(80px at 50% 50%);
    position: relative;
}
.mask:hover {
    clip-path:  circle(100% at 50% 50%);
}
.wrapper:after {
    content: ' ';
    display: block;
    position: relative;
    width: 160px;
    height: 160px;
    top: calc(-50% - 83px);
    left: calc(50% - 83px);
    border-radius: 50%;
    background:transparent;
    border: 3px solid #fff;
    box-shadow: 0px 0px 6px #aaa;
    pointer-events: none;
}

But I don't know how to hide the circle.

Is there any solution how to make and hide that circle with border and shadow ?

Body:
Try use transition and opacity for wrapper:after

You would want to transparent pseudo element after on hover and target it with .wrapper:hover:after.

.wrapper{
  width:400px;
  height:200px;
  background: white;
  position: relative;
}
.mask {
  width: 100%;
  height: 100%;
  background: green;
  background-size: cover;
  transition: 0.4s ease;
  clip-path: circle(80px at 50% 50%);
  position: relative;
}
.mask:hover {
  clip-path:  circle(100% at 50% 50%);
}
.wrapper:after {
  content: ' ';
  display: block;
  position: relative;
  width: 160px;
  height: 160px;
  top: calc(-50% - 83px);
  left: calc(50% - 83px);
  border-radius: 50%;
  background:transparent;
  border: 3px solid #fff;
  box-shadow: 0px 0px 6px #aaa;
  pointer-events: none;
  opacity:1;
  transition: all 0.5s forwards ;   /*added */
}
.wrapper:hover:after{
  opacity:0 ;                      /*added */
}

<div class="wrapper">
  <div id="map-canvas" class="mask">

  </div>
</div>

also if you want some animation on hover out you can use bellow code:

.wrapper{
  width:400px;
  height:200px;
  background: white;
  position: relative;
}
.mask {
  width: 100%;
  height: 100%;
  background: green;
  background-size: cover;
  transition: 0.4s ease;
  clip-path: circle(80px at 50% 50%);
  position: relative;
}
.mask:hover {
  clip-path:  circle(100% at 50% 50%);
}
.wrapper:after {
  content: ' ';
  display: block;
  position: relative;
  width: 160px;
  height: 160px;
  top: calc(-50% - 83px);
  left: calc(50% - 83px);
  border-radius: 50%;
  background:transparent;
  border: 3px solid #fff;
  box-shadow: 0px 0px 6px #aaa;
  pointer-events: none;
  transition: all 0.5s ease-in ;

}
.wrapper:hover:after{
  opacity:0 ;
  transition: all 0.5s forwards ; /* added */
}

<div class="wrapper">
  <div id="map-canvas" class="mask">

  </div>
</div>

ContentLicense: CC BY-SA 4.0


问:
Shift the offset during eval (using sourcemap)
I'm loading a script from a file, and I'm using eval() to generate a Javascript code like this:

```<code>var code = fs.readFileSync('myfile');
var shiftedCode= 'function(param) {' + code + '}\n'+ '//# sourceURL=myfile';
eval(shiftedCode)
</code>```

The problem is when I put a breakpoint or debugger inside the code, it stops two lines after the correct one because of the added chars at the beginning I suppose.

Is there a way to shift the sourceURL to the correct start point may be using sourcemaps?

Thank you in advance for your help.

答:
Defining the problem

I see that you're trying to import Javascript code from one page to another and you're facing some problems (You defined one and I will define another one):

The sourcemaps/debugger problem:

First, I don't recommend building the sourcemap in the run time. Tools like Gulp, Grunt and Webpack are made to help you with those use cases and will let you focus on the business logic and keep you away from these kinds of problems.

Second Think about someone who will use this code in another page. Do you think that shifting the sourcemap would be fine? It would be the every time shift!

Possible solution: This lib also can help you with your use case. Generate new code first, then run it.

var offsetLines = require('offset-sourcemap-lines');
var conv = require('convert-source-map');
var fs = require('fs');
var code = fs.readFileSync('myfile');
var originalMap = conv.fromSource(code).toObject();
var codeBody = conv.removeComments(code);
var offsettedMap = offsetLines(originalMap, 1); // One line to be shifted
var newSourceMapComment = conv.fromObject(offsettedMap).toComment();
var shiftedCode= 'function(param) {\n' + codeBody + '}\n' + newSourceMapComment;
eval(shiftedCode)```
</div>
</div>
</p>

<ol start="2">
<li><strong>Be Careful! You're using the dangerous <code>eval()</code></strong>:

<ul>
<li>Using <code>eval()</code> can open a program up to several different injection attacks. The use of <code>eval()</code> in most contexts can be substituted for a better, alternative approach to a problem.</li>
<li>It results in slow code.</li>
<li>MDN: Don't use <code>eval()</code> needlessly!

<blockquote>
  <p><code>eval()</code> is a dangerous function, which executes the code it's passed with the privileges of the caller. If you run eval() with a string that could be affected by a malicious party, you may end up running malicious code on the user's machine with the permissions of your webpage/extension. More importantly, third-party code can see the scope in which <code>eval()</code> was invoked, which can lead to possible attacks in ways to which the similar Function is not susceptible.<br><br>
  <code>eval()</code> is also generally slower than the alternatives, since it has to invoke the JS interpreter, while many other constructs are optimized by modern JS engines.<br><br>
  There are safer (and faster!) alternatives to <code>eval()</code> for common use-cases.</p>
</blockquote></li>
</ul></li>
</ol>

<h2>Recommendations</h2>

<p>As we agreed, you're trying to import some code. So, why don't you just use one of the modularity systems for Javascript like AMD, RequireJS, CommonJS, ES6 module feature,...</p>

<p>Assume you'll use ES6 modules, it would be very straight forward. You will need to export <code>myfile</code> script as a module and import it anywhere and that's it</p>

```//  myfile.js
export function sum (x, y) { return x + y }

//  someApp.js
import {sum} from "myfile"
console.log(sum(10, 20));
```

Body:
I'm loading a script from a file, and I'm using eval() to generate a Javascript code like this:

var code = fs.readFileSync('myfile');
var shiftedCode= 'function(param) {' + code + '}\n'+ '//# sourceURL=myfile';
eval(shiftedCode)

The problem is when I put a breakpoint or debugger inside the code, it stops two lines after the correct one because of the added chars at the beginning I suppose.

Is there a way to shift the sourceURL to the correct start point may be using sourcemaps?

Thank you in advance for your help.

Body:
Defining the problem

I see that you're trying to import Javascript code from one page to another and you're facing some problems (You defined one and I will define another one):

The sourcemaps/debugger problem:

First, I don't recommend building the sourcemap in the run time. Tools like Gulp, Grunt and Webpack are made to help you with those use cases and will let you focus on the business logic and keep you away from these kinds of problems.

Second Think about someone who will use this code in another page. Do you think that shifting the sourcemap would be fine? It would be the every time shift!

Possible solution: This lib also can help you with your use case. Generate new code first, then run it.

var offsetLines = require('offset-sourcemap-lines');
var conv = require('convert-source-map');
var fs = require('fs');
var code = fs.readFileSync('myfile');
var originalMap = conv.fromSource(code).toObject();
var codeBody = conv.removeComments(code);
var offsettedMap = offsetLines(originalMap, 1); // One line to be shifted
var newSourceMapComment = conv.fromObject(offsettedMap).toComment();
var shiftedCode= 'function(param) {\n' + codeBody + '}\n' + newSourceMapComment;
eval(shiftedCode)

Be Careful! You're using the dangerous eval():

Using eval() can open a program up to several different injection attacks. The use of eval() in most contexts can be substituted for a better, alternative approach to a problem.

It results in slow code.

MDN: Don't use eval() needlessly!

eval() is a dangerous function, which executes the code it's passed with the privileges of the caller. If you run eval() with a string that could be affected by a malicious party, you may end up running malicious code on the user's machine with the permissions of your webpage/extension. More importantly, third-party code can see the scope in which eval() was invoked, which can lead to possible attacks in ways to which the similar Function is not susceptible.

  eval() is also generally slower than the alternatives, since it has to invoke the JS interpreter, while many other constructs are optimized by modern JS engines.

  There are safer (and faster!) alternatives to eval() for common use-cases.

Recommendations

As we agreed, you're trying to import some code. So, why don't you just use one of the modularity systems for Javascript like AMD, RequireJS, CommonJS, ES6 module feature,...

Assume you'll use ES6 modules, it would be very straight forward. You will need to export myfile script as a module and import it anywhere and that's it

//  myfile.js
export function sum (x, y) { return x + y }

//  someApp.js
import {sum} from "myfile"
console.log(sum(10, 20));


问:
Error can not convert Object to table
```<code>//POST api/values
[HttpPost]
[Route("api/post")]
public HttpResponseMessage Post([FromBody]classUser usuario)
{
    try
    {
        bool resultado = false;

        if (usuario == null) throw new ArgumentNullException("user can`t be null");

        classUser usr = new classUser();
        usr.ID = usuario.ID;
        usr.name = usuario.name;
        usr.email = usuario.email;
        usr.bio = usuario.bio;

        dc.tb_User.InsertOnSubmit(usr);
        dc.SubmitChanges();
        return Request.CreateResponse(HttpStatusCode.OK, resultado);
    }
    catch (Exception ex)
    {
        return Request.CreateResponse(HttpStatusCode.BadRequest, ex.Message);
    }
}
</code>```

I am developing an api rest, but I get the error message in that line

```<code>dc.tb_User.InsertOnSubmit (usr);
</code>```

Can not convert object to my table in SQL database, showing this compile error:

Error CS1503  Argument 1: cannot convert from 'api4food.Models.classUser' to 'api4food.tb_User'   api4food

答:
Your method InsertOnSubmit expects an instance of type tb_User, not of
 type classUser.

So your mapping should be like this:

```<code>// other code omitted
// assuming tb_User has the same shape as classUser
var usr = new tb_User
{
    ID = usuario.ID,
    name = usuario.name,
    email = usuario.email,
    bio = usuario.bio
};

dc.tb_User.InsertOnSubmit(usr);
</code>```

Or adapt the propertynames that exist on tb_User accordingly.

Title: Error can not convert Object to table

Body:
//POST api/values
[HttpPost]
[Route("api/post")]
public HttpResponseMessage Post([FromBody]classUser usuario)
{
    try
    {
        bool resultado = false;

        if (usuario == null) throw new ArgumentNullException("user can`t be null");

        classUser usr = new classUser();
        usr.ID = usuario.ID;
        usr.name = usuario.name;
        usr.email = usuario.email;
        usr.bio = usuario.bio;

        dc.tb_User.InsertOnSubmit(usr);
        dc.SubmitChanges();
        return Request.CreateResponse(HttpStatusCode.OK, resultado);
    }
    catch (Exception ex)
    {
        return Request.CreateResponse(HttpStatusCode.BadRequest, ex.Message);
    }
}

I am developing an api rest, but I get the error message in that line

dc.tb_User.InsertOnSubmit (usr);

Can not convert object to my table in SQL database, showing this compile error:

Error CS1503  Argument 1: cannot convert from 'api4food.Models.classUser' to 'api4food.tb_User'   api4food

Body:
Your method InsertOnSubmit expects an instance of type tb_User, not of
 type classUser.

So your mapping should be like this:

// other code omitted
// assuming tb_User has the same shape as classUser
var usr = new tb_User
{
    ID = usuario.ID,
    name = usuario.name,
    email = usuario.email,
    bio = usuario.bio
};

dc.tb_User.InsertOnSubmit(usr);

Or adapt the propertynames that exist on tb_User accordingly.


问:
Is there any way I can convert any MS Document to PDF using LibreOffice SDK in java?
I want to write the code which will take input as ms document and convert it into PDF. I want to use LibraOffice SDK for conversion, but not able to find the related things. Is it possible to do? If yes, can you give me some pointers?</p>

答:
LibreOffice has native PDF "save as" capability, and of course you can exploit this feature from SDK.
I use it in my ASP.NET VC#, with I post here. I guess java will not be very different.

Once you have worked on your xDocument (both Calc or Write) you save them as PDF in this way:

```<code>            XStorable xStorable = (XStorable)xDocument;
            PropertyValue[] storeProps = new PropertyValue[3];
            storeProps[0] = new PropertyValue();
            storeProps[0].Name = "FilterName";
            storeProps[0].Value = new uno.Any("writer_pdf_Export");
            storeProps[1] = new PropertyValue();
            storeProps[1].Name = "Overwrite";
            storeProps[1].Value = new uno.Any(true);
            storeProps[2] = new PropertyValue();
            storeProps[2].Name = "SelectPdfVersion";
            storeProps[2].Value = new uno.Any(1);

            xStorable.storeToURL("file:///" + outFile, storeProps);
            xDocument.dispose();
</code>```

Body:
LibreOffice has native PDF "save as" capability, and of course you can exploit this feature from SDK.
I use it in my ASP.NET VC#, with I post here. I guess java will not be very different.

Once you have worked on your xDocument (both Calc or Write) you save them as PDF in this way:

            XStorable xStorable = (XStorable)xDocument;
            PropertyValue[] storeProps = new PropertyValue[3];
            storeProps[0] = new PropertyValue();
            storeProps[0].Name = "FilterName";
            storeProps[0].Value = new uno.Any("writer_pdf_Export");
            storeProps[1] = new PropertyValue();
            storeProps[1].Name = "Overwrite";
            storeProps[1].Value = new uno.Any(true);
            storeProps[2] = new PropertyValue();
            storeProps[2].Name = "SelectPdfVersion";
            storeProps[2].Value = new uno.Any(1);

            xStorable.storeToURL("file:///" + outFile, storeProps);
            xDocument.dispose();


问:
How sort a collection of associative arrays in PHP by a specific attribute
I have this array. I want sort this, how I can do that?

```<code> array:2 [▼
      0 => Collection {#198 ▼
        #items: array:2 [▼

      0 => {#201 ▼

        +"id": 2;
        +"title": "Now eldest";
        +"description": "Now eldest new tastes plenty mother called misery get."
        +"created_at": "2017-07-07 16:34:00"
      }

      1 => {#197 ▼

        +"id": 6
        +"title": "dffd"
        +"description": "fdfdfdfdfdffdfdf"
        +"created_at": "2017-07-07 10:23:00"
      }]  }
      1 => Collection {#189 ▼
        #items: array:2 [▼

      0 => {#208 ▼

        +"id": 5
        +"title": "However, if you are not using Homestead"
        +"description": "The Laravel framework has a few system requirements."
        +"created_at": "2017-07-07 13:37:00"
      }

      1 => {#196 ▼

        +"id": 7
        +"title": "fedffdf"
        +"description": "fdfdfdf"
        +"created_at": "2017-07-07 09:12:00"
      }] }]
</code>```

I work of an application, I want to show in timeline all posts sorted by time 'created_at'.
How can I do that?

答:
Try usort:

```<code>usort($collection, function(array $a, array $b) {
    return $a["created_at"] <=> $b["created_at"];
});
</code>```

If you are using a version of PHP that does not have the <=> operator, try this instead:

```<code>usort($collection, function(array $a, array $b) {
    return $a["created_at"] >= $b["created_at"] ? 1 : -1;
});
</code>```

Link to the documentation: PHP: usort

Body:
I have this array. I want sort this, how I can do that?

 array:2 [▼
      0 => Collection {#198 ▼
        #items: array:2 [▼

      0 => {#201 ▼

        +"id": 2;
        +"title": "Now eldest";
        +"description": "Now eldest new tastes plenty mother called misery get."
        +"created_at": "2017-07-07 16:34:00"
      }

      1 => {#197 ▼

        +"id": 6
        +"title": "dffd"
        +"description": "fdfdfdfdfdffdfdf"
        +"created_at": "2017-07-07 10:23:00"
      }]  }
      1 => Collection {#189 ▼
        #items: array:2 [▼

      0 => {#208 ▼

        +"id": 5
        +"title": "However, if you are not using Homestead"
        +"description": "The Laravel framework has a few system requirements."
        +"created_at": "2017-07-07 13:37:00"
      }

      1 => {#196 ▼

        +"id": 7
        +"title": "fedffdf"
        +"description": "fdfdfdf"
        +"created_at": "2017-07-07 09:12:00"
      }] }]

I work of an application, I want to show in timeline all posts sorted by time 'created_at'.
How can I do that?

Body:
Try usort:

usort($collection, function(array $a, array $b) {
    return $a["created_at"] <=> $b["created_at"];
});

If you are using a version of PHP that does not have the <=> operator, try this instead:

usort($collection, function(array $a, array $b) {
    return $a["created_at"] >= $b["created_at"] ? 1 : -1;
});

Link to the documentation: PHP: usort