答:
If you are using gson library then try this

```<code>Gson gson = new Gson();
   List<Consultation> consultations= gson.fromJson(json, new TypeToken<List<Consultation>>(){}.getType());
    for (Consultation consultation: consultations) {
        Log.e("TEST","Consultation id : " + consultation.getConsulationId());
        Log.e("TEST","Patient id: " + consultation.getPatientid());
    }
</code>```

Consultation.java

```<code>import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;

public class Consultation{

@SerializedName("consultation_id")
@Expose
private Integer consultationId;
@SerializedName("plageconsult_id")
@Expose
private Integer plageconsultId;
@SerializedName("patient_id")
@Expose
private Integer patientId;
@SerializedName("heure")
@Expose
private String heure;
@SerializedName("duree")
@Expose
private Integer duree;
@SerializedName("motif")
@Expose
private Object motif;
@SerializedName("secteur1")
@Expose
private Integer secteur1;
@SerializedName("secteur2")
@Expose
private Integer secteur2;
@SerializedName("rques")
@Expose
private String rques;
@SerializedName("chrono")
@Expose
private String chrono;
@SerializedName("annule")
@Expose
private String annule;
@SerializedName("patient_date_reglement")
@Expose
private Object patientDateReglement;
@SerializedName("examen")
@Expose
private Object examen;
@SerializedName("traitement")
@Expose
private String traitement;
@SerializedName("histoire_maladie")
@Expose
private Object histoireMaladie;
@SerializedName("conclusion")
@Expose
private Object conclusion;
@SerializedName("premiere")
@Expose
private String premiere;
@SerializedName("derniere")
@Expose
private String derniere;
@SerializedName("tarif")
@Expose
private Object tarif;
@SerializedName("patient_mode_reglement")
@Expose
private Object patientModeReglement;
@SerializedName("arrivee")
@Expose
private String arrivee;
@SerializedName("codes_ccam")
@Expose
private Object codesCcam;
@SerializedName("banque_id")
@Expose
private Object banqueId;
@SerializedName("categorie_id")
@Expose
private Object categorieId;
@SerializedName("adresse")
@Expose
private String adresse;
@SerializedName("valide")
@Expose
private String valide;
@SerializedName("total_amc")
@Expose
private Object totalAmc;
@SerializedName("total_amo")
@Expose
private Object totalAmo;
@SerializedName("total_assure")
@Expose
private Object totalAssure;
@SerializedName("du_patient")
@Expose
private Integer duPatient;
@SerializedName("sejour_id")
@Expose
private Integer sejourId;
@SerializedName("du_tiers")
@Expose
private Integer duTiers;
@SerializedName("tiers_mode_reglement")
@Expose
private Object tiersModeReglement;
@SerializedName("tiers_date_reglement")
@Expose
private Object tiersDateReglement;
@SerializedName("date_at")
@Expose
private Object dateAt;
@SerializedName("concerne_ALD")
@Expose
private String concerneALD;
@SerializedName("facture")
@Expose
private String facture;
@SerializedName("adresse_par_prat_id")
@Expose
private Object adresseParPratId;
@SerializedName("si_desistement")
@Expose
private String siDesistement;
@SerializedName("fin_at")
@Expose
private Object finAt;
@SerializedName("pec_at")
@Expose
private Object pecAt;
@SerializedName("reprise_at")
@Expose
private Object repriseAt;
@SerializedName("type")
@Expose
private String type;
@SerializedName("grossesse_id")
@Expose
private Object grossesseId;
@SerializedName("at_sans_arret")
@Expose
private String atSansArret;
@SerializedName("arret_maladie")
@Expose
private String arretMaladie;
@SerializedName("factureconsult_id")
@Expose
private Object factureconsultId;
@SerializedName("brancardage")
@Expose
private Object brancardage;
@SerializedName("sianesthesique")
@Expose
private Integer sianesthesique;

public Integer getConsultationId() {
return consultationId;
}

public void setConsultationId(Integer consultationId) {
this.consultationId = consultationId;
}

public Integer getPlageconsultId() {
return plageconsultId;
}

public void setPlageconsultId(Integer plageconsultId) {
this.plageconsultId = plageconsultId;
}

public Integer getPatientId() {
return patientId;
}

public void setPatientId(Integer patientId) {
this.patientId = patientId;
}

public String getHeure() {
return heure;
}

public void setHeure(String heure) {
this.heure = heure;
}

public Integer getDuree() {
return duree;
}

public void setDuree(Integer duree) {
this.duree = duree;
}

public Object getMotif() {
return motif;
}

public void setMotif(Object motif) {
this.motif = motif;
}

public Integer getSecteur1() {
return secteur1;
}

public void setSecteur1(Integer secteur1) {
this.secteur1 = secteur1;
}

public Integer getSecteur2() {
return secteur2;
}

public void setSecteur2(Integer secteur2) {
this.secteur2 = secteur2;
}

public String getRques() {
return rques;
}

public void setRques(String rques) {
this.rques = rques;
}

public String getChrono() {
return chrono;
}

public void setChrono(String chrono) {
this.chrono = chrono;
}

public String getAnnule() {
return annule;
}

public void setAnnule(String annule) {
this.annule = annule;
}

public Object getPatientDateReglement() {
return patientDateReglement;
}

public void setPatientDateReglement(Object patientDateReglement) {
this.patientDateReglement = patientDateReglement;
}

public Object getExamen() {
return examen;
}

public void setExamen(Object examen) {
this.examen = examen;
}

public String getTraitement() {
return traitement;
}

public void setTraitement(String traitement) {
this.traitement = traitement;
}

public Object getHistoireMaladie() {
return histoireMaladie;
}

public void setHistoireMaladie(Object histoireMaladie) {
this.histoireMaladie = histoireMaladie;
}

public Object getConclusion() {
return conclusion;
}

public void setConclusion(Object conclusion) {
this.conclusion = conclusion;
}

public String getPremiere() {
return premiere;
}

public void setPremiere(String premiere) {
this.premiere = premiere;
}

public String getDerniere() {
return derniere;
}

public void setDerniere(String derniere) {
this.derniere = derniere;
}

public Object getTarif() {
return tarif;
}

public void setTarif(Object tarif) {
this.tarif = tarif;
}

public Object getPatientModeReglement() {
return patientModeReglement;
}

public void setPatientModeReglement(Object patientModeReglement) {
this.patientModeReglement = patientModeReglement;
}

public String getArrivee() {
return arrivee;
}

public void setArrivee(String arrivee) {
this.arrivee = arrivee;
}

public Object getCodesCcam() {
return codesCcam;
}

public void setCodesCcam(Object codesCcam) {
this.codesCcam = codesCcam;
}

public Object getBanqueId() {
return banqueId;
}

public void setBanqueId(Object banqueId) {
this.banqueId = banqueId;
}

public Object getCategorieId() {
return categorieId;
}

public void setCategorieId(Object categorieId) {
this.categorieId = categorieId;
}

public String getAdresse() {
return adresse;
}

public void setAdresse(String adresse) {
this.adresse = adresse;
}

public String getValide() {
return valide;
}

public void setValide(String valide) {
this.valide = valide;
}

public Object getTotalAmc() {
return totalAmc;
}

public void setTotalAmc(Object totalAmc) {
this.totalAmc = totalAmc;
}

public Object getTotalAmo() {
return totalAmo;
}

public void setTotalAmo(Object totalAmo) {
this.totalAmo = totalAmo;
}

public Object getTotalAssure() {
return totalAssure;
}

public void setTotalAssure(Object totalAssure) {
this.totalAssure = totalAssure;
}

public Integer getDuPatient() {
return duPatient;
}

public void setDuPatient(Integer duPatient) {
this.duPatient = duPatient;
}

public Integer getSejourId() {
return sejourId;
}

public void setSejourId(Integer sejourId) {
this.sejourId = sejourId;
}

public Integer getDuTiers() {
return duTiers;
}

public void setDuTiers(Integer duTiers) {
this.duTiers = duTiers;
}

public Object getTiersModeReglement() {
return tiersModeReglement;
}

public void setTiersModeReglement(Object tiersModeReglement) {
this.tiersModeReglement = tiersModeReglement;
}

public Object getTiersDateReglement() {
return tiersDateReglement;
}

public void setTiersDateReglement(Object tiersDateReglement) {
this.tiersDateReglement = tiersDateReglement;
}

public Object getDateAt() {
return dateAt;
}

public void setDateAt(Object dateAt) {
this.dateAt = dateAt;
}

public String getConcerneALD() {
return concerneALD;
}

public void setConcerneALD(String concerneALD) {
this.concerneALD = concerneALD;
}

public String getFacture() {
return facture;
}

public void setFacture(String facture) {
this.facture = facture;
}

public Object getAdresseParPratId() {
return adresseParPratId;
}

public void setAdresseParPratId(Object adresseParPratId) {
this.adresseParPratId = adresseParPratId;
}

public String getSiDesistement() {
return siDesistement;
}

public void setSiDesistement(String siDesistement) {
this.siDesistement = siDesistement;
}

public Object getFinAt() {
return finAt;
}

public void setFinAt(Object finAt) {
this.finAt = finAt;
}

public Object getPecAt() {
return pecAt;
}

public void setPecAt(Object pecAt) {
this.pecAt = pecAt;
}

public Object getRepriseAt() {
return repriseAt;
}

public void setRepriseAt(Object repriseAt) {
this.repriseAt = repriseAt;
}

public String getType() {
return type;
}

public void setType(String type) {
this.type = type;
}

public Object getGrossesseId() {
return grossesseId;
}

public void setGrossesseId(Object grossesseId) {
this.grossesseId = grossesseId;
}

public String getAtSansArret() {
return atSansArret;
}

public void setAtSansArret(String atSansArret) {
this.atSansArret = atSansArret;
}

public String getArretMaladie() {
return arretMaladie;
}

public void setArretMaladie(String arretMaladie) {
this.arretMaladie = arretMaladie;
}

public Object getFactureconsultId() {
return factureconsultId;
}

public void setFactureconsultId(Object factureconsultId) {
this.factureconsultId = factureconsultId;
}

public Object getBrancardage() {
return brancardage;
}

public void setBrancardage(Object brancardage) {
this.brancardage = brancardage;
}

public Integer getSianesthesique() {
return sianesthesique;
}

public void setSianesthesique(Integer sianesthesique) {
this.sianesthesique = sianesthesique;
}

}
</code>```

Title: GSON can't deserialize an array

Body:
I'm facing a problem with Gson. I'm fetching Json data formatted. Here is the syntax :

I/Reponse-Json: [{"consultation_id":281,"plageconsult_id":76,"patient_id":116,"heure":"11:04:00","duree":1,"motif":null,"secteur1":0,"secteur2":0,"rques":null,"chrono":"32","annule":"0","patient_date_reglement":null,"examen":null,"traitement":null,"histoire_maladie":null,"conclusion":null,"premiere":"0","derniere":"0","tarif":null,"patient_mode_reglement":null,"arrivee":"2017-11-22 11:04:00","codes_ccam":null,"banque_id":null,"categorie_id":null,"adresse":"0","valide":"0","total_amc":null,"total_amo":null,"total_assure":null,"du_patient":0,"sejour_id":252,"du_tiers":0,"tiers_mode_reglement":null,"tiers_date_reglement":null,"date_at":null,"concerne_ALD":"0","facture":"0","adresse_par_prat_id":null,"si_desistement":"0","fin_at":null,"pec_at":null,"reprise_at":null,"type":"classique","grossesse_id":null,"at_sans_arret":"0","arret_maladie":"0","factureconsult_id":null,"brancardage":null,"sianesthesique":0},{"consultation_id":282,"plageconsult_id":77,"patient_id":116,"heure":"16:31:00","duree":1,"motif":null,"secteur1":0,"secteur2":0,"rques":"RAS","chrono":"64","annule":"0","patient_date_reglement":null,"examen":null,"traitement":"HUILE DE PARAFINE FL DE 1 LITRE\n","histoire_maladie":null,"conclusion":null,"premiere":"0","derniere":"0","tarif":null,"patient_mode_reglement":null,"arrivee":"2017-11-22 16:31:00","codes_ccam":null,"banque_id":null,"categorie_id":null,"adresse":"0","valide":"0","total_amc":null,"total_amo":null,"total_assure":null,"du_patient":0,"sejour_id":252,"du_tiers":0,"tiers_mode_reglement":null,"tiers_date_reglement":null,"date_at":null,"concerne_ALD":"0","facture":"0","adresse_par_prat_id":null,"si_desistement":"0","fin_at":null,"pec_at":null,"reprise_at":null,"type":"classique","grossesse_id":null,"at_sans_arret":"0","arret_maladie":"0","factureconsult_id":null,"brancardage":null,"sianesthesique":0}]

And here is the code used to deserialized

    Log.i("Reponse-Json", response);
    List<Consultation> consultations = Arrays.asList(gson.fromJson(response, Consultation[].class));
    Log.i("ConsultActivity", consultations.size()+" consultations loaded");
    for (Consultation c : consultations) {
        Log.i("ConsultActivity", ""+c.getConsultationId());
    }

And here is the error:

com.google.gson.JsonSyntaxException: java.lang.IllegalStateException: Expected BEGIN_OBJECT but was STRING at line 1 column 72
                                                                  at com.google.gson.internal.bind.ReflectiveTypeAdapterFactory$Adapter.read(ReflectiveTypeAdapterFactory.java:176)
                                                                  at com.google.gson.internal.bind.ReflectiveTypeAdapterFactory$1.read(ReflectiveTypeAdapterFactory.java:93)
                                                                  at com.google.gson.internal.bind.ReflectiveTypeAdapterFactory$Adapter.read(ReflectiveTypeAdapterFactory.java:172)
                                                                  at com.google.gson.internal.bind.TypeAdapterRuntimeTypeWrapper.read(TypeAdapterRuntimeTypeWrapper.java:40)
                                                                  at com.google.gson.internal.bind.ArrayTypeAdapter.read(ArrayTypeAdapter.java:72)
                                                                  at com.google.gson.Gson.fromJson(Gson.java:803)
                                                                  at com.google.gson.Gson.fromJson(Gson.java:768)
                                                                  at com.google.gson.Gson.fromJson(Gson.java:717)
                                                                  at com.google.gson.Gson.fromJson(Gson.java:689)
                                                                  at org.cfrtmbk.www.elaafi.ConsultActivity$1.onResponse(ConsultActivity.java:69)
                                                                  at org.cfrtmbk.www.elaafi.ConsultActivity$1.onResponse(ConsultActivity.java:65)
                                                                  at com.android.volley.toolbox.StringRequest.deliverResponse(StringRequest.java:60)
                                                                  at com.android.volley.toolbox.StringRequest.deliverResponse(StringRequest.java:30)
                                                                  at com.android.volley.ExecutorDelivery$ResponseDeliveryRunnable.run(ExecutorDelivery.java:99)
                                                                  at android.os.Handler.handleCallback(Handler.java:751)
                                                                  at android.os.Handler.dispatchMessage(Handler.java:95)
                                                                  at android.os.Looper.loop(Looper.java:154)
                                                                  at android.app.ActivityThread.main(ActivityThread.java:6119)
                                                                  at java.lang.reflect.Method.invoke(Native Method)
                                                                  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:886)
                                                                  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:776)
                                                               Caused by: java.lang.IllegalStateException: Expected BEGIN_OBJECT but was STRING at line 1 column 72
                                                                  at com.google.gson.stream.JsonReader.beginObject(JsonReader.java:374)
                                                                  at com.google.gson.internal.bind.ReflectiveTypeAdapterFactory$Adapter.read(ReflectiveTypeAdapterFactory

I have try to use a solution similar to :

Type collectionType = new TypeToken<Collection<channelSearchEnum>>(){}.getType();
Collection<channelSearchEnum> enums = gson.fromJson(yourJson, collectionType);

but having the same issue
Please help me

Body:
If you are using gson library then try this

Gson gson = new Gson();
   List<Consultation> consultations= gson.fromJson(json, new TypeToken<List<Consultation>>(){}.getType());
    for (Consultation consultation: consultations) {
        Log.e("TEST","Consultation id : " + consultation.getConsulationId());
        Log.e("TEST","Patient id: " + consultation.getPatientid());
    }

Consultation.java

import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;

public class Consultation{

@SerializedName("consultation_id")
@Expose
private Integer consultationId;
@SerializedName("plageconsult_id")
@Expose
private Integer plageconsultId;
@SerializedName("patient_id")
@Expose
private Integer patientId;
@SerializedName("heure")
@Expose
private String heure;
@SerializedName("duree")
@Expose
private Integer duree;
@SerializedName("motif")
@Expose
private Object motif;
@SerializedName("secteur1")
@Expose
private Integer secteur1;
@SerializedName("secteur2")
@Expose
private Integer secteur2;
@SerializedName("rques")
@Expose
private String rques;
@SerializedName("chrono")
@Expose
private String chrono;
@SerializedName("annule")
@Expose
private String annule;
@SerializedName("patient_date_reglement")
@Expose
private Object patientDateReglement;
@SerializedName("examen")
@Expose
private Object examen;
@SerializedName("traitement")
@Expose
private String traitement;
@SerializedName("histoire_maladie")
@Expose
private Object histoireMaladie;
@SerializedName("conclusion")
@Expose
private Object conclusion;
@SerializedName("premiere")
@Expose
private String premiere;
@SerializedName("derniere")
@Expose
private String derniere;
@SerializedName("tarif")
@Expose
private Object tarif;
@SerializedName("patient_mode_reglement")
@Expose
private Object patientModeReglement;
@SerializedName("arrivee")
@Expose
private String arrivee;
@SerializedName("codes_ccam")
@Expose
private Object codesCcam;
@SerializedName("banque_id")
@Expose
private Object banqueId;
@SerializedName("categorie_id")
@Expose
private Object categorieId;
@SerializedName("adresse")
@Expose
private String adresse;
@SerializedName("valide")
@Expose
private String valide;
@SerializedName("total_amc")
@Expose
private Object totalAmc;
@SerializedName("total_amo")
@Expose
private Object totalAmo;
@SerializedName("total_assure")
@Expose
private Object totalAssure;
@SerializedName("du_patient")
@Expose
private Integer duPatient;
@SerializedName("sejour_id")
@Expose
private Integer sejourId;
@SerializedName("du_tiers")
@Expose
private Integer duTiers;
@SerializedName("tiers_mode_reglement")
@Expose
private Object tiersModeReglement;
@SerializedName("tiers_date_reglement")
@Expose
private Object tiersDateReglement;
@SerializedName("date_at")
@Expose
private Object dateAt;
@SerializedName("concerne_ALD")
@Expose
private String concerneALD;
@SerializedName("facture")
@Expose
private String facture;
@SerializedName("adresse_par_prat_id")
@Expose
private Object adresseParPratId;
@SerializedName("si_desistement")
@Expose
private String siDesistement;
@SerializedName("fin_at")
@Expose
private Object finAt;
@SerializedName("pec_at")
@Expose
private Object pecAt;
@SerializedName("reprise_at")
@Expose
private Object repriseAt;
@SerializedName("type")
@Expose
private String type;
@SerializedName("grossesse_id")
@Expose
private Object grossesseId;
@SerializedName("at_sans_arret")
@Expose
private String atSansArret;
@SerializedName("arret_maladie")
@Expose
private String arretMaladie;
@SerializedName("factureconsult_id")
@Expose
private Object factureconsultId;
@SerializedName("brancardage")
@Expose
private Object brancardage;
@SerializedName("sianesthesique")
@Expose
private Integer sianesthesique;

public Integer getConsultationId() {
return consultationId;
}

public void setConsultationId(Integer consultationId) {
this.consultationId = consultationId;
}

public Integer getPlageconsultId() {
return plageconsultId;
}

public void setPlageconsultId(Integer plageconsultId) {
this.plageconsultId = plageconsultId;
}

public Integer getPatientId() {
return patientId;
}

public void setPatientId(Integer patientId) {
this.patientId = patientId;
}

public String getHeure() {
return heure;
}

public void setHeure(String heure) {
this.heure = heure;
}

public Integer getDuree() {
return duree;
}

public void setDuree(Integer duree) {
this.duree = duree;
}

public Object getMotif() {
return motif;
}

public void setMotif(Object motif) {
this.motif = motif;
}

public Integer getSecteur1() {
return secteur1;
}

public void setSecteur1(Integer secteur1) {
this.secteur1 = secteur1;
}

public Integer getSecteur2() {
return secteur2;
}

public void setSecteur2(Integer secteur2) {
this.secteur2 = secteur2;
}

public String getRques() {
return rques;
}

public void setRques(String rques) {
this.rques = rques;
}

public String getChrono() {
return chrono;
}

public void setChrono(String chrono) {
this.chrono = chrono;
}

public String getAnnule() {
return annule;
}

public void setAnnule(String annule) {
this.annule = annule;
}

public Object getPatientDateReglement() {
return patientDateReglement;
}

public void setPatientDateReglement(Object patientDateReglement) {
this.patientDateReglement = patientDateReglement;
}

public Object getExamen() {
return examen;
}

public void setExamen(Object examen) {
this.examen = examen;
}

public String getTraitement() {
return traitement;
}

public void setTraitement(String traitement) {
this.traitement = traitement;
}

public Object getHistoireMaladie() {
return histoireMaladie;
}

public void setHistoireMaladie(Object histoireMaladie) {
this.histoireMaladie = histoireMaladie;
}

public Object getConclusion() {
return conclusion;
}

public void setConclusion(Object conclusion) {
this.conclusion = conclusion;
}

public String getPremiere() {
return premiere;
}

public void setPremiere(String premiere) {
this.premiere = premiere;
}

public String getDerniere() {
return derniere;
}

public void setDerniere(String derniere) {
this.derniere = derniere;
}

public Object getTarif() {
return tarif;
}

public void setTarif(Object tarif) {
this.tarif = tarif;
}

public Object getPatientModeReglement() {
return patientModeReglement;
}

public void setPatientModeReglement(Object patientModeReglement) {
this.patientModeReglement = patientModeReglement;
}

public String getArrivee() {
return arrivee;
}

public void setArrivee(String arrivee) {
this.arrivee = arrivee;
}

public Object getCodesCcam() {
return codesCcam;
}

public void setCodesCcam(Object codesCcam) {
this.codesCcam = codesCcam;
}

public Object getBanqueId() {
return banqueId;
}

public void setBanqueId(Object banqueId) {
this.banqueId = banqueId;
}

public Object getCategorieId() {
return categorieId;
}

public void setCategorieId(Object categorieId) {
this.categorieId = categorieId;
}

public String getAdresse() {
return adresse;
}

public void setAdresse(String adresse) {
this.adresse = adresse;
}

public String getValide() {
return valide;
}

public void setValide(String valide) {
this.valide = valide;
}

public Object getTotalAmc() {
return totalAmc;
}

public void setTotalAmc(Object totalAmc) {
this.totalAmc = totalAmc;
}

public Object getTotalAmo() {
return totalAmo;
}

public void setTotalAmo(Object totalAmo) {
this.totalAmo = totalAmo;
}

public Object getTotalAssure() {
return totalAssure;
}

public void setTotalAssure(Object totalAssure) {
this.totalAssure = totalAssure;
}

public Integer getDuPatient() {
return duPatient;
}

public void setDuPatient(Integer duPatient) {
this.duPatient = duPatient;
}

public Integer getSejourId() {
return sejourId;
}

public void setSejourId(Integer sejourId) {
this.sejourId = sejourId;
}

public Integer getDuTiers() {
return duTiers;
}

public void setDuTiers(Integer duTiers) {
this.duTiers = duTiers;
}

public Object getTiersModeReglement() {
return tiersModeReglement;
}

public void setTiersModeReglement(Object tiersModeReglement) {
this.tiersModeReglement = tiersModeReglement;
}

public Object getTiersDateReglement() {
return tiersDateReglement;
}

public void setTiersDateReglement(Object tiersDateReglement) {
this.tiersDateReglement = tiersDateReglement;
}

public Object getDateAt() {
return dateAt;
}

public void setDateAt(Object dateAt) {
this.dateAt = dateAt;
}

public String getConcerneALD() {
return concerneALD;
}

public void setConcerneALD(String concerneALD) {
this.concerneALD = concerneALD;
}

public String getFacture() {
return facture;
}

public void setFacture(String facture) {
this.facture = facture;
}

public Object getAdresseParPratId() {
return adresseParPratId;
}

public void setAdresseParPratId(Object adresseParPratId) {
this.adresseParPratId = adresseParPratId;
}

public String getSiDesistement() {
return siDesistement;
}

public void setSiDesistement(String siDesistement) {
this.siDesistement = siDesistement;
}

public Object getFinAt() {
return finAt;
}

public void setFinAt(Object finAt) {
this.finAt = finAt;
}

public Object getPecAt() {
return pecAt;
}

public void setPecAt(Object pecAt) {
this.pecAt = pecAt;
}

public Object getRepriseAt() {
return repriseAt;
}

public void setRepriseAt(Object repriseAt) {
this.repriseAt = repriseAt;
}

public String getType() {
return type;
}

public void setType(String type) {
this.type = type;
}

public Object getGrossesseId() {
return grossesseId;
}

public void setGrossesseId(Object grossesseId) {
this.grossesseId = grossesseId;
}

public String getAtSansArret() {
return atSansArret;
}

public void setAtSansArret(String atSansArret) {
this.atSansArret = atSansArret;
}

public String getArretMaladie() {
return arretMaladie;
}

public void setArretMaladie(String arretMaladie) {
this.arretMaladie = arretMaladie;
}

public Object getFactureconsultId() {
return factureconsultId;
}

public void setFactureconsultId(Object factureconsultId) {
this.factureconsultId = factureconsultId;
}

public Object getBrancardage() {
return brancardage;
}

public void setBrancardage(Object brancardage) {
this.brancardage = brancardage;
}

public Integer getSianesthesique() {
return sianesthesique;
}

public void setSianesthesique(Integer sianesthesique) {
this.sianesthesique = sianesthesique;
}

}


来源: stackexchange

问:
Xamarin Android. Separate view for selected item in listview
I have ListView where every item represented as image + text, defined in separate layout.
When user clicks any item, I would like to extend selected item with additional information, so listview would have bigger height and contain some text.
What is the best practice to do that? Should I replace listview item view somehow?</p>

答:
You can use Visibility property by setting it to Invisible, and then change it to Visible when Item is Clicked. note that the information height should be auto and you need to calculate ListView Height with each modification;

Edited Code:

```<code>FindViewById<TextView>(Resource.Id.Test).Visibility = Android.Views.ViewStates.Invisible;
</code>```

Use this code to set the element (ex. TextView) to Invisible or Visible (ViewStates.Visible)

ContentLicense: CC BY-SA 3.0

Body:
You can use Visibility property by setting it to Invisible, and then change it to Visible when Item is Clicked. note that the information height should be auto and you need to calculate ListView Height with each modification;

Edited Code:

FindViewById<TextView>(Resource.Id.Test).Visibility = Android.Views.ViewStates.Invisible;

Use this code to set the element (ex. TextView) to Invisible or Visible (ViewStates.Visible)


问:
How to open ssh gcloud vm session from the browser to another account
I have a VM instance setup in Google Cloud. Most of the time I use gcloud tool to open ssh session from the terminal, it uses a user account on the VM with the same name as the account I am connecting from.

When, however, I open an SSH session from the browser it uses another user account on the VM, the one with the same name as the email I use to login to google cloud from the browser.

I would like to open the session from the browser and to log into the another account of my choice, the one I open from the terminal for instance.

How can I manage that?

答:
After ssh into your virtual machine from the browser, you can login with another account by using the command $ gcloud auth login

You will get a link that allows you to choose a different account. After choosing the account, you will get a verification code. Paste the verification code into the VM instance terminal and you are done.

To verify the change, you can use $ gcloud auth list to see the accounts you currently have available. You should see a * sign before the current active account.

Now you can also set the active account by running:
    $ gcloud config set account [YOUR_ACCOUNT]

Extra: In case you want to use a different account from the terminal, you can simply use  $ gcloud compute ssh [user@]INSTANCE


问:
Alamofire post body format is not correct
I use Alamofire to call api methods. I use it like this

```<code>Alamofire.request("some api",
        method:method,
        parameters:body,
        encoding:URLEncoding.default,
        headers: finalHeaders)
        .responseJSON { (apiResponse) in
        ...
</code>```

body is a Dictionary of Strings and Any. When I send a post request server gets something like this as body:

```<code>key1=StringValue&key2=intValue
</code>```

While I need my body format be like this:

```<code>"key1":"StringValue","key2":intValue
</code>```

What parameter is not set or is set wrongly?

答:
The answer is to change the encoding type like this</p>

```<code>Alamofire.request("some api",
        method:method,
        parameters:body,
        encoding:JSONEncoding.default,
        headers: finalHeaders)
        .responseJSON { (apiResponse) in
        ...
</code>```

Body:
I use Alamofire to call api methods. I use it like this

Alamofire.request("some api",
        method:method,
        parameters:body,
        encoding:URLEncoding.default,
        headers: finalHeaders)
        .responseJSON { (apiResponse) in
        ...

body is a Dictionary of Strings and Any. When I send a post request server gets something like this as body:

key1=StringValue&key2=intValue

While I need my body format be like this:

"key1":"StringValue","key2":intValue

What parameter is not set or is set wrongly?

Body:
The answer is to change the encoding type like this

Alamofire.request("some api",
        method:method,
        parameters:body,
        encoding:JSONEncoding.default,
        headers: finalHeaders)
        .responseJSON { (apiResponse) in
        ...


问:
about torch.nn.CrossEntropyLoss parameter shape
i'm learning pytorch, and taking the anpr project,which is based tensorflow
(https://github.com/matthewearl/deep-anpr,
http://matthewearl.github.io/2016/05/06/cnn-anpr/)
as a exercise, transplant it to pytorch platform.

there is a problem,i'm using nn.CrossEntropyLoss() as loss function:

```<code>criterion=nn.CrossEntropyLoss()
</code>```

the output.data of model is:

```<code>  - 1.00000e-02 *
   - 2.5552 2.7582 2.5368 ... 5.6184 1.2288 -0.0076
   - 0.7033 1.3167 -1.0966 ... 4.7249 1.3217 1.8367
   - 0.7592 1.4777 1.8095 ... 0.8733 1.2417 1.1521
   - 0.1040 -0.7054 -3.4862 ... 4.7703 2.9595 1.4263
   - [torch.FloatTensor of size 4x253]
</code>```

and targets.data is:

```<code> - 1 0 0 ... 0 0 0
 - 1 0 0 ... 0 0 0
 - 1 0 0 ... 0 0 0
 - 1 0 0 ... 0 0 0
 - [torch.DoubleTensor of size 4x253]
</code>```

when i call:

```<code>loss=criterion(output,targets)
</code>```

error occured,information is:

```<code>TypeError: FloatClassNLLCriterion_updateOutput received an invalid combination of arguments - got (int, torch.FloatTensor, **torch.DoubleTensor**, torch.FloatTensor, bool, NoneType, torch.FloatTensor), but expected (int state, torch.FloatTensor input, **torch.LongTensor** target, torch.FloatTensor output, bool sizeAverage, [torch.FloatTensor weights or None], torch.FloatTensor total_weight)

'expected torch.LongTensor'......'got torch.DoubleTensor',but if i convert the targets into LongTensor:
torch.LongTensor(numpy.array(targets.data.numpy(),numpy.long))
</code>```

call loss=criterion(output,targets), the error is:

```<code>RuntimeError: multi-target not supported at /data/users/soumith/miniconda2/conda-bld/pytorch-0.1.10_1488752595704/work/torch/lib/THNN/generic/ClassNLLCriterion.c:20
</code>```

my last exercise is mnist, a example from pytorch,i made a bit modification,batch_size is 4,the loss function:

```<code>loss = F.nll_loss(outputs, labels)
</code>```

outputs.data:

```<code> - -2.3220 -2.1229 -2.3395 -2.3391 -2.5270 -2.3269 -2.1055 -2.2321 -2.4943 -2.2996

   -2.3653 -2.2034 -2.4437 -2.2708 -2.5114 -2.3286 -2.1921 -2.1771 -2.3343 -2.2533

   -2.2809 -2.2119 -2.3872 -2.2190 -2.4610 -2.2946 -2.2053 -2.3192 -2.3674 -2.3100

   -2.3715 -2.1455 -2.4199 -2.4177 -2.4565 -2.2812 -2.2467 -2.1144 -2.3321 -2.3009

   [torch.FloatTensor of size 4x10]
</code>```

labels.data:

```<code> - 8
 - 6
 - 0
 - 1
 - [torch.LongTensor of size 4]
</code>```

the labels, for a input image,must be a single element, in upper example, there is 253 numbers, and in 'mnist',there is only one number, the shape of outputs is difference from labels.

i review the tensorflow manual, tf.nn.softmax_cross_entropy_with_logits,
'Logits and labels must have the sameshape [batch_size, num_classes] and the same dtype (either float32 or float64).'

does pytorch support the same function in tensorflow?

many thks

答:
CrossEntropyLoss is equivalent to tf.nn.softmax_cross_entropy_with_logits. The input to CrossEntropyLoss  is a categorical vector of shape [batch_size]. Use .view() to change the tensor shapes.

labels = labels.view(-1)
output = output.view(labels.size(0), -1)
loss = criterion(output, loss)

calling .view(x, y, -1) causes the tensor to use the remaining datapoints to fill the -1 dimension and will cause an error if there is not enough to make a full dimension

labels.size(0) gives the size of the 0th dimension of the label tensor

Additional

to convert between tensor types you can call the type on the tensor, for example 'labels = labels.long()`

Second Additional

If you unpack the data from a variable like so output.data then you will lose the gradients for that output and be unable to backprop when the time comes

ContentLicense: CC BY-SA 4.0

Body:
i'm learning pytorch, and taking the anpr project,which is based tensorflow
(https://github.com/matthewearl/deep-anpr,
http://matthewearl.github.io/2016/05/06/cnn-anpr/)
as a exercise, transplant it to pytorch platform.

there is a problem,i'm using nn.CrossEntropyLoss() as loss function:

criterion=nn.CrossEntropyLoss()

the output.data of model is:

  - 1.00000e-02 *
   - 2.5552 2.7582 2.5368 ... 5.6184 1.2288 -0.0076
   - 0.7033 1.3167 -1.0966 ... 4.7249 1.3217 1.8367
   - 0.7592 1.4777 1.8095 ... 0.8733 1.2417 1.1521
   - 0.1040 -0.7054 -3.4862 ... 4.7703 2.9595 1.4263
   - [torch.FloatTensor of size 4x253]

and targets.data is:

 - 1 0 0 ... 0 0 0
 - 1 0 0 ... 0 0 0
 - 1 0 0 ... 0 0 0
 - 1 0 0 ... 0 0 0
 - [torch.DoubleTensor of size 4x253]

when i call:

loss=criterion(output,targets)

error occured,information is:

TypeError: FloatClassNLLCriterion_updateOutput received an invalid combination of arguments - got (int, torch.FloatTensor, **torch.DoubleTensor**, torch.FloatTensor, bool, NoneType, torch.FloatTensor), but expected (int state, torch.FloatTensor input, **torch.LongTensor** target, torch.FloatTensor output, bool sizeAverage, [torch.FloatTensor weights or None], torch.FloatTensor total_weight)

'expected torch.LongTensor'......'got torch.DoubleTensor',but if i convert the targets into LongTensor:
torch.LongTensor(numpy.array(targets.data.numpy(),numpy.long))

call loss=criterion(output,targets), the error is:

RuntimeError: multi-target not supported at /data/users/soumith/miniconda2/conda-bld/pytorch-0.1.10_1488752595704/work/torch/lib/THNN/generic/ClassNLLCriterion.c:20

my last exercise is mnist, a example from pytorch,i made a bit modification,batch_size is 4,the loss function:

loss = F.nll_loss(outputs, labels)

outputs.data:

 - -2.3220 -2.1229 -2.3395 -2.3391 -2.5270 -2.3269 -2.1055 -2.2321 -2.4943 -2.2996

   -2.3653 -2.2034 -2.4437 -2.2708 -2.5114 -2.3286 -2.1921 -2.1771 -2.3343 -2.2533

   -2.2809 -2.2119 -2.3872 -2.2190 -2.4610 -2.2946 -2.2053 -2.3192 -2.3674 -2.3100

   -2.3715 -2.1455 -2.4199 -2.4177 -2.4565 -2.2812 -2.2467 -2.1144 -2.3321 -2.3009

   [torch.FloatTensor of size 4x10]

labels.data:

 - 8
 - 6
 - 0
 - 1
 - [torch.LongTensor of size 4]

the labels, for a input image,must be a single element, in upper example, there is 253 numbers, and in 'mnist',there is only one number, the shape of outputs is difference from labels.

i review the tensorflow manual, tf.nn.softmax_cross_entropy_with_logits,
'Logits and labels must have the sameshape [batch_size, num_classes] and the same dtype (either float32 or float64).'

does pytorch support the same function in tensorflow?

many thks


问:
C# static vs instance methods
I'm risking it this might be a newb question but here goes. I'm tempted to add a method to a class that could possible have thousands and thousands of instances in memory at a given time. Now, the other option is creating a static class with a static method, and just create the [static] method there, instead of an instance method in the class. Something like so:

This:

```<code>public static class PetOwner
{
    public static void RenamePet(Pet pet, string newName)
    {
        pet.Name = newName;
    }
}
</code>```

Instead of this:

```<code>public class Pet
{
    public string Name { get; set; }

    public void Rename(string newName)
    {
        this.Name = newName;
    }
}
</code>```

I'm just wondering if the static class alternative would take considerably less memory.

Thanks!

答:
Only data fields require storage per instance, subject to certain conditions and optimisations. For instance, 10,000 instances of a class that define an Int32 member will consume ~40,000 bytes of memory.

Strings, on the other hand, are not so simple due to interning. You can try this as an example:

```<code>object.ReferenceEquals("", string.Empty) // returns true!
</code>```

If the same 10,000 instances also define a string, and that string is the same for each instance, then you're going to have 10,000 references pointing at the same data, reducing overhead considerably (but in a 32-bit environment, there's another 40,000 bytes taken up by the references).

Methods, as pointed out by others, whether static or instance, are only loaded once.

The decision to use either instance or static methods is not influenced by performance reasons, but by how the method is intended to be used. In your case, the method requires an instance of the type as its first parameter so it may as well be an instance method.

Static methods, in my experience, are most useful as an alternative to a type's constructor for returning a new instance. Constructors, once invoked, have to either return a new instance or throw an exception, which may not be desirable. Static methods can return null if something fails, or return a cached instance (the latter of which is useful if the constructor is an expensive operation).

ContentLicense: CC BY-SA 2.5

Title: C# static vs instance methods

Body:
I'm risking it this might be a newb question but here goes. I'm tempted to add a method to a class that could possible have thousands and thousands of instances in memory at a given time. Now, the other option is creating a static class with a static method, and just create the [static] method there, instead of an instance method in the class. Something like so:

This:

public static class PetOwner
{
    public static void RenamePet(Pet pet, string newName)
    {
        pet.Name = newName;
    }
}

Instead of this:

public class Pet
{
    public string Name { get; set; }

    public void Rename(string newName)
    {
        this.Name = newName;
    }
}

I'm just wondering if the static class alternative would take considerably less memory.

Thanks!

Body:
Only data fields require storage per instance, subject to certain conditions and optimisations. For instance, 10,000 instances of a class that define an Int32 member will consume ~40,000 bytes of memory.

Strings, on the other hand, are not so simple due to interning. You can try this as an example:

object.ReferenceEquals("", string.Empty) // returns true!

If the same 10,000 instances also define a string, and that string is the same for each instance, then you're going to have 10,000 references pointing at the same data, reducing overhead considerably (but in a 32-bit environment, there's another 40,000 bytes taken up by the references).

Methods, as pointed out by others, whether static or instance, are only loaded once.

The decision to use either instance or static methods is not influenced by performance reasons, but by how the method is intended to be used. In your case, the method requires an instance of the type as its first parameter so it may as well be an instance method.

Static methods, in my experience, are most useful as an alternative to a type's constructor for returning a new instance. Constructors, once invoked, have to either return a new instance or throw an exception, which may not be desirable. Static methods can return null if something fails, or return a cached instance (the latter of which is useful if the constructor is an expensive operation).


问:
C++ expected class-name before { token, an inheritance error
KSetBase.h base class , an interface

```<code>#ifndef HW6_GTUSETBASE_H
#define HW6_GTUSETBASE_H

class KSet;

#include <cstddef>
namespace TU {
    template<typename T>
    class KSetBase {
    public:
        virtual bool empty() const = 0;

        virtual size_t size() const = 0; //int is not okay since unsigned also could be in.
        //comparisons would be not working if that was case
        //detailed
        //https://stackoverflow.com/questions/1181079/stringsize-type-instead-of-int

        virtual size_t max_size() const = 0;

        virtual void insert(T first, T second) = 0; //cift dondurmesi gerekli
        virtual void erase(T deleter) = 0;

        virtual void clear() = 0;

        virtual T find(T deneme) = 0;

        virtual size_t count(T testle) = 0;

        virtual T begin() = 0;

        virtual T end() = 0;

    protected:
        ~GTUSetBase() {
            //do nothing
        }

    };
}

#endif //HW6_GTUSETBASE_H
</code>```

KSet.h (derived class)

```<code>#include "KSetBase.h"
#ifndef HW6_GTUSET_H
#define HW6_GTUSET_H

#include <memory>

using namespace std;
namespace TU {

    template<typename T>
    class KSet : public KSetBase {
    public:
        bool empty() const;

        size_t size() const;

        size_t max_size() const;

        void insert(T first);

        void erase(T deleter);

        void clear();

        T find(T deneme);

        size_t count(T testle);

        T begin();

        T end();

    protected:
        int hmany = 0;
        shared_ptr<T> set_harmony;

    };

}

#endif //HW6_GTUSET_H
</code>```

I cant figure out what part of my code is wrong. I basically made a basic inheritance from interface class, which i implemented all functions in KSet.cpp. In theory nothing looks wrong but it gives 2 errors.

both in main.cpp and KSet.cpp

class KSet : public KSetBase {
Error line is this.

I checked #ifndef and #defines, i thought about using forward declaration but i cant seems to work that out.I am really stuck with this problem. I searched whole web about it , in the end there's always a big error on syntax or something that is visible , but i can't figure out on mine. It's very short and simple code.

答:
KSetBase is a template class, if you inherit from it you must specify a template argument:

```<code>template<typename T>
    class KSet : public KSetBase<T>
</code>```

In addition, it seems you have a typo in the base class destructor.

Body:
KSetBase.h base class , an interface

#ifndef HW6_GTUSETBASE_H
#define HW6_GTUSETBASE_H

class KSet;

#include <cstddef>
namespace TU {
    template<typename T>
    class KSetBase {
    public:
        virtual bool empty() const = 0;

        virtual size_t size() const = 0; //int is not okay since unsigned also could be in.
        //comparisons would be not working if that was case
        //detailed
        //https://stackoverflow.com/questions/1181079/stringsize-type-instead-of-int

        virtual size_t max_size() const = 0;

        virtual void insert(T first, T second) = 0; //cift dondurmesi gerekli
        virtual void erase(T deleter) = 0;

        virtual void clear() = 0;

        virtual T find(T deneme) = 0;

        virtual size_t count(T testle) = 0;

        virtual T begin() = 0;

        virtual T end() = 0;

    protected:
        ~GTUSetBase() {
            //do nothing
        }

    };
}

#endif //HW6_GTUSETBASE_H

KSet.h (derived class)

#include "KSetBase.h"
#ifndef HW6_GTUSET_H
#define HW6_GTUSET_H

#include <memory>

using namespace std;
namespace TU {

    template<typename T>
    class KSet : public KSetBase {
    public:
        bool empty() const;

        size_t size() const;

        size_t max_size() const;

        void insert(T first);

        void erase(T deleter);

        void clear();

        T find(T deneme);

        size_t count(T testle);

        T begin();

        T end();

    protected:
        int hmany = 0;
        shared_ptr<T> set_harmony;

    };

}

#endif //HW6_GTUSET_H

I cant figure out what part of my code is wrong. I basically made a basic inheritance from interface class, which i implemented all functions in KSet.cpp. In theory nothing looks wrong but it gives 2 errors.

both in main.cpp and KSet.cpp

class KSet : public KSetBase {
Error line is this.

I checked #ifndef and #defines, i thought about using forward declaration but i cant seems to work that out.I am really stuck with this problem. I searched whole web about it , in the end there's always a big error on syntax or something that is visible , but i can't figure out on mine. It's very short and simple code.

Body:
KSetBase is a template class, if you inherit from it you must specify a template argument:

template<typename T>
    class KSet : public KSetBase<T>

In addition, it seems you have a typo in the base class destructor.


问:
How to get the Child in Firebase Android?
I'm trying to perform login operation in my app using firebase my Users node is something like:

```<code>mUserCompounds.orderByChild("email").equalTo("test@gmail.com").addValueEventListener(new ValueEventListener() {
                    @Override
                    public void onDataChange(DataSnapshot dataSnapshot) {
                        System.out.println(dataSnapshot.getChildrenCount());                        }

                    @Override
                    public void onCancelled(DatabaseError databaseError) {

                    }
                });
</code>```

i want to get that complete object with which i have matched the name. so that

i can also compare password etc.
Thanks for help.

答:
First make a pojo class of User data .

```<code>Class User {
 String about;
 String email;
 String image;
 String name;
 String password;
 String pointsTotal;
 String totalTasksDone;
}
</code>```

Make getter setters and define constructors.

```<code>mUserCompounds.orderByChild("email").equalTo("test@gmail.com").addValueEventListener(new ValueEventListener() {
                @Override
                public void onDataChange(DataSnapshot dataSnapshot) {
                    if (dataSnapshot.exists()) {
                         //User already exists
                         User user1 = dataSnapshot.getValue(User.class);
                         System.out.println(user1.getPassword());
                       }
                  }

                @Override
                public void onCancelled(DatabaseError databaseError) {

                }
            });
</code>```

Body:
I'm trying to perform login operation in my app using firebase my Users node is something like:

mUserCompounds.orderByChild("email").equalTo("test@gmail.com").addValueEventListener(new ValueEventListener() {
                    @Override
                    public void onDataChange(DataSnapshot dataSnapshot) {
                        System.out.println(dataSnapshot.getChildrenCount());                        }

                    @Override
                    public void onCancelled(DatabaseError databaseError) {

                    }
                });

i want to get that complete object with which i have matched the name. so that

i can also compare password etc.
Thanks for help.

Body:
First make a pojo class of User data .

Class User {
 String about;
 String email;
 String image;
 String name;
 String password;
 String pointsTotal;
 String totalTasksDone;
}

Make getter setters and define constructors.

mUserCompounds.orderByChild("email").equalTo("test@gmail.com").addValueEventListener(new ValueEventListener() {
                @Override
                public void onDataChange(DataSnapshot dataSnapshot) {
                    if (dataSnapshot.exists()) {
                         //User already exists
                         User user1 = dataSnapshot.getValue(User.class);
                         System.out.println(user1.getPassword());
                       }
                  }

                @Override
                public void onCancelled(DatabaseError databaseError) {

                }
            });


问:
Symfony ResetType: reset dropdown selection
I added a "Reset Filter" button and it's perfectly doing what it promised, so whenever it's clicked, all the selected filters are reset.
However, there's one thing that's still bothering me, concering dropdowns I use for filtering. When something is selected in that dropdown and I hit the "reset" button, the dropdown still shows the selected values. Only when opening the dropdown, I see that there is actually nothing selected.
I added the following screenshot, to show what I mean. That's the situation AFTER I hit the "Reset filter" button, so the resetting of the dropdown worked (no value is selected) but it's still displaying "BR" as selected.. And if I would now select another value of that dropdown (e.g. CA) and then applied the filters both (BR and CA) would be selected..
So what I thought is, that I need an ajax that's reloading the page after I clicked "Reset filter"? or is there a javascript that's handling the reset? I'm kind of lost.

Btw. I'm using the bootstrap-multiselect.js for that dropdown!

```<code>      $('#document_filter_markets').multiselect({
    enableCaseInsensitiveFiltering: true, includeSelectAllOption: true, nonSelectedText: 'Select Markets',
    maxHeight: 200
  });
</code>```

Any ideas how to clear everything?

答:
I finally found an answer myself.

I added a reset-button:

```<code>  <input type="reset" id="resetter" class="btn-primary btn btn-xs" value="Reset All"/>
</code>```

and then added some javascript to that button to uncheck everything and then refresh the dropdown:

```<code>    $("#resetter").click(function () {
    $('option', $('#document_filter_markets')).each(function(element) {
    $(this).removeAttr('selected').prop('selected', false);
      });
      $("#document_filter_markets").multiselect('refresh');
});
</code>```

Hope it helps!

Body:
I added a "Reset Filter" button and it's perfectly doing what it promised, so whenever it's clicked, all the selected filters are reset.
However, there's one thing that's still bothering me, concering dropdowns I use for filtering. When something is selected in that dropdown and I hit the "reset" button, the dropdown still shows the selected values. Only when opening the dropdown, I see that there is actually nothing selected.
I added the following screenshot, to show what I mean. That's the situation AFTER I hit the "Reset filter" button, so the resetting of the dropdown worked (no value is selected) but it's still displaying "BR" as selected.. And if I would now select another value of that dropdown (e.g. CA) and then applied the filters both (BR and CA) would be selected..
So what I thought is, that I need an ajax that's reloading the page after I clicked "Reset filter"? or is there a javascript that's handling the reset? I'm kind of lost.

Btw. I'm using the bootstrap-multiselect.js for that dropdown!

      $('#document_filter_markets').multiselect({
    enableCaseInsensitiveFiltering: true, includeSelectAllOption: true, nonSelectedText: 'Select Markets',
    maxHeight: 200
  });

Any ideas how to clear everything?

Body:
I finally found an answer myself.

I added a reset-button:

  <input type="reset" id="resetter" class="btn-primary btn btn-xs" value="Reset All"/>

and then added some javascript to that button to uncheck everything and then refresh the dropdown:

    $("#resetter").click(function () {
    $('option', $('#document_filter_markets')).each(function(element) {
    $(this).removeAttr('selected').prop('selected', false);
      });
      $("#document_filter_markets").multiselect('refresh');
});

Hope it helps!


问:
Filter on Datatable using jquery
I am trying to implement excel type filter on data table similar to the following code. but the problem is this code give duplicates values in the search filter and it eliminates based on row index.

This also does not handle null cases and adds empty checkbox in the filter.

please let me know how we can eliminate duplicates and null cases.

Used code from this URL

// Code goes here

var arrayMap = {};

function showFilterOption(tdObject){
  var filterGrid = $(tdObject).find(".filter");

  if (filterGrid.is(":visible")){
    filterGrid.hide();
    return;
  }

  $(".filter").hide();

  var index = 0;
  filterGrid.empty();
  var allSelected = true;
  filterGrid.append('
<input id="all" type="checkbox" checked>Select All
');

  var $rows = $(tdObject).parents("table").find("tbody tr");

  $rows.each(function(ind, ele){
    var currentTd = $(ele).children()[$(tdObject).attr("index")];
    var div = document.createElement("div");
    div.classList.add("grid-item")
    var str = $(ele).is(":visible") ? 'checked' : '';
    if ($(ele).is(":hidden")){
      allSelected = false;
    }
    div.innerHTML = '<input type="checkbox" '+str+' >'+currentTd.innerHTML;
    filterGrid.append(div);
    arrayMap[index] = ele;
    index++;
  });

  if (!allSelected){
    filterGrid.find("#all").removeAttr("checked");
  }

  filterGrid.append('
<input id="close" type="button" value="Close"/><input id="ok" type="button" value="Ok"/>
');
  filterGrid.show();

  $gridItems.click(function(event){
    var chk = $(this).find("input[type='checkbox']");
    $(chk).prop("checked",!$(chk).is(":checked"));
  });

  $all.change(function(){
    var chked = $(this).is(":checked");
    filterGrid.find(".grid-item [type='checkbox']").prop("checked",chked);
  })

  filterGrid.click(function(event){
    event.stopPropagation();
  });

  return filterGrid;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><!DOCTYPE html>
<html>

  <head>
    <script data-require="jquery@2.0.3" data-semver="2.0.3" src="http://code.jquery.com/jquery-2.0.3.min.js"></script>
    <link rel="stylesheet" href="style.css" />
    <script src="script.js"></script>
  </head>

  <body>
    <table class="grid">
      <thead>
        <tr>
          <td index=0>Name
            <div class="filter"></div>
          </td>
          <td index=1>Address
            <div class="filter"></div>
            </td>
          <td index=2>City
            <div class="filter"></div>
          </td>
        </tr>
      </thead>
      <tbody>
        <tr>
          <td>first</td>
          <td>first add</td>
          <td>SDF dfd</td>
        </tr>
        <tr>
          <td>second</td>
          <td>second add</td>
          <td>SDF dfd</td>
        </tr>
        <tr>
          <td>third</td>
          <td>third add</td>
          <td>SDF dfd</td>
        </tr>
      </tbody>
    </table>
  </body>

</html></code>```

答:
you need to just add code for make unique your list of filter checkbox something like my file.just replace your js file with mine Hope it is same as you want

// Code goes here

$(document).ready(function(){

    $(".grid thead td").click(function(){
      showFilterOption(this);
    });

});

var arrayMap = {};

function showFilterOption(tdObject){
  var filterGrid = $(tdObject).find(".filter");

  if (filterGrid.is(":visible")){
    filterGrid.hide();
    return;
  }

  $(".filter").hide();

  var index = 0;
  filterGrid.empty();
  var allSelected = true;
  filterGrid.append('
<input id="all" type="checkbox" checked>Select All
');

  var $rows = $(tdObject).parents("table").find("tbody tr");

  var uniqueArr =[];
  $rows.each(function(ind, ele){
    var currentTd = $(ele).children()[$(tdObject).attr("index")];
    var div = document.createElement("div");
    div.classList.add("grid-item")
    var str = $(ele).is(":visible") ? 'checked' : '';
    if ($(ele).is(":hidden")){
      allSelected = false;
    }
    div.innerHTML = '<input type="checkbox" '+str+' >'+currentTd.innerHTML;
    if(!uniqueArr.includes(currentTd.innerHTML)){
      uniqueArr.push(currentTd.innerHTML);
      filterGrid.append(div);
    }
    arrayMap[index] = ele;
    index++;
  });

  if (!allSelected){
    filterGrid.find("#all").removeAttr("checked");
  }

  filterGrid.append('
<input id="close" type="button" value="Close"/><input id="ok" type="button" value="Ok"/>
');
  filterGrid.show();

  var $closeBtn = filterGrid.find("#close");
  var $okBtn = filterGrid.find("#ok");
  var $checkElems = filterGrid.find("input[type='checkbox']");
  var $gridItems = filterGrid.find(".grid-item");
  var $all = filterGrid.find("#all");

  $closeBtn.click(function(){
    filterGrid.hide();
    return false;
  });

  $okBtn.click(function(){
    filterGrid.find(".grid-item").each(function(ind,ele){
      if ($(ele).find("input").is(":checked")){
        $(arrayMap[ind]).show();
      }else{
        $(arrayMap[ind]).hide();
      }
    });
    filterGrid.hide();
    return false;
  });

  $checkElems.click(function(event){
    event.stopPropagation();
  });

  $gridItems.click(function(event){
    var chk = $(this).find("input[type='checkbox']");
    $(chk).prop("checked",!$(chk).is(":checked"));
  });

  $all.change(function(){
    var chked = $(this).is(":checked");
    filterGrid.find(".grid-item [type='checkbox']").prop("checked",chked);
  })

  filterGrid.click(function(event){
    event.stopPropagation();
  });

  return filterGrid;
}```

Title: Filter on Datatable using jquery

Body:
I am trying to implement excel type filter on data table similar to the following code. but the problem is this code give duplicates values in the search filter and it eliminates based on row index.

This also does not handle null cases and adds empty checkbox in the filter.

please let me know how we can eliminate duplicates and null cases.

Used code from this URL

// Code goes here

var arrayMap = {};

function showFilterOption(tdObject){
  var filterGrid = $(tdObject).find(".filter");

  if (filterGrid.is(":visible")){
    filterGrid.hide();
    return;
  }

  $(".filter").hide();

  var index = 0;
  filterGrid.empty();
  var allSelected = true;
  filterGrid.append('
<input id="all" type="checkbox" checked>Select All
');

  var $rows = $(tdObject).parents("table").find("tbody tr");

  $rows.each(function(ind, ele){
    var currentTd = $(ele).children()[$(tdObject).attr("index")];
    var div = document.createElement("div");
    div.classList.add("grid-item")
    var str = $(ele).is(":visible") ? 'checked' : '';
    if ($(ele).is(":hidden")){
      allSelected = false;
    }
    div.innerHTML = '<input type="checkbox" '+str+' >'+currentTd.innerHTML;
    filterGrid.append(div);
    arrayMap[index] = ele;
    index++;
  });

  if (!allSelected){
    filterGrid.find("#all").removeAttr("checked");
  }

  filterGrid.append('
<input id="close" type="button" value="Close"/><input id="ok" type="button" value="Ok"/>
');
  filterGrid.show();

  $gridItems.click(function(event){
    var chk = $(this).find("input[type='checkbox']");
    $(chk).prop("checked",!$(chk).is(":checked"));
  });

  $all.change(function(){
    var chked = $(this).is(":checked");
    filterGrid.find(".grid-item [type='checkbox']").prop("checked",chked);
  })

  filterGrid.click(function(event){
    event.stopPropagation();
  });

  return filterGrid;
}

<!DOCTYPE html>

    <link rel="stylesheet" href="style.css" />

          Name

          Address

          City

          first
          first add
          SDF dfd

          second
          second add
          SDF dfd

          third
          third add
          SDF dfd

Body:
you need to just add code for make unique your list of filter checkbox something like my file.just replace your js file with mine Hope it is same as you want

// Code goes here

$(document).ready(function(){

    $(".grid thead td").click(function(){
      showFilterOption(this);
    });

});

var arrayMap = {};

function showFilterOption(tdObject){
  var filterGrid = $(tdObject).find(".filter");

  if (filterGrid.is(":visible")){
    filterGrid.hide();
    return;
  }

  $(".filter").hide();

  var index = 0;
  filterGrid.empty();
  var allSelected = true;
  filterGrid.append('<div><input id="all" type="checkbox" checked>Select All</div>');

  var $rows = $(tdObject).parents("table").find("tbody tr");

  var uniqueArr =[];
  $rows.each(function(ind, ele){
    var currentTd = $(ele).children()[$(tdObject).attr("index")];
    var div = document.createElement("div");
    div.classList.add("grid-item")
    var str = $(ele).is(":visible") ? 'checked' : '';
    if ($(ele).is(":hidden")){
      allSelected = false;
    }
    div.innerHTML = '<input type="checkbox" '+str+' >'+currentTd.innerHTML;
    if(!uniqueArr.includes(currentTd.innerHTML)){
      uniqueArr.push(currentTd.innerHTML);
      filterGrid.append(div);
    }
    arrayMap[index] = ele;
    index++;
  });

  if (!allSelected){
    filterGrid.find("#all").removeAttr("checked");
  }

  filterGrid.append('<div><input id="close" type="button" value="Close"/><input id="ok" type="button" value="Ok"/></div>');
  filterGrid.show();

  var $closeBtn = filterGrid.find("#close");
  var $okBtn = filterGrid.find("#ok");
  var $checkElems = filterGrid.find("input[type='checkbox']");
  var $gridItems = filterGrid.find(".grid-item");
  var $all = filterGrid.find("#all");

  $closeBtn.click(function(){
    filterGrid.hide();
    return false;
  });

  $okBtn.click(function(){
    filterGrid.find(".grid-item").each(function(ind,ele){
      if ($(ele).find("input").is(":checked")){
        $(arrayMap[ind]).show();
      }else{
        $(arrayMap[ind]).hide();
      }
    });
    filterGrid.hide();
    return false;
  });

  $checkElems.click(function(event){
    event.stopPropagation();
  });

  $gridItems.click(function(event){
    var chk = $(this).find("input[type='checkbox']");
    $(chk).prop("checked",!$(chk).is(":checked"));
  });

  $all.change(function(){
    var chked = $(this).is(":checked");
    filterGrid.find(".grid-item [type='checkbox']").prop("checked",chked);
  })

  filterGrid.click(function(event){
    event.stopPropagation();
  });

  return filterGrid;
}


问:
oracle compare a date with the current date
I have to convert a column to a date and then compare the month of the column with the current month.

The column looks like this :

```<code>Date
0117
0217
0317
..
</code>```

I know how to convert it but cant compare it.

```<code>select  date,to_date(date, 'mmyy')
from table
where ????
</code>```

any ideas?

答:
You can convert the current date to a string and use string comparisons (which would allow you to use an index on your column):

```<code>SELECT *
FROM   your_table
WHERE  your_date_column = TO_CHAR( SYSDATE, 'MMYY' )
</code>```

or you can convert the column to a date and compare it (which would not use an index on your column but could use a function-based index, if you created one):

```<code>SELECT *
FROM   your_table
WHERE  TO_DATE( your_date_column, 'MMYY' ) = TRUNC( SYSDATE, 'MM' )
</code>```

Body:
I have to convert a column to a date and then compare the month of the column with the current month.

The column looks like this :

Date
0117
0217
0317
..

I know how to convert it but cant compare it.

select  date,to_date(date, 'mmyy')
from table
where ????

any ideas?

Body:
You can convert the current date to a string and use string comparisons (which would allow you to use an index on your column):

SELECT *
FROM   your_table
WHERE  your_date_column = TO_CHAR( SYSDATE, 'MMYY' )

or you can convert the column to a date and compare it (which would not use an index on your column but could use a function-based index, if you created one):

SELECT *
FROM   your_table
WHERE  TO_DATE( your_date_column, 'MMYY' ) = TRUNC( SYSDATE, 'MM' )


答:
If you're using Google Chrome, click the three-dot menu in the upper right corner and from the menu that drops down click "New incognito window". Then use the incognito window to connect to the Google Cloud console. Using incognito mode prevents the browser from reading your cookies, so it allows you to log in with a different account than the one you're logged into in the standard browser window.

If you're not using Chrome, pretty much all the major browsers offer an equivalent. Firefox also calls it "Incognito". IE and Edge call it "InPrivate".

Title: How to open ssh gcloud vm session from the browser to another account

Body:
I have a VM instance setup in Google Cloud. Most of the time I use gcloud tool to open ssh session from the terminal, it uses a user account on the VM with the same name as the account I am connecting from.

When, however, I open an SSH session from the browser it uses another user account on the VM, the one with the same name as the email I use to login to google cloud from the browser.

I would like to open the session from the browser and to log into the another account of my choice, the one I open from the terminal for instance.

How can I manage that?


问:
Finding duplicate values in a SQL table
It's easy to find duplicates with one field:

```<code>SELECT email, COUNT(email)
FROM users
GROUP BY email
HAVING COUNT(email) > 1
</code>```

So if we have a table

ID   NAME   EMAIL
1    John   asd@asd.com
2    Sam    asd@asd.com
3    Tom    asd@asd.com
4    Bob    bob@asd.com
5    Tom    asd@asd.com
```

This query will give us John, Sam, Tom, Tom because they all have the same email.

However, what I want is to get duplicates with the same email and name.

That is, I want to get "Tom", "Tom".

The reason I need this: I made a mistake, and allowed inserting duplicate name and email values. Now I need to remove/change the duplicates, so I need to find them first.

答: SELECT column_name,COUNT(*) FROM TABLE_NAME GROUP BY column1, HAVING COUNT(*) > 1;

Title: Finding duplicate values in a SQL table

Body:
It's easy to find duplicates with one field:

SELECT email, COUNT(email)
FROM users
GROUP BY email
HAVING COUNT(email) > 1

So if we have a table

ID   NAME   EMAIL
1    John   asd@asd.com
2    Sam    asd@asd.com
3    Tom    asd@asd.com
4    Bob    bob@asd.com
5    Tom    asd@asd.com

This query will give us John, Sam, Tom, Tom because they all have the same email.

However, what I want is to get duplicates with the same email and name.

That is, I want to get "Tom", "Tom".

The reason I need this: I made a mistake, and allowed inserting duplicate name and email values. Now I need to remove/change the duplicates, so I need to find them first.


问:
Spark Streaming with Python: Joining two stream with respect to a particular attribute
I am receiving two socket streams S1 and S2 with schemas S1 and S2 respectively.

I would like to join S1 and S2 with respect to attribute "a" using spark streaming. Following is my code:

```<code>    sc = SparkContext("local[3]", "StreamJoin")
    ssc = StreamingContext(sc, 1)

    S1 = ssc.socketTextStream("localhost", 9999)
    S2 = ssc.socketTextStream("localhost", 8085)

    # Create windowed stream
    wS1 = S1.window(10)
    wS2 = S2.window(1)

    wS1.flatMap(lambda line: line.split(",")).pprint()
    wS2.flatMap(lambda line: line.split(",")).pprint()

    # Perform join
    joinedStream = wS1.join(wS2)

    joinedStream.foreachRDD(lambda rdd: rdd.foreach(lambda x: print(x)))

    ssc.start()
    ssc.awaitTermination()
</code>```

Both S1 and S2 are comma separated.

Although the above code performs join, however with respect to complete row.

I am interested to join the two streams with respect to a particular attribute, in this case attribute 'a'. How I can achieve this?

Thanks a lot!

答:
The way join works in spark is it joins rdd rows based on a key, the key is the value at row[0]. So you can do:

```<code>wS1.flatMap(lambda line: line.split(",")).map(lambda x: (x[0], x)).pprint()
wS2.flatMap(lambda line: line.split(",")).map(lambda x: (x[0], x)).pprint()
</code>```

And then the join will be done based on the first element of the split list.

Docs reference:

https://spark.apache.org/docs/latest/api/python/pyspark.html?highlight=join#pyspark.RDD.join

Body:
I am receiving two socket streams S1 and S2 with schemas S1 and S2 respectively.

I would like to join S1 and S2 with respect to attribute "a" using spark streaming. Following is my code:

    sc = SparkContext("local[3]", "StreamJoin")
    ssc = StreamingContext(sc, 1)

    S1 = ssc.socketTextStream("localhost", 9999)
    S2 = ssc.socketTextStream("localhost", 8085)

    # Create windowed stream
    wS1 = S1.window(10)
    wS2 = S2.window(1)

    wS1.flatMap(lambda line: line.split(",")).pprint()
    wS2.flatMap(lambda line: line.split(",")).pprint()

    # Perform join
    joinedStream = wS1.join(wS2)

    joinedStream.foreachRDD(lambda rdd: rdd.foreach(lambda x: print(x)))

    ssc.start()
    ssc.awaitTermination()

Both S1 and S2 are comma separated.

Although the above code performs join, however with respect to complete row.

I am interested to join the two streams with respect to a particular attribute, in this case attribute 'a'. How I can achieve this?

Thanks a lot!

Body:
The way join works in spark is it joins rdd rows based on a key, the key is the value at row[0]. So you can do:

wS1.flatMap(lambda line: line.split(",")).map(lambda x: (x[0], x)).pprint()
wS2.flatMap(lambda line: line.split(",")).map(lambda x: (x[0], x)).pprint()

And then the join will be done based on the first element of the split list.

Docs reference:

https://spark.apache.org/docs/latest/api/python/pyspark.html?highlight=join#pyspark.RDD.join


问:
Recursively wrapping a regular expression with given text
For a given path, I wish to wrap a given regular expression in all files in that path or that path's sub-directories with some given text using standard Linux shell commands.

More specifically, wrap all my syslog commands with an assert command such as syslog(LOG_INFO,json_encode($obj)); becomes assert(syslog(LOG_INFO,json_encode($obj)));.

I thought the following might work, but received sed: -e expression #1, char 47: Invalid preceding regular expression error.

```<code>sed -i -E "s/(?<=syslog\()(.*)(?=\);)/assert(syslog(\1));/" /path/to/somewhere
</code>```

BACKUP INFO IN RESPONSE TO Wiktor Stribiżew's ANSWER

I've never used sed before.  Please confirm my understanding of your answer:

```<code>sed -i "s/syslog(\(.*\));/assert(syslog(\1));/g" /path/to/somewhere
</code>```

-i edit files in place.  One could first leave out to see on the screen what will be changed.

s   substitute text

The three /'s surrounding the pattern and replacement (i.e. /pattern/replacement/) are deliminator and can be any single character and not just /.

syslog(\(.*\));  The pattern with one placeholder.  Uses escaped parentheses.

assert(syslog(\1));  The replacement using escaped 1 (or 2, 3, etc) for replacement sub-strings.

g  Replace all and not just the first match.

Would sed -i "s/syslog(.*);/assert(&);/g" /path/to/somewhere work as well?

答:
If you need Perl-compatible regex constructs, you can use Perl (sic).

```<code>perl -i -pe 's/(?<=syslog\()(.*)(?=\);)/assert(syslog($1));/' /path/to/somewhere
</code>```

Regardless of this specific solution I switched to single quotes on the assumption that you are on a Unix-ish platform. Backslashes inside double quotes are pesky (sometimes you need to double them, sometimes not).

Perl prefers $1 over \1 in the replacement pattern, though the latter will also technically work.

Body:
For a given path, I wish to wrap a given regular expression in all files in that path or that path's sub-directories with some given text using standard Linux shell commands.

More specifically, wrap all my syslog commands with an assert command such as syslog(LOG_INFO,json_encode($obj)); becomes assert(syslog(LOG_INFO,json_encode($obj)));.

I thought the following might work, but received sed: -e expression #1, char 47: Invalid preceding regular expression error.

sed -i -E "s/(?<=syslog\()(.*)(?=\);)/assert(syslog(\1));/" /path/to/somewhere

BACKUP INFO IN RESPONSE TO Wiktor Stribiżew's ANSWER

I've never used sed before.  Please confirm my understanding of your answer:

sed -i "s/syslog(\(.*\));/assert(syslog(\1));/g" /path/to/somewhere

-i edit files in place.  One could first leave out to see on the screen what will be changed.

s   substitute text

The three /'s surrounding the pattern and replacement (i.e. /pattern/replacement/) are deliminator and can be any single character and not just /.

syslog(\(.*\));  The pattern with one placeholder.  Uses escaped parentheses.

assert(syslog(\1));  The replacement using escaped 1 (or 2, 3, etc) for replacement sub-strings.

g  Replace all and not just the first match.

Would sed -i "s/syslog(.*);/assert(&);/g" /path/to/somewhere work as well?

Body:
If you need Perl-compatible regex constructs, you can use Perl (sic).

perl -i -pe 's/(?<=syslog\()(.*)(?=\);)/assert(syslog($1));/' /path/to/somewhere

Regardless of this specific solution I switched to single quotes on the assumption that you are on a Unix-ish platform. Backslashes inside double quotes are pesky (sometimes you need to double them, sometimes not).

Perl prefers $1 over \1 in the replacement pattern, though the latter will also technically work.


问:
why the height of the out div is affected by vertical-align

in chrome, I thought the height of .wrap should be 24px.

it is 25px when the vertial-align is set to middle. can someone explain why?

answer in this article

body {
  line-height: 1.5;
}

.wrap {
  font-size:16px;  /* 16*1.5= 24 */
}

.btn {
  font-size: 14px;
  padding: 4px;
  line-height: 1;
  box-sizing: border-box;
  border: 1px solid blue;
  vertical-align: middle;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="wrap">
  <button class="btn">
    OK
  </button>
</div></code>```

答:
Please give block CSS for the btn

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

Why block and not inline-block??

Elements in the inline formatting context will cause white spaces from carriage returns and white-spaces in your HTML
The inline-block value is incredibly useful when wanting to control margin and padding on "inline" elements without the need to block and float them.  One problem that arrises when you use inline-block is that whitespace in HTML becomes visual space on screen.

This isn't a "bug" (I don't think). It's just the way setting elements on a line works. You want spaces between words that you type to be spaces right? The spaces between these blocks are just like spaces between words.

So thats OK!

Body:
in chrome, I thought the height of .wrap should be 24px.

it is 25px when the vertial-align is set to middle. can someone explain why?

answer in this article

body {
  line-height: 1.5;
}

.wrap {
  font-size:16px;  /* 16*1.5= 24 */
}

.btn {
  font-size: 14px;
  padding: 4px;
  line-height: 1;
  box-sizing: border-box;
  border: 1px solid blue;
  vertical-align: middle;
}

  <button class="btn">
    OK
  </button>

Body:
Please give block CSS for the btn

.btn { display: block;}

Why block and not inline-block??

Elements in the inline formatting context will cause white spaces from carriage returns and white-spaces in your HTML
The inline-block value is incredibly useful when wanting to control margin and padding on "inline" elements without the need to block and float them.  One problem that arrises when you use inline-block is that whitespace in HTML becomes visual space on screen.

This isn't a "bug" (I don't think). It's just the way setting elements on a line works. You want spaces between words that you type to be spaces right? The spaces between these blocks are just like spaces between words.

So thats OK!


问:
What is the difference between tf.estimator.Estimator and tf.contrib.learn.Estimator in TensorFlow
Some months ago, I used the tf.contrib.learn.DNNRegressor API from TensorFlow, which I found very convenient to use. I didn't keep up with the development of TensorFlow the last few months. Now I have a project where I want to use a Regressor again, but with more control over the actual model as provided by DNNRegressor. As far as I can see, this is supported by the Estimator API using the model_fn parameter.

But there are two Estimators in the TensorFlow API:

tf.contrib.learn.Estimator

tf.estimator.Estimator

Both provide a similar API, but are nevertheless slightly different in their usage. Why are there two different implementations and are there reasons to prefer one?

Unfortunately, I can't find any differences in the TensorFlow documentation or a guide when to use which of both. Actually, working through the TensorFlow tutorials produced a lot of warnings as some of the interfaces apparently have changed (instead of the x,y parameter, the input_fn parameter et cetera).

答:
Now there is this explicit statement in the docs:

Note: TensorFlow also includes a deprecated Estimator class at tf.contrib.learn.Estimator, which you should not use.

https://www.tensorflow.org/programmers_guide/estimators

For some reason it's not marked Deprecated in code.


问:
Extract vector images from Revit file
I was wondering if it's possible to extract Vector images from 2d views of revit files from forge api. I've used the following endpoint to achieve thumbnail of the views, but the thumbnails are very small (400 x 400)

https://developer.autodesk.com/en/docs/model-derivative/v2/reference/http/urn-thumbnail-GET/

Is there a way I can extract high resolution image, (preferably in vector formate that can be zoomed in or out) from a 2d View ?

Here's an example that I've tried:
https://jsfiddle.net/uLnvwyLa/

答:
Use the Viewer screenshot API and run a headless browser, no UI interaction needed and can run server-side. This will definitely produce the highest quality thumbnails that you can possibly obtain. Here are links that may be helpful:

https://github.com/GoogleChrome/puppeteer

http://adndevblog.typepad.com/cloud_and_mobile/2015/05/screenshot-extension-manager-for-the-viewer.html

See viewer.getScreenshot method:

```<code>this.viewer.getScreenShot(
 width, height, (blob) => {
</code>```

Talked with Autodesk support Philippe

Title: Extract vector images from Revit file

Body:
Use the Viewer screenshot API and run a headless browser, no UI interaction needed and can run server-side. This will definitely produce the highest quality thumbnails that you can possibly obtain. Here are links that may be helpful:

https://github.com/GoogleChrome/puppeteer

http://adndevblog.typepad.com/cloud_and_mobile/2015/05/screenshot-extension-manager-for-the-viewer.html

See viewer.getScreenshot method:

this.viewer.getScreenShot(
 width, height, (blob) => {

Talked with Autodesk support Philippe


问:
Edge Detection method better than Canny Edge detection
Is there an Edge Detection Method that performs significantly better than the Canny Edge Detector ??

答:
Hope this helps future reader

Active Canny: Edge Detection and Recovery with Open Active Contour Models

Here is an image showing its performance

Implementing it is a pain.
I'm trying to implement it using OpenCV and Python

Here's another paper I found.

Anisotropic Edge-Based Balloon Eikonal Active Contours


问:
Is it appropriate to use BackgroundWorker to do work that raises an event that I listen for
I'm new to Threading but I've read threads here on BackgroundWorker (BW) and mostly understand the material.  I suspect BW is not the correct solution but let me ask.
I have an object (GPS Emulator) that does its work in a loop mostly waiting (Thread.Sleep()) but occasionally raising an event that the UI listens for.  I want the UI to be responsive of course so it would be nice to put the work of the object in the background (as in gps.Start()).  On the UI I want to have the ability to Pause, Resume, and Stop the GPS.  I figured I could do this by setting appropriate flags in the GPS object that would break the loop running in the background.  What I don't understand is what happens to the events that are raised by the GPS.  The Thread that the event is raised on is not the Thread that is listening and so it seems, the UI can't respond correctly (as in painting the new GPS point on the UI).
Am I missing something wrt BW or is there a better (but still simple) way of doing this?</p>

答: So if I understood this right, the events fired by the GPS emulator result in an UI update and you want to be able to control the running of the GPS emulator from your UI. If this is indeed correct, I'd use the event WaitHandle constructs, either Auto or Manual based on the situation</p>


问:
Should we give new Token to each user when 2 users logins with same credentials in webapi?
what happens when 2 users logins with same credentials in token based authentication in webapi.
Should i give different token to each user or same token to both user.</p>

答:
It really depends on what you mean by "2 users".

It could be 2 different users or the same user connecting twice.
Given the fact those two users have used the same credentials, I think they should have the same token.


问:
TypeError: a float is required in python 3
I have a Python3 script as follows:

```<code>import math

Value_1 = float(input("what's the X1 value?")), float(input("what's the X2 value?"))

Value_2 = float(input("what's the Y1 value?")), float(input("what's the Y2 value?"))

equation =(math.sqrt(math.sqrt(Value_1)+ math.sqrt(Value_2)))

print (equation)
</code>```

with this output

what's the X1 value?3.0

what's the X2 value?12.0

what's the Y1 value?10.0

what's the Y2 value?110.0

Then the program return this error:

```<code>TypeError                                 Traceback (most recent call last)
<ipython-input-15-cc8d8b28ff67> in <module>()
      5
      6
----> 7 equation = float(math.sqrt(math.sqrt(Value_1)+ math.sqrt(Value_2)))
      8
      9 print (equation)

TypeError: a float is required
</code>```

I have tried to use all tips for other questions but error persist. Any tips?

答:
What is the problem?

By assigning to inputs to Value_1, separated by a comma, you are defining a tuple. As a short example for this:

```<code>In [1]: tup = 42, 23

In [2]: type(tup)
Out[2]: tuple
</code>```

However, the math.sqrt function requires a float value as input, not a tuple.

How to solve this

You can use tuple unpacking to keep the structure of your original post intact:

```<code>import math

# read in x and y value of the first point and store them in a tuple
point_1 = float(input("What is the x value of point 1? ")), float(input("What is the y value of point 1? "))
# read in x and y value of the second point and store them in a tuple
point_2 = float(input("What is the x value of point 2? ")), float(input("What is the y value of point 2? "))

# This is where the tuple unpacking happens.
# After this you have the x and y values
# of the points in their respective variables.
p1_x, p1_y = point_1
p2_x, p2_y = point_2

# At this point you can use point_1 when you need both x and y value of
# of the first point. If you need only the x or y value you can use the
# unpacked coordinates saved in p1_x and p1_y respectively.

x_diff = abs(p1_x - p2_x)
y_diff = abs(p1_y - p2_y)

distance = math.sqrt(math.pow(x_diff, 2) + math.pow(y_diff, 2))
print("Distance of {} and {} is {}".format(point_1, point_2, distance))
</code>```

As you can see above it can be helpful to save the information for the point as a tuple first and then use the unpacked coordinates at at a different point.

I hope this sheds some light on what happened.

Body:
I have a Python3 script as follows:

import math

Value_1 = float(input("what's the X1 value?")), float(input("what's the X2 value?"))

Value_2 = float(input("what's the Y1 value?")), float(input("what's the Y2 value?"))

equation =(math.sqrt(math.sqrt(Value_1)+ math.sqrt(Value_2)))

print (equation)

with this output

what's the X1 value?3.0

what's the X2 value?12.0

what's the Y1 value?10.0

what's the Y2 value?110.0

Then the program return this error:

TypeError                                 Traceback (most recent call last)
<ipython-input-15-cc8d8b28ff67> in <module>()
      5
      6
----> 7 equation = float(math.sqrt(math.sqrt(Value_1)+ math.sqrt(Value_2)))
      8
      9 print (equation)

TypeError: a float is required

I have tried to use all tips for other questions but error persist. Any tips?

Body:
What is the problem?

By assigning to inputs to Value_1, separated by a comma, you are defining a tuple. As a short example for this:

In [1]: tup = 42, 23

In [2]: type(tup)
Out[2]: tuple

However, the math.sqrt function requires a float value as input, not a tuple.

How to solve this

You can use tuple unpacking to keep the structure of your original post intact:

import math

# read in x and y value of the first point and store them in a tuple
point_1 = float(input("What is the x value of point 1? ")), float(input("What is the y value of point 1? "))
# read in x and y value of the second point and store them in a tuple
point_2 = float(input("What is the x value of point 2? ")), float(input("What is the y value of point 2? "))

# This is where the tuple unpacking happens.
# After this you have the x and y values
# of the points in their respective variables.
p1_x, p1_y = point_1
p2_x, p2_y = point_2

# At this point you can use point_1 when you need both x and y value of
# of the first point. If you need only the x or y value you can use the
# unpacked coordinates saved in p1_x and p1_y respectively.

x_diff = abs(p1_x - p2_x)
y_diff = abs(p1_y - p2_y)

distance = math.sqrt(math.pow(x_diff, 2) + math.pow(y_diff, 2))
print("Distance of {} and {} is {}".format(point_1, point_2, distance))

As you can see above it can be helpful to save the information for the point as a tuple first and then use the unpacked coordinates at at a different point.

I hope this sheds some light on what happened.


问:
Dynamically add CORS Mappings to Rest Controller at runtime

Hi! I am a beginner in Spring Boot. I have a simple Java Spring Boot Application which uses a Rest Controller. Some of the controller's endpoints are exposed to CORS requests. I've found out that it is possible to allow CORS requests by adding @CrossOrigin(origins ="..") annotations above the methods.

My problem is that I don't know all the origins at the moment and will have to add some of them later during the runtime of my Spring Boot Application.

Is it possible to have a method to manually add new origin-addresses to some endpoints of my Rest Controller? E.g. to have an endpoint in my Rest Controller that allows a particular user (e.g.Admin) to add new cors-origins to a rest endpoint? If yes: Please give a simple example.
</p>

答:
I think this is possible by implementing your own org.springframework.web.cors.CorsProcessor. Look at he implementation of org.springframework.web.filter.CorsFilter which can get configured with your custom CorsProcessor via method public void setCorsProcessor(CorsProcessor processor).

I woulod then suggest to implement your own CorsProcessor and handle in the method process your custom rules.

Or another option is to set your own CorsConfigurationSource in your Spring Security Config. e.g.

```<code>@Override
 protected void configure(HttpSecurity http) throws Exception {
        http.cors().configurationSource(new CustomConfigSource());
}
</code>```

The CorsConfigurationSource offers a method CorsConfiguration getCorsConfiguration(HttpServletRequest request); in which you can handle your specific CORS  Handling.

Body:
I think this is possible by implementing your own org.springframework.web.cors.CorsProcessor. Look at he implementation of org.springframework.web.filter.CorsFilter which can get configured with your custom CorsProcessor via method public void setCorsProcessor(CorsProcessor processor).

I woulod then suggest to implement your own CorsProcessor and handle in the method process your custom rules.

Or another option is to set your own CorsConfigurationSource in your Spring Security Config. e.g.

@Override
 protected void configure(HttpSecurity http) throws Exception {
        http.cors().configurationSource(new CustomConfigSource());
}

The CorsConfigurationSource offers a method CorsConfiguration getCorsConfiguration(HttpServletRequest request); in which you can handle your specific CORS  Handling.


问:
How can I use Nhibernate to retrieve data when the "WHERE IN()" have thousands of values? (too many parameters in the sql)
The problem: Nhibernate parses each value in the "WHERE IN()" sql as parameters and MS SQL server doesn't support enough parameters (over 2000).

I am using Nhibernate with Linq to retrive my data from the SQL server and I need to load alot of entities based on already known ID's.

My code looks something like this:

```<code>int[] knownIds = GetIDsFromFile();
var loadedEntities = _Repository.GetAll()
                                .Where(x => knownIds.Contains(x.ID))
                                .ToList();
</code>```

Which give an sql like this:

```<code>SELECT id, name FROM MyTable
WHERE id IN (1 /* @p0 */,2 /* @p1 */,3 /* @p2 */,4 /* @p3 */, 5 /* @p4 */)
</code>```

If there is too many values in knownIds, then this code will throw an Exception because of the many parameters that NHibernate uses.

I think the best solution would be if I could make NHibernate use only 1 parameter for the whole "WHERE IN()", but I don't know how to do this:

```<code>SELECT id, name FROM MyTable WHERE id IN (1, 2, 3, 4, 5 /* @p0 */)
</code>```

I'll be glad to hear any ideas of how to solve this - either by extending the LINQ provider or by other means. One solution is to simple do the query x times (knownIds.Count / 1000), but I rather want a generic solution which would work for all my entities.

I have tried looking at extending the LINQ provider by searching google and Stackoverflow, however I can't find a solution and I dont have any experience with either HQL or the treebuilder.
Here are a few of the sites I have been at:

Extending LINQ to Nhibernate provider, in combination with Dynamic LINQ problem

NHibernate LINQ provider extension

Sourcecode: NHibernate/Linq/Functions/QueryableGenerator.cs

UPDATE:
I know it ain't good practice by having so many values in the IN clause, but I don't know a better solution for what I want to do.

Consider a company where all the customers pay for the company's services one time each month. The company don't handle the payments itself, but have another company to collect the money. One time each month the company receives a file containing the status of these payments: if they have been paid or not. The file only contains the ID of the specific payment, and not the ID of the customer.
A company with 3000 monthly customers, will then make 3000 LogPayments each month, where the status need to be updated. After 1 year there will be around 36.000 LogPayments, so just loading them all doesn't seem like a good solution either.

MY SOLUTION:
Thanks for all the usefull answers. In the end I choosed to use a combination of the answers. For this specific case I did something like Fourth suggested, as that would increase performance a great deal. However I have allso implemented the generic method Stefan Steinegger suggested, because I like that I can do this, if that is what I really want. Besides, I don't want my program to crash with an exception, so in the future I will allso use this ContainsAlot-method as a safeguard.

答:
I faced the same problem in Oracle which doesn't allow more than 1000 elements inside IN condition as well. The error is: "ORA-01795: maximum number of expressions in a list is 1000". Here is my solution:

```<code>    //partition an IEnumerable into fixed size IEnumerables
    public static IEnumerable<IEnumerable<T>> Partition<T>(this IEnumerable<T> source, int partitionSize)
    {
        return source
            .Select((value, index) => new { Index = index, Value = value })
            .GroupBy(i => i.Index / partitionSize)
            .Select(i => i.Select(i2 => i2.Value));
    }

    public IEnumerable<T> Get(List<long> listOfIDs)
    {
        var partitionedList = listOfIDs.Partition(1000).ToList();
        List<ICriterion> criterions = new List<ICriterion>();
        foreach (var ids in partitionedList)
        {
            criterions.Add(Restrictions.In("Id", ids.ToArray()));
        }
        var criterion = criterions.Aggregate(Restrictions.Or);
        var criteria = session.CreateCriteria<T>().Add(criterion);
        return criteria.Future<T>();
    }
</code>```

First part is an extension method to IEnumerable, to partition a big list into fixed size lists. Second part uses NHibernate Criterions to dynamically generate multiple IN conditions to be later joined with OR conditions.

Body:
The problem: Nhibernate parses each value in the "WHERE IN()" sql as parameters and MS SQL server doesn't support enough parameters (over 2000).

I am using Nhibernate with Linq to retrive my data from the SQL server and I need to load alot of entities based on already known ID's.

My code looks something like this:

int[] knownIds = GetIDsFromFile();
var loadedEntities = _Repository.GetAll()
                                .Where(x => knownIds.Contains(x.ID))
                                .ToList();

Which give an sql like this:

SELECT id, name FROM MyTable
WHERE id IN (1 /* @p0 */,2 /* @p1 */,3 /* @p2 */,4 /* @p3 */, 5 /* @p4 */)

If there is too many values in knownIds, then this code will throw an Exception because of the many parameters that NHibernate uses.

I think the best solution would be if I could make NHibernate use only 1 parameter for the whole "WHERE IN()", but I don't know how to do this:

SELECT id, name FROM MyTable WHERE id IN (1, 2, 3, 4, 5 /* @p0 */)

I'll be glad to hear any ideas of how to solve this - either by extending the LINQ provider or by other means. One solution is to simple do the query x times (knownIds.Count / 1000), but I rather want a generic solution which would work for all my entities.

I have tried looking at extending the LINQ provider by searching google and Stackoverflow, however I can't find a solution and I dont have any experience with either HQL or the treebuilder.
Here are a few of the sites I have been at:

Extending LINQ to Nhibernate provider, in combination with Dynamic LINQ problem

NHibernate LINQ provider extension

Sourcecode: NHibernate/Linq/Functions/QueryableGenerator.cs

UPDATE:
I know it ain't good practice by having so many values in the IN clause, but I don't know a better solution for what I want to do.

Consider a company where all the customers pay for the company's services one time each month. The company don't handle the payments itself, but have another company to collect the money. One time each month the company receives a file containing the status of these payments: if they have been paid or not. The file only contains the ID of the specific payment, and not the ID of the customer.
A company with 3000 monthly customers, will then make 3000 LogPayments each month, where the status need to be updated. After 1 year there will be around 36.000 LogPayments, so just loading them all doesn't seem like a good solution either.

MY SOLUTION:
Thanks for all the usefull answers. In the end I choosed to use a combination of the answers. For this specific case I did something like Fourth suggested, as that would increase performance a great deal. However I have allso implemented the generic method Stefan Steinegger suggested, because I like that I can do this, if that is what I really want. Besides, I don't want my program to crash with an exception, so in the future I will allso use this ContainsAlot-method as a safeguard.

Body:
I faced the same problem in Oracle which doesn't allow more than 1000 elements inside IN condition as well. The error is: "ORA-01795: maximum number of expressions in a list is 1000". Here is my solution:

    //partition an IEnumerable into fixed size IEnumerables
    public static IEnumerable<IEnumerable<T>> Partition<T>(this IEnumerable<T> source, int partitionSize)
    {
        return source
            .Select((value, index) => new { Index = index, Value = value })
            .GroupBy(i => i.Index / partitionSize)
            .Select(i => i.Select(i2 => i2.Value));
    }

    public IEnumerable<T> Get(List<long> listOfIDs)
    {
        var partitionedList = listOfIDs.Partition(1000).ToList();
        List<ICriterion> criterions = new List<ICriterion>();
        foreach (var ids in partitionedList)
        {
            criterions.Add(Restrictions.In("Id", ids.ToArray()));
        }
        var criterion = criterions.Aggregate(Restrictions.Or);
        var criteria = session.CreateCriteria<T>().Add(criterion);
        return criteria.Future<T>();
    }

First part is an extension method to IEnumerable, to partition a big list into fixed size lists. Second part uses NHibernate Criterions to dynamically generate multiple IN conditions to be later joined with OR conditions.