source
sequence | text
stringlengths 99
98.5k
|
---|---|
[
"scifi.stackexchange",
"0000138966.txt"
] | Q:
80s Movie about kid gaining super intelligence
This was an 80s movie, the kid had super intelligence, was able to read barcodes and I think could some how ID people if they had arrest records. I also remember him being attacked by some sort of virus he got through the phone. I want to say it's because of some sort of accident with a computer.
A:
This could be The Computer Wore Tennis Shoes. The date isn't right, there is the 1969 version starring Kurt RusselL and the 1995 remake starring Kirk Cameron. An accident involving an electric shock makes him into a human computer. I don't remember details involving reading barcodes or computer virus. But it's a place to start.
|
[
"stackoverflow",
"0035010628.txt"
] | Q:
How can I get all the property-names of different nodes?
I want to get the effect like using Oracle.
For example,I hava two tables: Student, Tearcher. I can get all the column names of the two tables using SQL.
Now, I have two nodes: one with label Student with Name, age, sex, grade properties, another with label Teacher and Name, sex, salary properties.
Can I get all the property names with Neo4jClient using Cypher?
Thx Z.Tom
A:
You could use the keys function, if you want to get the properties by label you could match accordingly with a query like:
MATCH (a:Student) WITH keys(a) as k UNWIND k as x RETURN DISTINCT x
Will return all the existing properties on the nodes labeled as Student
Explanation:
The query matches all the nodes labeled as Student.
It extracts the property keys of the nodes using keys, then passes them by as arrays WITH
UNWIND catches the arrays and splits them into single rows
RETURN DISTINCT returns the property names as rows avoiding duplicates
Example
On C# using Neo4jClient the code to execute that query would be something like:
client = new GraphClient(new Uri(connString), dbuser, dbpass);
client.Connect();
var results = (Result)client.Cypher.Match("(a:Student)")
.With("keys(a) as k")
.Unwind("k as x")
.ReturnDistinct<Result>("x")
.Results.ToList()
Having a class setup for results like this:
public class Result
{
public string x { get; set; }
}
|
[
"stackoverflow",
"0029282665.txt"
] | Q:
Modify some attributs in a json files
i have this json schema:
{
"Stock": {
"Vehicule": [
{
"CodePvo": "...",
"SocieteNom": "...",
"SocieteAdresse": "...",
"SocieteCodePostal": "...",
"SocieteVille": "...",
"ContactsNoms": "...",
"ContactsTelephones": "...",
"ContactsTelephones2": "...",
"ContactsEmails": "...",
"IdentifiantVehicule": "10784615",
"ReferenceVehicule": "1078",
"NumeroPolice": "1232",
"StatutStock": "ST",
"Annee": "2007",
"Date1Mec": "23-10-2007",
"GenreLibelle": "Voitures",
"Marque": "KIA",
"Famille": "CEE'D SW",
"Version": "1.6 CRDI115 FAP ISG ACTIVE",
"Modele": "CEE'D SW 1.6 CRDI115 FAP ISG ACTIVE",
"EnergieLibelle": "Diesel",
"PuissanceFiscale": "6",
"PuissanceReelle": "115",
"Cylindree": "1582",
"NbPlaces": "5",
"NbPortes": "5",
"Kilometrage": "146013",
"KmGaranti": "Non garanti",
"Couleur": "GRIS",
"BoiteLibelle": "Manuelle",
"NbRapports": "6",
"PrixVenteTTC": "4990",
"PremiereMain": "FAUX",
"GarantieLibelle": "3 MOIS OU 5000 KM",
"CategorieLibelle": "Break",
"EquipementsSerieEtOption": "Peinture métal|Jack et Lecteur Audio Nomade|Prises USB|ABS|Airbags frontaux|Airbags latéraux avant|Airbags rideaux|Allumage des phares automatique|Arrêt et redémarrage auto. du moteur|Banquette 60/40|Clim automatique bi-zones|Filtre à particules|Fixations Isofix aux places arrières|Kit mains-libres Bluetooth|Ordinateur de bord|Pack Sérénité|Phares antibrouillard|Prise iPod|Prises USB, Jack et Lecteur Audio Nomade|Radar de recul|Radio CD MP3|Régulateur de vitesse|Répartiteur électronique de freinage|Roue de secours galette|Sièges cond et pass réglables en hauteur|Verrouillage auto. des portes en roulant|Verrouillage centralisé à distance|Verrouillage centralisé des portes|Vitres arrière électriques|Vitres avant électriques|Volant cuir|Volant réglable en profondeur et hauteur",
"Photos": "10784615_01_hd.jpg|10784615_02_hd.jpg|10784615_03_hd.jpg|10784615_04_hd.jpg|10784615_05_hd.jpg|10784615_06_hd.jpg|10784615_07_hd.jpg|10784615_08_hd.jpg|10784615_09_hd.jpg",
"Co2": "119",
"Poids": "0",
"PTAC": "0",
"PTRA": "0",
"ChargeUtile": "0",
"Longueur": "4490",
"Largeur": "1790",
"Empattement": "0",
"Hauteur": "1490",
"Volume": "0"
},
{
"CodePvo": "...",
"SocieteNom": "...",
"SocieteAdresse": "...",
"SocieteCodePostal": "...",
"SocieteVille": "...",
"ContactsNoms": "...",
"ContactsTelephones": "...",
"ContactsTelephones2": "...",
"ContactsEmails": "...",
"IdentifiantVehicule": "11454615",
"ReferenceVehicule": "1145",
"NumeroPolice": "1290",
"StatutStock": "ST",
"Annee": "2010",
"Date1Mec": "17-06-2010",
"GenreLibelle": "Voitures",
"Marque": "OPEL",
"Famille": "ASTRA",
"Version": "1.7 CDTI125 FAP COSMO",
"Modele": "ASTRA 1.7 CDTI125 FAP COSMO",
"EnergieLibelle": "Diesel",
"PuissanceFiscale": "7",
"PuissanceReelle": "125",
"Cylindree": "1686",
"NbPlaces": "5",
"NbPortes": "5",
"Kilometrage": "97667",
"KmGaranti": "Non garanti",
"Couleur": "MAUVE",
"BoiteLibelle": "Manuelle",
"NbRapports": "6",
"PrixVenteTTC": "9990",
"PremiereMain": "FAUX",
"GarantieLibelle": "3 MOIS OU 5000 KM",
"CategorieLibelle": "Berline",
"EquipementsSerieEtOption": "ABS|Aide au démarrage en côte|Aide au freinage d'urgence|Airbags frontaux|Airbags latéraux avant|Airbags rideaux|Allumage des phares automatique|Antipatinage|Banquette 1/3-2/3|Capteur de Pluie|Clim automatique bi-zones|Commandes du système audio au volant|ESP|Filtre à particules|Fixations Isofix aux places arrières|Frein stationnement électrique|Kit anti-crevaison|Ordinateur de bord|Phares antibrouillard|Porte-gobelets avant|Radio CD MP3|Régulateur de vitesse|Répartiteur électronique de freinage|Retroviseur intérieur electrochrome|Rétroviseurs électriques dégivrants|Siège conducteur réglable en hauteur|Système audio CD400|Verrouillage centralisé à distance|Verrouillage centralisé des portes|Vitres arrière électriques|Vitres avant électriques|Volant cuir|Volant réglable en profondeur et hauteur",
"Photos": "11454615_01_hd.jpg|11454615_02_hd.jpg|11454615_03_hd.jpg|11454615_04_hd.jpg|11454615_05_hd.jpg|11454615_06_hd.jpg",
"Co2": "119",
"Poids": "0",
"PTAC": "0",
"PTRA": "0",
"ChargeUtile": "0",
"Longueur": "4419",
"Largeur": "1814",
"Empattement": "0",
"Hauteur": "1510",
"Volume": "0"
},
{
"CodePvo": "...",
"SocieteNom": "...",
"SocieteAdresse": "...",
"SocieteCodePostal": "...",
"SocieteVille": "...",
"ContactsNoms": "...",
"ContactsTelephones": "...",
"ContactsTelephones2": "...",
"ContactsEmails": "...",
"IdentifiantVehicule": "11824615",
"ReferenceVehicule": "1182",
"NumeroPolice": "1323",
"StatutStock": "ST",
"Annee": "2011",
"Date1Mec": "08-03-2011",
"GenreLibelle": "Voitures",
"Marque": "PEUGEOT",
"Famille": "EXPERT FG",
"Version": "227 L1H1 HDI90 CONFORT",
"Modele": "EXPERT FG 227 L1H1 HDI90 CONFORT",
"EnergieLibelle": "Diesel",
"PuissanceFiscale": "5",
"PuissanceReelle": "90",
"Cylindree": "1560",
"NbPlaces": "3",
"NbPortes": "3",
"Kilometrage": "125000",
"KmGaranti": "Non garanti",
"Couleur": "BLANC",
"BoiteLibelle": "Manuelle",
"NbRapports": "5",
"PrixVenteTTC": "7490",
"PremiereMain": "FAUX",
"GarantieLibelle": "3 MOIS OU 5000 KM",
"CategorieLibelle": "GRAND UTILITAIRE",
"EquipementsSerieEtOption": "ABS|Airbag conducteur|Direction assistée|Verrouillage auto. des portes en roulant|Verrouillage centralisé des portes|Vitres avant électriques",
"Photos": "11824615_01_hd.jpg|11824615_02_hd.jpg|11824615_03_hd.jpg|11824615_04_hd.jpg|11824615_05_hd.jpg|11824615_06_hd.jpg|11824615_07_hd.jpg",
"Co2": "0",
"Poids": "0",
"PTAC": "0",
"PTRA": "0",
"ChargeUtile": "0",
"Longueur": "4805",
"Largeur": "1895",
"Empattement": "0",
"Hauteur": "1942",
"Volume": "0"
},
{
"CodePvo": "...",
"SocieteNom": "...",
"SocieteAdresse": "...",
"SocieteCodePostal": "...",
"SocieteVille": "...",
"ContactsNoms": "...",
"ContactsTelephones": "...",
"ContactsTelephones2": "...",
"ContactsEmails": "...",
"IdentifiantVehicule": "11844615",
"ReferenceVehicule": "1184",
"NumeroPolice": "1325",
"StatutStock": "ST",
"Annee": "2006",
"Date1Mec": "19-01-2006",
"GenreLibelle": "Voitures",
"Marque": "PEUGEOT",
"Famille": "607",
"Version": "2.7 V6 HDI SIGNATURE",
"Modele": "607 2.7 V6 HDI SIGNATURE",
"EnergieLibelle": "Diesel",
"PuissanceFiscale": "13",
"PuissanceReelle": "204",
"Cylindree": "2721",
"NbPlaces": "5",
"NbPortes": "5",
"Kilometrage": "174368",
"KmGaranti": "Non garanti",
"Couleur": "NOIR",
"BoiteLibelle": "Automatique",
"NbRapports": "5",
"PrixVenteTTC": "6490",
"PremiereMain": "FAUX",
"GarantieLibelle": "3 MOIS OU 5000 KM",
"CategorieLibelle": "Berline",
"EquipementsSerieEtOption": "ABS|Airbags latéraux arrière|Airbags latéraux avant|Airbags rideaux|Allumage des phares automatique|Antipatinage|Boite automatique|Capteur de Pluie|Chargeur CD|Clim automatique|Détecteur de sous-gonflage|Direction assistée|ESP|GPS Cartographique|Jantes Alu|Lampes Xenon|Ordinateur de bord|Peinture métal|Phares antibrouillard|Radar de recul AR|Radar de stationnement AV|Radio CD MP3|Régulateur-Limiteur de vitesse|Rétros élec. dégivrants et rabattables|Sellerie cuir|Verrouillage centralisé des portes|Vitres électriques avant",
"Photos": "11844615_01_hd.jpg|11844615_02_hd.jpg|11844615_03_hd.jpg|11844615_04_hd.jpg|11844615_05_hd.jpg|11844615_06_hd.jpg|11844615_07_hd.jpg|11844615_08_hd.jpg|11844615_09_hd.jpg|11844615_10_hd.jpg|11844615_11_hd.jpg",
"Co2": "223",
"Poids": "0",
"PTAC": "0",
"PTRA": "0",
"ChargeUtile": "0",
"Longueur": "4902",
"Largeur": "1835",
"Empattement": "0",
"Hauteur": "1442",
"Volume": "0"
},
{
"CodePvo": "...",
"SocieteNom": "...",
"SocieteAdresse": "...",
"SocieteCodePostal": "...",
"SocieteVille": "...",
"ContactsNoms": "...",
"ContactsTelephones": "...",
"ContactsTelephones2": "...",
"ContactsEmails": "...",
"IdentifiantVehicule": "12254615",
"ReferenceVehicule": "1225",
"NumeroPolice": "0",
"StatutStock": "ST",
"Annee": "2006",
"Date1Mec": "27-12-2006",
"GenreLibelle": "Voitures",
"Marque": "PEUGEOT",
"Famille": "407",
"Version": "1.6 HDI110 CONFORT PACK FAP",
"Modele": "407 1.6 HDI110 CONFORT PACK FAP",
"EnergieLibelle": "Diesel",
"PuissanceFiscale": "6",
"PuissanceReelle": "110",
"Cylindree": "1560",
"NbPlaces": "5",
"NbPortes": "4",
"Kilometrage": "125000",
"KmGaranti": "Non garanti",
"Couleur": "NOIR",
"BoiteLibelle": "Manuelle",
"NbRapports": "5",
"PrixVenteTTC": "5990",
"PremiereMain": "FAUX",
"GarantieLibelle": "3 MOIS OU 5000 KM",
"CategorieLibelle": "Berline",
"EquipementsSerieEtOption": "Kit mains-libres Bluetooth|Peinture métal|Régulateur-Limiteur de vitesse|Radio CD|ABS|Airbag de colonne de direction|Airbags frontaux|Airbags latéraux avant|Airbags rideaux|Antipatinage|Clim automatique|Direction assistée|ESP|Ordinateur de bord|Phares antibrouillard|Radio CD MP3|Verrouillage auto. des portes en roulant|Verrouillage centralisé des portes|Vitres électriques avant|Pack electrique|Radio CD",
"Photos": "12254615_01_hd.jpg|12254615_02_hd.jpg|12254615_03_hd.jpg|12254615_04_hd.jpg|12254615_05_hd.jpg|12254615_06_hd.jpg|12254615_07_hd.jpg|12254615_08_hd.jpg",
"Co2": "140",
"Poids": "0",
"PTAC": "0",
"PTRA": "0",
"ChargeUtile": "0",
"Longueur": "4676",
"Largeur": "1811",
"Empattement": "0",
"Hauteur": "1447",
"Volume": "0"
},
{
"CodePvo": "...",
"SocieteNom": "...",
"SocieteAdresse": "...",
"SocieteCodePostal": "...",
"SocieteVille": "...",
"ContactsNoms": "...",
"ContactsTelephones": "...",
"ContactsTelephones2": "...",
"ContactsEmails": "...",
"IdentifiantVehicule": "12394615",
"ReferenceVehicule": "1239",
"NumeroPolice": "1372",
"StatutStock": "ST",
"Annee": "2006",
"Date1Mec": "04-04-2006",
"GenreLibelle": "Voitures",
"Marque": "PEUGEOT",
"Famille": "607",
"Version": "2.7 V6 HDI GRIFFE FAP BAA",
"Modele": "607 2.7 V6 HDI GRIFFE FAP BAA",
"EnergieLibelle": "Diesel",
"PuissanceFiscale": "13",
"PuissanceReelle": "204",
"Cylindree": "2721",
"NbPlaces": "5",
"NbPortes": "4",
"Kilometrage": "145500",
"KmGaranti": "Non garanti",
"Couleur": "GRIS",
"BoiteLibelle": "Manuelle séquent.",
"NbRapports": "6",
"PrixVenteTTC": "7490",
"PremiereMain": "VRAI",
"GarantieLibelle": "3 MOIS OU 5000 KM",
"CategorieLibelle": "Berline",
"EquipementsSerieEtOption": "ABS|Airbags latéraux arrière|Airbags latéraux avant|Airbags rideaux|Allumage des phares automatique|Antipatinage|Capteur de Pluie|Chargeur CD|Clim automatique bi-zones|Détecteur de sous-gonflage|Direction assistée|ESP|GPS TV + Chargeur CD|Jantes Alu|Lampes Xenon|Ordinateur de bord|Peinture métal|Phares antibrouillard|Radar de recul AR|Radar de stationnement AV|Radio CD MP3|Régulateur-Limiteur de vitesse|Rétros élec. dégivrants et rabattables|Rétroviseur intérieur électrochrome|Sellerie cuir|Sièges avant chauffants|Sièges avant électriques|Verrouillage auto. des portes en roulant|Verrouillage centralisé des portes|Vitres arrière électriques|Vitres électriques avant|Volant réglable en profondeur et hauteur",
"Photos": "12394615_01_hd.jpg|12394615_02_hd.jpg|12394615_03_hd.jpg|12394615_04_hd.jpg|12394615_05_hd.jpg|12394615_06_hd.jpg|12394615_07_hd.jpg|12394615_08_hd.jpg|12394615_09_hd.jpg|12394615_10_hd.jpg|12394615_11_hd.jpg",
"Co2": "223",
"Poids": "0",
"PTAC": "0",
"PTRA": "0",
"ChargeUtile": "0",
"Longueur": "4902",
"Largeur": "1835",
"Empattement": "0",
"Hauteur": "1442",
"Volume": "0"
},
{
"CodePvo": "...",
"SocieteNom": "...",
"SocieteAdresse": "...",
"SocieteCodePostal": "...",
"SocieteVille": "...",
"ContactsNoms": "...",
"ContactsTelephones": "...",
"ContactsTelephones2": "...",
"ContactsEmails": "...",
"IdentifiantVehicule": "12644615",
"ReferenceVehicule": "1264",
"NumeroPolice": "1392",
"StatutStock": "ST",
"Annee": "2007",
"Date1Mec": "12-10-2007",
"GenreLibelle": "Voitures",
"Marque": "MERCEDES",
"Famille": "CLASSE B",
"Version": "180 CDI PACK DESIGN",
"Modele": "CLASSE B 180 CDI PACK DESIGN",
"EnergieLibelle": "Diesel",
"PuissanceFiscale": "6",
"PuissanceReelle": "109",
"Cylindree": "1991",
"NbPlaces": "5",
"NbPortes": "5",
"Kilometrage": "158900",
"KmGaranti": "Non garanti",
"Couleur": "GRIS",
"BoiteLibelle": "Manuelle",
"NbRapports": "6",
"PrixVenteTTC": "7490",
"PremiereMain": "FAUX",
"GarantieLibelle": "3 MOIS OU 5000 KM",
"CategorieLibelle": "Monospace",
"EquipementsSerieEtOption": "ABS|Airbags frontaux|Airbags latéraux avant|Allumage des phares automatique|Antipatinage|Capteur de Pluie|Clim manuelle|Direction assistée|ESP|Jantes Alu|Ordinateur de bord|Phares antibrouillard|Rétroviseurs électriques dégivrants|Verrouillage auto. des portes en roulant|Verrouillage centralisé des portes|Vitres electriques avant",
"Photos": "12644615_01_hd.jpg|12644615_02_hd.jpg|12644615_03_hd.jpg|12644615_04_hd.jpg|12644615_05_hd.jpg|12644615_06_hd.jpg|12644615_07_hd.jpg|12644615_08_hd.jpg",
"Co2": "146",
"Poids": "0",
"PTAC": "0",
"PTRA": "0",
"ChargeUtile": "0",
"Longueur": "4270",
"Largeur": "1777",
"Empattement": "0",
"Hauteur": "1604",
"Volume": "0"
},
{
"CodePvo": "...",
"SocieteNom": "...",
"SocieteAdresse": "...",
"SocieteCodePostal": "...",
"SocieteVille": "...",
"ContactsNoms": "...",
"ContactsTelephones": "...",
"ContactsTelephones2": "...",
"ContactsEmails": "...",
"IdentifiantVehicule": "12694615",
"ReferenceVehicule": "1269",
"NumeroPolice": "1396",
"StatutStock": "ST",
"Annee": "2008",
"Date1Mec": "30-01-2008",
"GenreLibelle": "Voitures",
"Marque": "PEUGEOT",
"Famille": "407",
"Version": "2.0 HDI136 PREMIUM BAA6 FAP",
"Modele": "407 2.0 HDI136 PREMIUM BAA6 FAP",
"EnergieLibelle": "Diesel",
"PuissanceFiscale": "9",
"PuissanceReelle": "136",
"Cylindree": "1997",
"NbPlaces": "5",
"NbPortes": "4",
"Kilometrage": "80788",
"KmGaranti": "Non garanti",
"Couleur": "GRIS",
"BoiteLibelle": "Manuelle séquent.",
"NbRapports": "6",
"PrixVenteTTC": "7490",
"PremiereMain": "FAUX",
"GarantieLibelle": "3 MOIS OU 5000 KM",
"CategorieLibelle": "Berline",
"EquipementsSerieEtOption": "Radar de recul AR|ABS|Airbag de colonne de direction|Airbags frontaux|Airbags latéraux avant|Airbags rideaux|Antipatinage|Clim automatique bi-zones|Direction assistée|ESP|Jantes Alu|Ordinateur de bord|Pack Visibilité|Phares antibrouillard|Radio CD MP3|Régulateur-Limiteur de vitesse|Verrouillage auto. des portes en roulant|Verrouillage centralisé des portes|Vitres arrière électriques|Vitres électriques avant",
"Photos": "12694615_01_hd.jpg|12694615_02_hd.jpg|12694615_03_hd.jpg|12694615_04_hd.jpg|12694615_05_hd.jpg|12694615_06_hd.jpg|12694615_07_hd.jpg|12694615_08_hd.jpg|12694615_09_hd.jpg|12694615_10_hd.jpg",
"Co2": "189",
"Poids": "0",
"PTAC": "0",
"PTRA": "0",
"ChargeUtile": "0",
"Longueur": "4676",
"Largeur": "1811",
"Empattement": "0",
"Hauteur": "1455",
"Volume": "0"
},
{
"CodePvo": "...",
"SocieteNom": "...",
"SocieteAdresse": "...",
"SocieteCodePostal": "...",
"SocieteVille": "...",
"ContactsNoms": "...",
"ContactsTelephones": "...",
"ContactsTelephones2": "...",
"ContactsEmails": "...",
"IdentifiantVehicule": "12844615",
"ReferenceVehicule": "1284",
"NumeroPolice": "1411",
"StatutStock": "ST",
"Annee": "1999",
"Date1Mec": "24-07-1998",
"GenreLibelle": "Voitures",
"Marque": "RENAULT",
"Famille": "SCENIC",
"Version": "1.9 D64 RTE",
"Modele": "SCENIC 1.9 D64 RTE",
"EnergieLibelle": "Diesel",
"PuissanceFiscale": "5",
"PuissanceReelle": "64",
"Cylindree": "1870",
"NbPlaces": "5",
"NbPortes": "5",
"Kilometrage": "335965",
"KmGaranti": "Non garanti",
"Couleur": "VERT",
"BoiteLibelle": "Manuelle",
"NbRapports": "5",
"PrixVenteTTC": "1500",
"PremiereMain": "FAUX",
"GarantieLibelle": "3 MOIS OU 5000 KM",
"CategorieLibelle": "Monospace",
"EquipementsSerieEtOption": "Jantes Alu|ABS|Airbag conducteur|Airbags frontaux|Direction assistée|Radio cassette",
"Photos": "12844615_01_hd.jpg|12844615_02_hd.jpg|12844615_03_hd.jpg|12844615_04_hd.jpg|12844615_05_hd.jpg|12844615_06_hd.jpg",
"Co2": "0",
"Poids": "0",
"PTAC": "0",
"PTRA": "0",
"ChargeUtile": "0",
"Longueur": "0",
"Largeur": "0",
"Empattement": "0",
"Hauteur": "0",
"Volume": "0"
},
{
"CodePvo": "...",
"SocieteNom": "...",
"SocieteAdresse": "...",
"SocieteCodePostal": "...",
"SocieteVille": "...",
"ContactsNoms": "...",
"ContactsTelephones": "...",
"ContactsTelephones2": "...",
"ContactsEmails": "...",
"IdentifiantVehicule": "12874615",
"ReferenceVehicule": "1287",
"NumeroPolice": "1414",
"StatutStock": "ST",
"Annee": "2008",
"Date1Mec": "04-04-2008",
"GenreLibelle": "Voitures",
"Marque": "PEUGEOT",
"Famille": "407",
"Version": "2.0 HDI136 EXECUTIVE FAP",
"Modele": "407 2.0 HDI136 EXECUTIVE FAP",
"EnergieLibelle": "Diesel",
"PuissanceFiscale": "8",
"PuissanceReelle": "136",
"Cylindree": "1997",
"NbPlaces": "5",
"NbPortes": "4",
"Kilometrage": "104369",
"KmGaranti": "Non garanti",
"Couleur": "GRIS FER",
"BoiteLibelle": "Manuelle",
"NbRapports": "6",
"PrixVenteTTC": "6490",
"PremiereMain": "VRAI",
"GarantieLibelle": "3 MOIS OU 5000 KM",
"CategorieLibelle": "Berline",
"EquipementsSerieEtOption": "ABS|Airbag de colonne de direction|Airbags frontaux|Airbags latéraux avant|Airbags rideaux|Antipatinage|Clim automatique bi-zones|Détecteur de sous-gonflage|Direction assistée|ESP|Ordinateur de bord|Pack Visibilité|Phares antibrouillard|Radio CD MP3|Régulateur-Limiteur de vitesse|Verrouillage auto. des portes en roulant|Verrouillage centralisé des portes|Vitres électriques avant",
"Photos": "12874615_01_hd.jpg|12874615_02_hd.jpg|12874615_03_hd.jpg|12874615_04_hd.jpg|12874615_05_hd.jpg|12874615_06_hd.jpg|12874615_07_hd.jpg",
"Co2": "155",
"Poids": "0",
"PTAC": "0",
"PTRA": "0",
"ChargeUtile": "0",
"Longueur": "4676",
"Largeur": "1811",
"Empattement": "0",
"Hauteur": "1447",
"Volume": "0"
},
....
it's possible to modify some attributs ?
i want to rename Marque to brand and Familleto model
i want to use a script bash (Ubuntu server) to do this modification.
A:
Using jq:
jq -M '.Stock.Vehicule[] = (.Stock.Vehicule[] | with_entries(.key |= (if . == "Marque" then "brand" else . end)) | with_entries(.key |= (if . == "Famille" then "model" else . end)))' filename.json
The important parts of the filter are the
with_entries(.key |= (if . == "Marque" then "brand" else . end))
with_entries(.key |= (if . == "Famille" then "model" else . end))
clauses that modify the keys of the objects they're applied to in the manner you wanted. The rest is
jq '.Stock.Vehicule[] = (.Stock.Vehicule[] | that filter)' filename.json
...which assigns to .Stock.Vehicule[] the filter-modified version of itself.
Addendum: I suppose you might, in this case, get away with sed:
sed 's/"Marque":/"brand":/;s/"Famille":/"model":/' filename.json
but JSON is not a format you want to edit with sed, or any other tool that treats its input as flat text. Benign whitespaces (and particular newlines) that don't invalidate the JSON will confuse such scripts. It is generally better to parse JSON with tools that understand JSON (like jq).
|
[
"mathematica.stackexchange",
"0000009375.txt"
] | Q:
Evaluation of Notebook chosen by FileNameSetter
Please consider the following:
I have created a GUI where I can choose the path of a notebook (which I need for later calculation) via
FileNameSetter[Dynamic[path1], "Open", {"Mathematica Notebook" -> {"*.nb"}}]
Now I would like Mathematica to evaluate the chosen notebook immediately after setting the path.
Has anyone an idea?
A:
I suspect there might be an easier way to do this, but you might use a variation of this example:
Module[{nb},
Button["Find and run",(
path1 = SystemDialogInput["FileOpen"];
nb = NotebookOpen[path1, Visible -> False];
SelectionMove[nb, All, Notebook];
SelectionEvaluate[nb];
NotebookClose[nb];
)]]
Update:
I initially couldn't get NotebookEvaluate[] To work inside a button, which led me to just use the method above, however a quick search and I found this answer by celtschk: How do I make NotebookEvaluate work inside Button? which means you can simplify the above and just have:
Button["Find and run",
NotebookEvaluate[path1 = SystemDialogInput["FileOpen"]]
,Method -> "Queued"]
|
[
"stackoverflow",
"0037686213.txt"
] | Q:
Upload image from URL to Firebase Storage
I'm wondering how to upload file onto Firebase's storage via URL instead of input (for example). I'm scrapping images from a website and retrieving their URLS. I want to pass those URLS through a foreach statement and upload them to Firebase's storage. Right now, I have the firebase upload-via-input working with this code:
var auth = firebase.auth();
var storageRef = firebase.storage().ref();
function handleFileSelect(evt) {
evt.stopPropagation();
evt.preventDefault();
var file = evt.target.files[0];
var metadata = {
'contentType': file.type
};
// Push to child path.
var uploadTask = storageRef.child('images/' + file.name).put(file, metadata);
// Listen for errors and completion of the upload.
// [START oncomplete]
uploadTask.on('state_changed', null, function(error) {
// [START onfailure]
console.error('Upload failed:', error);
// [END onfailure]
}, function() {
console.log('Uploaded',uploadTask.snapshot.totalBytes,'bytes.');
console.log(uploadTask.snapshot.metadata);
var url = uploadTask.snapshot.metadata.downloadURLs[0];
console.log('File available at', url);
// [START_EXCLUDE]
document.getElementById('linkbox').innerHTML = '<a href="' + url + '">Click For File</a>';}
Question what do I replace
var file = evt.target.files[0];
with to make it work with external URL instead of a manual upload process?
var file = "http://i.imgur.com/eECefMJ.jpg"; doesn't work!
A:
There's no need to use Firebase Storage if all you're doing is saving a url path. Firebase Storage is for physical files, while the Firebase Realtime Database could be used for structured data.
Example . once you get the image url from the external site this is all you will need :
var externalImageUrl = 'https://foo.com/images/image.png';
then you would store this in your json structured database:
databaseReference.child('whatever').set(externalImageUrl);
OR
If you want to actually download the physical images straight from external site to storage then this will require making an http request and receiving a blob response or probably may require a server side language ..
Javascript Solution : How to save a file from a url with javascript
PHP Solution : Saving image from PHP URL
A:
Hopefully this helps somebody else :)
// Download a file form a url.
function saveFile(url) {
// Get file name from url.
var filename = url.substring(url.lastIndexOf("/") + 1).split("?")[0];
var xhr = new XMLHttpRequest();
xhr.addEventListener("load", transferComplete);
xhr.addEventListener("error", transferFailed);
xhr.addEventListener("abort", transferCanceled);
xhr.responseType = 'blob';
xhr.onload = function() {
var a = document.createElement('a');
a.href = window.URL.createObjectURL(xhr.response); // xhr.response is a blob
a.download = filename; // Set the file name.
a.style.display = 'none';
document.body.appendChild(a);
a.click();
delete a;
if (this.status === 200) {
// `blob` response
console.log(this.response);
var reader = new FileReader();
reader.onload = function(e) {
var auth = firebase.auth();
var storageRef = firebase.storage().ref();
var metadata = {
'contentType': 'image/jpeg'
};
var file = e.target.result;
var base64result = reader.result.split(',')[1];
var blob = b64toBlob(base64result);
console.log(blob);
var uploadTask = storageRef.child('images/' + filename).put(blob, metadata);
uploadTask.on('state_changed', null, function(error) {
// [START onfailure]
console.error('Upload failed:', error);
// [END onfailure]
}, function() {
console.log('Uploaded',uploadTask.snapshot.totalBytes,'bytes.');
console.log(uploadTask.snapshot.metadata);
var download = uploadTask.snapshot.metadata.downloadURLs[0];
console.log('File available at', download);
// [START_EXCLUDE]
document.getElementById('linkbox').innerHTML = '<a href="' + download + '">Click For File</a>';
// [END_EXCLUDE]
});
// `data-uri`
};
reader.readAsDataURL(this.response);
};
};
xhr.open('GET', url);
xhr.send();
}
function b64toBlob(b64Data, contentType, sliceSize) {
contentType = contentType || '';
sliceSize = sliceSize || 512;
var byteCharacters = atob(b64Data);
var byteArrays = [];
for (var offset = 0; offset < byteCharacters.length; offset += sliceSize) {
var slice = byteCharacters.slice(offset, offset + sliceSize);
var byteNumbers = new Array(slice.length);
for (var i = 0; i < slice.length; i++) {
byteNumbers[i] = slice.charCodeAt(i);
}
var byteArray = new Uint8Array(byteNumbers);
byteArrays.push(byteArray);
}
var blob = new Blob(byteArrays, {type: contentType});
return blob;
}
function transferComplete(evt) {
window.onload = function() {
// Sign the user in anonymously since accessing Storage requires the user to be authorized.
auth.signInAnonymously().then(function(user) {
console.log('Anonymous Sign In Success', user);
document.getElementById('file').disabled = false;
}).catch(function(error) {
console.error('Anonymous Sign In Error', error);
});
}
}
function transferFailed(evt) {
console.log("An error occurred while transferring the file.");
}
function transferCanceled(evt) {
console.log("The transfer has been canceled by the user.");
}
A:
This answer is similar to @HalesEnchanted's answer but with less code. In this case it's done with a Cloud Function but I assume the same can be done from the front end. Notice too how createWriteStream() has an options parameter similar to bucket.upload().
const fetch = require("node-fetch");
const bucket = admin.storage().bucket('my-bucket');
const file = bucket.file('path/to/image.jpg');
fetch('https://example.com/image.jpg').then((res: any) => {
const contentType = res.headers.get('content-type');
const writeStream = file.createWriteStream({
metadata: {
contentType,
metadata: {
myValue: 123
}
}
});
res.body.pipe(writeStream);
});
|
[
"stackoverflow",
"0006089642.txt"
] | Q:
qpainter painting alternatives (performance sucks on Mac)
I have a class which displays waveform data of audiofiles in a QWidget (see screenshot of the widget below, back then i still used a gradient, which caused poor performance).
The audio data is painted in the paintEvent directly on the widget using multiple calls to QPainter::drawLine (the minimum amount of calls to QWidget::drawLine is equivalent to the width of the widget => at least one line for each x coordinate).
While the approach works quite well on Windows (a paintEvent in fullscreen takes around ~4ms), the performance is 4-5 times worse when the program is run under MacOS.
The performance of the painting is important for fluid scrolling of the displayed data.
So my question is, does anyone know a faster alternative to QPainter.drawLine to paint lines (platform dependant solutions might be ok, as long as they can be used in a paintEvent), or is there a way to speed up scrolling, some kind of buffering etc ?
A:
The current version (4.7.x) of Qt uses Core Graphics backend for painting. It can be slow at times as you found out. On Windows, it uses a software renderer which has really good performances.
My suggestion is to not paint on the passed painter directly in your paint event. Instead, create a QImage the same size as your widget paint area and paint on it. This will use the software renderer which is much faster. Then plot the QImage onto the painter when needed.
A:
Use OpenGL and QGLWidget if you want to draw really fast.
|
[
"math.stackexchange",
"0002963328.txt"
] | Q:
Convex polyhedron: Show $B$ is an extremal point and $A$ is not
Given is the convex polyhedron $P:= \left\{\begin{pmatrix} x\\ y
\end{pmatrix} \in \mathbb{R}^2 \mid 5x-2y \leq 7, x \geq 0, y \geq
0\right\}$. Show that $A = \begin{pmatrix} 3\\ 4 \end{pmatrix}$ is
not an extreme point in $P$ and that the point $B = \begin{pmatrix}
1.4\\ 0 \end{pmatrix}$ is an extreme point.
I have a definition about an extreme point from my book: Point $x$ of a convex set $S \subseteq R^n$ is called an extreme point of $S$ if there is no $u \in R^n$, $u \neq 0_n$ such that there is an $\varepsilon > 0$ with $x+\varepsilon u \in S$ and $x-\varepsilon u \in S$
So I'm not sure if the following counts as "Show" but graphically, $P$ is a triangle where $A$ is an interior point of $5x-2y = 7$ and if you choose $u=(2,5)$ and $\varepsilon$ small enough such that you have that $x + \varepsilon u$ and $x - \varepsilon u$ on $5x-2y=7$. Thus $A$ cannot be an extreme point in $P$.
And $B$ is an extreme point in $P$ because it is a vertex and there is no section in $P$ that contains $B$ in the interior.
I'm not sure if it's correct like that?
A:
Suppose on the contrary that such $u \ne 0$ exists for point $B$, then
$$5(1.4+ \epsilon u_1)-2(0 +\epsilon u_2) \le 7\tag{1}$$
$$5(1.4- \epsilon u_1)-2(0 -\epsilon u_2) \le 7\tag{2}$$
$$\epsilon u_2 \ge 0\tag{3}$$
$$-\epsilon u_2 \ge 0\tag{4}$$
From $(3)$ and $(4)$, we conclude that $u_2=0.$
Hence now, we have $$7+5\epsilon u_1 \le 7 \iff \epsilon u_1 \le 0$$
$$7-5\epsilon u_1 \le 7 \iff \epsilon u_1 \ge 0$$
whcih again enable us to conclude that $u_1 = 0$ which is a contradiction.
Remark for your attempt for point $A$:
It would be better if you can state clearly how small do you want to choose your $\epsilon$ to be.
|
[
"pt.stackoverflow",
"0000378948.txt"
] | Q:
Como inciar um processamento no spring-boot após injetar todos os beans e antes de começar a ouvir eventos externos?
Estou criando uma aplicação em Spring-Boot que para mim é crítico ela recuperar seu ponto de processamento anterior antes de começar a receber novas requisições.
Para tal, eu tenho uma tabela chamada PROCESSOS que guarda um ID único, o seu estágio de processamento (enfileirado, processando, concluído, etc), um ponteiro para onde está o dado sendo processado e outras informações sem relevância pra essa questão.
Para recuperar os processos que pararam no meio do caminho, eu faço a seguinte consulta no método List<Integer> recuperaBreakpoint():
SELECT id, 1 as type
FROM PROCESSOS
WHERE estagio_id != 'QUEUED' AND
(estagio_id NOT LIKE 'FINISHED%' COLLATE NOCASE AND
estagio_id NOT LIKE 'FAILED%' COLLATE NOCASE AND
estagio_id NOT LIKE 'CANCELED%' COLLATE NOCASE)
UNION ALL
SELECT id, 2 as type
FROM PROCESSOS WHERE estagio_id = 'QUEUED'
ORDER BY type, id
E ela me retorna o que eu quero na ordem que eu quero:
o retorno contém todos os processos não terminados/cancelados/falhos
priorizo no retorno quem já começou algum processamento
só então coloco os processos que foram apenas enfileirados (QUEUED), porém não sofreram nenhum processo ainda
Em tese, após recuperar esses processos, seria só delegar a alguma thread executora disponível (ou colocar no pool de processos a serem executados, no caso de não ter executores disponíveis). Eu faço isso através da função void executaProcesso(int idProcesso), que vai se encarregar de delegar aos exeutores/enfileirar as requisições perfeitamente.
A questão é:
Como, em Spring-Boot, faço para resgatar esses valores e dar continuidade ao processo no início da aplicação porém antes de começar a responder requisições externas?
Em outras palavras, como fazer recuperaBreakpoint().stream().forEachOrdered(this::executaProcesso) assim que o Spring-Boot estiver pronto pra rodar?
A:
Fala Jefferson,
Você pode realizar isso utilizando a annotation @EventListener, ela atua como listener para executar certo método dependendo do evento de inicialização gerado.
Os eventos derivam de ApplicationEvent, podendo ser utilizados os SpringApplicationEvent ou ApplicationContextEvent
Basta você colocar a annotation no método e indicar o evento em que gostaria de executar o código:
@EventListener(ContextRefreshedEvent.class)
public void warmup() {
System.out.println("Código executado logo após a aplicação ser startada");
}
Eu recomendo você utilizar o evento ContextRefreshedEvent porque ele é executado antes da aplicação começar a aceitar requests (os request passam a ser aceitos após a emissão do evento ApplicationReadyEvent).
|
[
"space.stackexchange",
"0000032150.txt"
] | Q:
Could a ball of water stay in orbit?
Could a water bubble (spherical occlusion of water in air or vacuum) similar to the one in the picture below remain in Earth orbit without evaporating, dispersing, or disintegrating? Assume the orbit is high enough (high LEO or MEO) so that re-entry is not the limiting factor.
Is there a range of sizes that would be suitable; is there a "too small" or "too large" to remain stable?
Would it likely remain liquid, or would it freeze?
Assuming the water was originally pure and potable, would it eventually become toxic or unsuitable for drinking as a result of being in Earth orbit?
If a time limit is necessary for the answer, let's say we'd like it to remain stable, and ideally drinkable, for 100 years.
A:
The ball of water in that picture is in orbit; it's just surrounded by (presumably) the ISS.
But a ball of water like that definitely cannot survive in the vacuum of space. Below a certain pressure, water can only be water vapor or ice. So a ball like that would immediately start to boil if it were surrounded by a vacuum. The water vapor would quickly disperse and there would be nothing there.
It would not become toxic. If it were kept in a container to keep it from evaporating, it would just be water.
A giant, moon-sized ball of water is a whole different story. Gravity would hold it together. There would be an atmosphere of water vapor above an ocean of water that extended all the way through. In the middle, the pressure would be so great that its properties would change. [Note added later: After writing this I believe I read that the pressure at the center of a Moon-sized ball of water would not be great enough to lead to one of the special kinds of ice that exist at high pressures. So its properties might not actually change.]
This is all assuming it's close enough to the sun to remain liquid. Some of the moons in the outer solar system are mostly ice, and at least Enceladus (around Saturn) and Europa (around Jupiter) have large oceans under the ice.
|
[
"stackoverflow",
"0061723412.txt"
] | Q:
Match partial text in a div and if it matches text in another div then show a span - jquery and javascript
I need to show the quantity in stock of a product if there is an out of stock message for it:
<div class="OutOfStockMessage">Sorry, Avocado is not available in the quantity that you selected. Please select a lower quantity to be able to place this order.</div>
<div class="ItemDecription">Avocado<span class="Quantity" style="display:none"> 16 pieces in stock</span></div>
<div class="ItemDecription">Tomato<span class="Quantity" style="display:none"> 97 pieces in stock</span></div>
<div class="ItemDecription">Mushroom<span class="Quantity" style="display:none"> 217 pieces in stock</span></div>
I tried this jQuery however it only works with an exact text match and not with a partial text match:
if ( $(".OutOfStockMessage").text() == $(".ItemDecription").text() ) {
$(".Quantity").show();
}
Here is the Fiddle: https://jsfiddle.net/8jmpnwuy/
When .OutOfStockMessage contains the word 'Avocado' plus other words then I need the span inside of the div which contains the word 'Avocado' to show.
A:
You can use .filter() function to find all itemdescription divs with partial text matching OutOfStockMessage message text.
You can then find the immediate span elements in these sets and show them. I would suggest using a class selector instead of immediate child selector. This makes it less error prone to DOM changes
var stockMessageTxt= $(".OutOfStockMessage").text();
var $itemDescrptnToShow = $(".ItemDecription").filter(function(){
return stockMessageTxt.includes($(this).clone()
.children() //select all the children
.remove() //remove all the children
.end() //again go back to selected element
.text());
});
$('.Quantity', $itemDescrptnToShow).show();
Working Demo
|
[
"stackoverflow",
"0053671113.txt"
] | Q:
How to change jaxb model for add inner list of elements?
I use spring for creation rest-controller and jaxb lib for exchangin with client xml - elements, so, my model are Users, User and Property.
Users contains list of users, every user contains list of properies. To create Users with user-list elements - it works, but can't to create inner property-list for user elements.
My models are:
@XmlRootElement(name = "Users")
@NoArgsConstructor
@AllArgsConstructor
@Getter
@Setter
@XmlAccessorType(XmlAccessType.FIELD)
public class Users {
@XmlElement(name = "User")
private List<User> users;
@XmlElement(name = "UserError")
private UserError error;
}
@Getter
@Setter
@NoArgsConstructor
@AllArgsConstructor
@XmlRootElement(name = "User")
@XmlAccessorType(XmlAccessType.FIELD)
public class User implements Serializable {
@XmlElement(name = "Id")
private String id;
@XmlElement(name = "Name")
private String name;
@XmlElement(name = "Property")
private List<Property> properties;
}
@Getter
@Setter
@NoArgsConstructor
@XmlRootElement(name = "Property")
@AllArgsConstructor
@XmlAccessorType(XmlAccessType.FIELD)
public class Property implements Serializable {
@XmlElement(name = "passport")
private String passport;
@XmlElement(name = "age")
private String age;
}
How to change jaxb model for change xml from:
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<Users>
<User>
<Id>fff</Id>
<Name>Alex</Name>
<Property>
<Name>passport</Name>
<Value>111-222</Value>
</Property>
<Property>
<Name>car</Name>
<Value>bmv</Value>
</Property>
</User>
</Users>
To this view presentation
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<Users>
<User>
<Id>fff</Id>
<Name>Alex</Name>
<Properties>
<Property>
<Name>passport</Name>
<Value>111-222</Value>
</Property>
<Property>
<Name>car</Name>
<Value>bmv</Value>
</Property>
</Properties>
</User>
</Users>
A:
It is easy. Just add an @XmlElementWrapper annotation to the definition of
the Java variable properties:
@XmlElementWrapper(name = "Properties")
@XmlElement(name = "Property")
private List<Property> properties;
This will add <Properties>...</Properties> around the sequence of <Property>...</Property> elements.
|
[
"stackoverflow",
"0047434416.txt"
] | Q:
Unable to tap the link after tap on Allow button of permission alert in Appium?
I'm automating an Android App using Appium. The issue I'm facing is it doesn't perform any action after tabbing on allow button of Contact Access Permission as shown in below Image :
I've tried below code for the same :
@Test
public void doLogin()
{
driver.findElement(By.id("com.rawalinfocom.rcontact:id/text_next")).click();
// Clicks on Allow Button
driver.findElement(By.id("com.android.packageinstaller:id/permission_allow_button")).click();
// Clicks on Skip link
driver.findElement(By.id("com.rawalinfocom.rcontact:id/text_skip")).click();
driver.findElement(By.id("com.rawalinfocom.rcontact:id/checkbox_terms_conditions")).click();
driver.findElement(By.id("com.rawalinfocom.rcontact:id/button_get_started")).click();
driver.findElement(By.id("com.rawalinfocom.rcontact:id/input_number")).sendKeys("9422307801");
driver.findElement(By.id("com.rawalinfocom.rcontact:id/button_submit")).click();
driver.findElement(By.id("com.rawalinfocom.rcontact:id/input_enter_password")).sendKeys("1234");
driver.findElement(By.id("com.rawalinfocom.rcontact:id/button_login")).click();
System.out.print("Login Success");
}
I'm newbie in Appium. How can I find the missing thing?
A:
I'm able to handle the popup by setting up below capabilities :
capabilities.setCapability("autoGrantPermissions", "true");
capabilities.setCapability("autoAcceptAlerts", "true");
In this case it doesn't show the popup the permission set always granted.
|
[
"stackoverflow",
"0030748395.txt"
] | Q:
How to create virtual folders using php?
I am using php with aws elasticbeanstalk.
I want to create folder that accept this url :
www.example.com/481818
where 481818 present an id that is changed.
so i want to create file that accept every request form this structure www.example.com/integer. and fetch the id.
i don't know how to create this file.
I can do it with this url : www.example.com/?id=4545454 . but I don't want this url structure.
thank you
A:
Put this in you .htaccess file
<IfModule mod_rewrite.c>
RewriteEngine on
RewriteRule ^([0-9]+)$ index.php?id=$1 [NC,L]
</IfModule>
It should do what you want, I didn't use elastic-beanstalk before, hopes I can help you.
|
[
"stackoverflow",
"0006037532.txt"
] | Q:
Creating editable HTML tables with Django
I'm trying to create a Django app where the user can make a list of movies. Each time the user logs in, their list of movies will be presented to them in a table. The table will have three columns: one for the movie's name, one for the genre, and another that will contain delete buttons that will allow the user to delete the row corresponding to the button. The user can add rows to the table by filling in a textbox with the name of the movie, and selecting a genre from a drop down menu, and then pressing an "Add" button. The "Add" and "Delete" buttons are the only way by which the user can edit the table.
Is there any Django shortcuts to creating such an editable table? I thought this might be something that is appropriate for formsets, but I can't figure out how to do it. Also, it has been difficult to google "Django tables" as the results seem to be about database tables.
This is the model that I am currently trying to use:
class MovieList(models.Model):
user = models.ForeignKey(User)
movie = models.ForeignKey(Movie)
class Movie(models.Model):
genre = models.ForeignKey(Genre)
name = models.CharField(max_length=300)
class Genre(models.Model):
name = models.CharField(max_length=200)
Any help would be very much appreciated.
A:
There are several ways you can solve this. Though it doesn't really use a shortcut i can't see what's wrong about rendering the table by a standard view and a attach a form for entering new entries to it.
If you are looking for a shortcut and some additional convenience django-tables might be for you.
Of course you could use jQuery to make the process even more dynamic so that people can add and delete items without reloading the whole page: Something similar to Django's dynamic inlines in the admin. If you decide to take this route you should take a closer look a django-dynamic-formsets or at one of the several grid-plugins for jQuery. jqGrid to name one.
|
[
"stackoverflow",
"0005929886.txt"
] | Q:
selecting date where date can be null
I have an object that looks like this:
public class MyObject
{
public Nullable<DateTime> SpecificDate {get;set;}
....other properties
}
I'm writing a dynamic query that receive this object as a parameter and where I may or may not need the SpecificDate:
if (condition){
TheQuery = from....
where x.AppointDate.Date == TheObject.SpecificDate.Date
}
However, when I write TheObject.SpecificDate. I'm not getting the intellisense to choose the .Date property.
Any idea why?
Thanks.
A:
You need to write TheObject.SpecificDate.Value.Date.
However, be careful because if the date is null this will throw. You might want to check that TheObject.SpecificDate != null first.
|
[
"academia.stackexchange",
"0000077712.txt"
] | Q:
Given the traditional ACM copyright license, is it legal to publish the paper on ResearchGate?
The ACM license states
(iii) Post the Accepted Version of the Work on (1) the Author's home
page, (2) the Owner's institutional repository, (3) any repository
legally mandated by an agency funding the research on which the Work
is based, and (4) any non-commercial repository or aggregation that
does not duplicate ACM tables of contents, i.e., whose patterns of
links do not substantially duplicate an ACM-copyrighted volume or
issue. Non-commercial repositories are here understood as repositories
owned by non-profit organizations that do not charge a fee for
accessing deposited articles and that do not sell advertising or
otherwise profit from serving articles.
Does this (somehow) include ResearchGate?
A:
No. Researchgate is a for-profit organization that makes money from ads and job adverts. See for instance http://osc.universityofcalifornia.edu/2015/12/a-social-networking-site-is-not-an-open-access-repository/.
Also, if you share your paper there, the Researchgate TOS state that you, not them, have to cover all the legal costs in case they get sued (Article 3, comma 5).
|
[
"stackoverflow",
"0060619389.txt"
] | Q:
Why does std::list::front result change after creating a new list?
In the following code, why does list_front change after calling gen_list a second time? gen_list is creating a new list, how does that change a previous list head?
#include <iostream>
#include <list>
std::list<int> gen_list()
{
static int s_count = 0;
std::list<int> result;
for (int i = 0; i < 5; i++)
{
result.push_back(s_count++);
}
return result;
}
int main()
{
const auto& list_front = gen_list().front();
std::cout<<list_front<<"\n";
gen_list();
std::cout<<list_front<<"\n";
}
result:
0
9
Demo
A:
You need to bind to the temporary std::list<int> returned by gen_list():
const auto& list = gen_list();
const auto& list_front = list.front();
otherwise, the std::list<int> will be destroyed at the end of the expression and you'll have a dangling reference. Any use of the dangling reference makes your program have undefined behavior.
|
[
"stackoverflow",
"0026697727.txt"
] | Q:
What does "Error in namespaceExport(ns, exports) : undefined exports" mean?
When building a package, I got the error
Error in namespaceExport(ns, exports) :
undefined exports: FooBarBaz
What does this mean, and how do I fix it?
A:
This error occurs when you try to export an object that doesn't exist. That is, the package NAMESPACE file contains the line
export(FooBarBaz)
but FooBarBaz doesn't exist in the package.
One case where this error can occur is when you are trying to create a common help page for several functions using roxygen2. In the example below, f and g are related functions to be documented in the WidgetUtils page.
#' Widget-related functions
#'
#' Utility functions to assist working with widgets.
#' @param x An input.
#' @return A value.
#' @name WidgetUtils
#' @export
NULL
#' @rdname WidgetUtils
#' @export
f <- function(x)
{
x + 1
}
#' @rdname WidgetUtils
#' @export
g <- function(x)
{
x - 1
}
The mistake in this code chunk is the inclusion of the @export tag in the WidgetUtils roxygen block. This tells roxygen to generate the export line in the NAMESPACE file, but its value is NULL, so there is nothing to export. By removing the @export line, so the code will work correctly.
A:
Be careful not to have any commented lines that begin with an apostrophe!
By bad luck, inside my function I had commented out a line that began with an apostrophe (in front of 'Battlestar Galactica' in my fake example) so it look like this:
#' @export
getMyFavoriteSciFiShows <- function() {
myFavoriteSciFiShows <-
c('Star Trek Next Generation',
#'Battlestar Galactica',
'Babylon 5')
return(myFavoriteSciFiShows)
}
This really screwed up roxygen2 v 6.0.1 since it did not signal any errors and this is what it put into my NAMSEPACE file:
export("Galactica',")
export(Battlestar)
Not only was my desired export myFavoriteSciFiShows missing but two erroneous ones were added. These erroneous ones can result in undefined exports.
|
[
"stackoverflow",
"0013956820.txt"
] | Q:
How to take the mean of last 10 values in a column before a missing value using R?
I am new to R and having trouble figuring out to go about this. I have data on tree growth rates from dead trees, organized by year. So, my first column is year and the columns to the right are growth rates for individual trees, ending in the year each tree died. After the tree died, the values are "NA" for the remaining years in the dataset. I need to take the mean growth for the 10 years preceding each tree's death, but each tree died in a different year. Does anyone have an idea for how to do this? Here is an example of what a dataset might look like:
Year Tree1 Tree2 Tree3
1989 53.00 84.58 102.52
1990 63.68 133.16 146.07
1991 90.37 103.10 233.58
1992 149.24 127.61 245.69
1993 96.20 54.78 417.96
1994 230.64 60.92 125.31
1995 150.81 60.98 100.43
1996 124.25 42.73 75.43
1997 173.42 67.20 50.34
1998 119.60 73.40 32.43
1999 179.97 61.24 NA
2000 114.88 67.43 NA
2001 82.23 55.23 NA
2002 49.40 NA NA
2003 93.46 NA NA
2004 104.67 NA NA
2005 44.14 NA NA
2006 88.40 NA NA
So, the averages I need to calculate are:
Tree1: mean(1997-2006) = 105.01
Tree2: mean(1992-2001) = 67.15
Tree3: mean(1989-1998) = 152.98
Since I need to do this for a large number of trees, it would be helpful to have a method of automating the calculation. Thank you very much for any help! Katie
A:
You can use sapply and tail together with na.omit as follows:
sapply(mydf[-1], function(x) mean(tail(na.omit(x), 10)))
# Tree1 Tree2 Tree3
# 105.017 67.152 152.976
mydf[-1] says to drop the first column. tail has an argument, n, that lets you specify how many values you want from the end (tail) of your data. Here, we've set it to "10" since you want the last 10 values. Then, assuming that there are no NA values in your actual data from while the trees are alive, you can safely use na.omit on your data.
|
[
"stackoverflow",
"0014916000.txt"
] | Q:
CDC fails after attaching database to SQL Server 2008 R2 instance
We have a SQL Server database hosted on SQL Server 2008 R2 (SP 1) with CDC (change data capture) enabled.
After a re-install of the SQL Server instance due to license expiration (the deployment team forgot to install the correct license :( ) we attached the database to the newly installed instance.
However, the CDC was not enabled for all tables
When we tried to enable it by executing
sys.sp_cdc_enable_table
we got
The database 'DBName' is not enabled for Change Data Capture. Ensure
that the correct database context is set and retry the operation. To
report on the databases enabled for Change Data Capture, query the
is_cdc_enabled column in the sys.databases catalog view.
Suggesting that CDC is not enabled.
So, we tried to enable it by executing
sys.sp_cdc_enable_db
we got the following error:
Msg 22906, Level 16, State 1, Procedure sp_cdc_enable_db_internal,
Line 49
The database 'DBName' cannot be enabled for Change Data
Capture because a database user named 'cdc' or a schema named 'cdc'
already exists in the current database. These objects are required
exclusively by Change Data Capture. Drop or rename the user or schema
and retry the operation.
After trying to disable the CDC by executing
sys.sp_cdc_disable_db
we got the error the same error again:
The database 'DBName' is not enabled for Change Data Capture. Ensure
that the correct database context is set and retry the operation. To
report on the databases enabled for Change Data Capture, query the
is_cdc_enabled column in the sys.databases catalog view.
My guess is that there is some inconsistency between the db system tables and the SQL server system tables that lead to an invalid state of the CDC.
Is there any way to fix that?
Any thoughts are appreciated.
A:
Hi
For repairing Db ( with dropping everything in the cdc schema and the schema itself )
use this :
DECLARE @tableName NVARCHAR(100);
DECLARE myCursor CURSOR FORWARD_ONLY FAST_FORWARD READ_ONLY
FOR
SELECT QUOTENAME(t.name) AS name
FROM sys.tables t
JOIN sys.schemas s ON t.schema_id = s.schema_id
WHERE s.name = 'cdc'
OPEN myCursor
FETCH FROM myCursor INTO @TableName
WHILE ( @@Fetch_Status = 0 )
BEGIN
EXEC ( 'drop table cdc.' + @TableName + '; ' );
FETCH NEXT FROM myCursor INTO @TableName
END
CLOSE myCursor
DEALLOCATE myCursor;
go
DECLARE @prName NVARCHAR(100);
DECLARE myCursor2 CURSOR FORWARD_ONLY FAST_FORWARD READ_ONLY
FOR
SELECT QUOTENAME(pr.name) AS name
FROM sys.procedures pr
JOIN sys.schemas s ON pr.schema_id = s.schema_id
WHERE s.name = 'cdc'
OPEN myCursor2
FETCH FROM myCursor2 INTO @prName
WHILE ( @@Fetch_Status = 0 )
BEGIN
EXEC ( 'drop procedure cdc.' + @prName + '; ' );
FETCH NEXT FROM myCursor2 INTO @prName
END
CLOSE myCursor2
DEALLOCATE myCursor2
GO
DECLARE @fnName NVARCHAR(100);
DECLARE myCursor3 CURSOR FORWARD_ONLY FAST_FORWARD READ_ONLY
FOR
SELECT QUOTENAME(fn.name) AS name
FROM sys.objects fn
JOIN sys.schemas s ON fn.schema_id = s.schema_id
WHERE fn.type IN ( 'FN', 'IF', 'TF' )
AND s.name = 'cdc'
OPEN myCursor3
FETCH FROM myCursor3 INTO @fnName
WHILE ( @@Fetch_Status = 0 )
BEGIN
EXEC ( 'drop function cdc.' + @fnName + '; ' );
FETCH NEXT FROM myCursor3 INTO @fnName
END
CLOSE myCursor3
DEALLOCATE myCursor3
go
DECLARE @ruleName NVARCHAR(100);
SELECT @ruleName = DP1.name
FROM sys.database_principals AS DP1
JOIN sys.database_principals AS DP2 ON DP1.owning_principal_id = DP2.principal_id
WHERE DP1.type = 'R'
AND DP2.name = 'cdc';
EXEC ('ALTER AUTHORIZATION ON ROLE::'+@ruleName+' TO dbo; ')
go
DROP SCHEMA [cdc]
GO
DROP USER [cdc]
GO
|
[
"japanese.stackexchange",
"0000064613.txt"
] | Q:
Difference between "じゃない" and "ない"
I would like to ask what is the difference between "じゃない" and "ない"?
I know that "ない" is an i-adjective (info from dictionary).
But we have a sentence for example:
近くも遠くもないです。
Can we say:
近くも遠くもじゃないです。
If not, please explain why.
I've also found here this information:
"You may be aware that ない is the negative form of ある".
How does it come???
Is "ない" i-adjective or negative conjugation of verb "ある"?
I think that now I do not understand nothing.
Thank you very much in advance.
A:
ある is a verb which means "to be located" (It also means 'to have', but that is not relevant here).
The negative conjugation of ある is ない. Which behaves grammatically like an i-adjective. Whether it is strictly correct to call it in i-adjective, I do not know.
So ない means 'is not located'. Therefore your sentence can translate as "It is located neither near nor far from here".
じゃない means 'is not'. But it denotes the lack of equality of two things. e.g ."A cat is not a vegetable". 猫は野菜じゃない. Can you see how this is different from the "is not" in "He is not here"? In the latter we are talking about a location and not about the equivalence between "him" and "here".
Note, that I am confident about the things above this line, but less so about the things below.
Unfortunately things can get more complicated. If you wanted to say "It is not here" you could say ここにない but you could also say ここじゃない. I'm starting to speculate now, but I think the latter could just be an abbreviation of あるところはここじゃない. That is to say that the equivalence we are comparing is, the place where it is located, and here. Which makes more sense than comparing it (which maybe a cabbage) and here, which is a place.
For this reason, as a non-native speaker, I'm not sure if 近くも遠くもじゃない is grammatical. It sounds weird to me though.
|
[
"physics.stackexchange",
"0000019537.txt"
] | Q:
How can Kaluza-Klein particles be told apart from winding modes at the LHC?
I`ve already asked this in the comments below this article http://profmattstrassler.com/articles-and-posts/some-speculative-theoretical-ideas-for-the-lhc/extra-dimensions/how-to-look-for-signs-of-extra-dimensions/ from Prof. Strassler but did not get a satisfactory answer...
In the article Prof. Strassler explains that a possible sign of extra dimensions at the LHC could be the detection of Kaluza-Klein particles. The energy (or mass squared) spectrum of the corresponding particle tower would have a step size proportional to 1/r (where r is the radius of a compact extra dimension).
Now I`m wondering how such a (hypothetical) KK particle candidate can be told apart from a winding mode particle (with the step size of the energy spectrum proportional to r) which is probably more easily produced depending on the size r of the extra dimension ?
By the way what's the actual state of these searches for extra dimensions considering the data already available ?
Clarification
Considering an extra dimension that is much larger than the particle, the KK modes with the 1/r spectrum arise from the quantized angular momentum a particle can have due to it' movement in the extra dimension. If the extra dimension is smaller the particle can wind around the extra dimension leading to the winding mode particles. For these the energy spectrum is determined by the potential energy of stretching. The spectra of the KK and winding modes are T-dual to each other.
A:
By the way what's the actual state of these searches for extra dimensions considering the data already available ?
The LHC experiments are looking for extra dimensions in various channels (search for "extra dimensions LHC) and putting limits. At the moment the standard model reigns.
They are trying for KK s too, though still at a planning stage.
I do not know what a winding mode particle is, but I expect the decay products, which are the main thing measured at LHC experiments, will make the distinction possible.
|
[
"stackoverflow",
"0019905555.txt"
] | Q:
C# key pressed listener in a Windows Forms UserControl
Good day,
I want to add key listeners in a forms user control. Which is included in a main form.
When a user presses a key in my application I want it to do some thing.
How do I go about doing this?
for example. If I pressed w then a popup would appear saying you pressed w.
I have tried this in my User Control Class;
private void UC_ControlsTank_KeyPress(object sender, KeyPressEventArgs e)
{
Console.Write("You pressed:" + e.KeyChar);
}
But when i press keys nothing seems to happen.
EDIT:
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_KeyPress(object sender, KeyPressEventArgs e)
{
MessageBox.Show(e.KeyChar.ToString());
}
}
Here is my form:
and here is how I linked it in visual studio:
A:
First of all before capturing KeyPress you have to set the KeyPreview property of the Win Form to true. Unless you set it to true KeyPress will not be captured.
A:
There is a KeyPressed event that you can use
Control.KeyPress Event
This has System.Windows.Forms.KeyEventArgs e that will tell you what key was pressed
Edit:
So I just tried this on a sample app and it worked fine
private void Form1_KeyPress(object sender, KeyPressEventArgs e)
{
MessageBox.Show(e.KeyChar.ToString());
}
|
[
"ru.stackoverflow",
"0000885400.txt"
] | Q:
Как отсортировать массив содержащий массивы и объекты WordPress по двум параметрам?
Array(
[0] => Array(
[format] => WP_Post Object
(
[id] => 1
//прочее
)
[variants] => Array
(
[0] => Array
(
[variant] => WP_Term Object
(
[name] => 'Иван'
//прочее
)
)
)
)
[1] => Array(
[format] => WP_Post Object
(
[id] => 2
//прочее
)
[variants] => Array
(
[0] => Array
(
[variant] => WP_Term Object
(
[name] => 'Алексей'
//прочее
)
)
)
)
)
Есть такой сложный массив, как отсортировать его по значениям name и потом по значениям id ?
A:
foreach($your_array as $k=>$v){
$key = $v['variants'][0][variant]['name'] . $v['format']['id'];
$result_array[$key]= $v;
}
ksort($result_array);unset($your_array);$k=0;
foreach($result_array as $v){$your_array[$k] = $v;$k++;}
|
[
"stackoverflow",
"0048838516.txt"
] | Q:
Devexpress xtrareport character spacing
How to add character spacing in devexpress xtrareport in lable.
I am trying to search on their site but they answer that they do not support it.
Here is the link: Click Here
I want this for cheque date print.
If anyone has any answer please tell me.
A:
You are correct, the XRLabel report control doesn't provide a way to specify the character spacing, but you can try using the XRCharacterComb report control instead. Does this help?
|
[
"stackoverflow",
"0056828061.txt"
] | Q:
Non-canonical mode don't work on backtick
When I launch my program using backticks like:
cat `./my_program`
I expect my read() to read character by character, it still reads line by line. The non-canonical mode of my terminal doesn't work. I don't really understand why.
Here is my code:
#include <unistd.h>
#include <stdlib.h>
#include <stdio.h>
#include <term.h>
#include <strings.h>
int main()
{
struct termios term_setting;
char *term;
char buff[10];
term = getenv("TERM");
tgetent(NULL, term);
tcgetattr(STDOUT_FILENO, &term_setting); //
term_setting.c_lflag &= ~(ICANON | ECHO); //set my term in echo and non-canonique mode
tcsetattr(STDOUT_FILENO, 0, &term_setting); //
for (;;){
bzero(buff, sizeof(char) * 10);
read(STDIN_FILENO, buff, 9);
printf("%s\n", buff);
}
return (0);
}
A:
Ry-♦ say in comment:
Because stdout isn’t the terminal anymore. Did you mean to get/set those attributes on STDIN_FILENO?
It's exactly my probleme, thx!
|
[
"stackoverflow",
"0054071055.txt"
] | Q:
Element looking weird with animation set two times
So I got this pen: https://codepen.io/tobiasglaus/pen/NedpxQ
Whenever it "clicks", a circle should be animated. There are 2 clicks in the animation, so I just added the animation 2 times, like this:
animation: circle .3s forwards, circle .3s forwards;
animation-delay: 1.7s, 4.9s;
The problem is, that the circle isn't a circle anymore, but a blurry square:
But it should look like this:
I can't replicate the problem in a SO-snippet, but since I need to provide a minimal code example, here's the snippet of how it should look.
Note: When I view the animation with the Chrome DevTools, the animation looks correct.
.circle:after{
content:"";
position:absolute;
top:20px;
left:20px;
width:50px;
height:50px;
border-radius:50%;
border:2px solid #222f3e;
animation:circle .3s forwards, circle .3s forwards;
animation-delay:0s, 1s;
opacity:0;
transform:scale(0);
}
@keyframes circle {
0%{
transform:scale(0);
}
50%{
opacity:1;
}
100%{
transform:scale(1);
opacity:0;
}
}
<div class="circle"></div>
A:
I still don't know why the circle rendered weirdly, but I managed to come up with a solution that works:
That's what I had:
animation: circle .3s forwards, circle .3s forwards;
animation-delay: 1.7s, 4.9s;
and the animation:
@keyframes circle {
0%{
transform:scale(0);
}
50%{
opacity:1;
}
100%{
transform:scale(1);
opacity:0;
}
}
Instead of calling the animation twice, I created one big animation:
animation: circle 3.5s forwards;
animation-delay:1.7s;
and that's the animation:
@keyframes circle{
0%{
transform:scale(0);
}
4%{
opacity:1;
}
8%{
transform:scale(1);
opacity:0;
}
92%{
transform:scale(0);
opacity:0;
}
96%{
opacity:1;
}
100%{
transform:scale(1);
opacity:0;
}
}
So the initial animation duration of 0.3s is now equal to 8% and the animation delay between the animations is equal to the 74% of nothing in the animation.
|
[
"stackoverflow",
"0056168988.txt"
] | Q:
System.Diagnostics.ProcessStartInfo hangs if the arguments include a tilde mark
The git command git reset HEAD~ will undo the last commit. But when I try and run the command in PowerShell using System.Diagnostics.ProcessStartInfo, the process just hangs.
I think it has something to do with the tilde (~) mark, because I tried to escape it with a backslash and the command didn't hang anymore. But it didn't work, either. It just silently failed.
Here is the script:
$pinfo = New-Object System.Diagnostics.ProcessStartInfo
$pinfo.FileName = "C:\Program Files\Git\cmd\git.exe"
$pinfo.Arguments = "reset HEAD~"
$pinfo.WorkingDirectory = "C:\GitRepo"
$pinfo.RedirectStandardError = $true
$pinfo.RedirectStandardOutput = $true
$pinfo.UseShellExecute = $false
$pinfo.CreateNoWindow = $true
$p = New-Object System.Diagnostics.Process
$p.StartInfo = $pinfo
$p.Start() | Out-Null
$p.WaitForExit()
A:
Passing the arguments as a list seems to fix it:
$pinfo.Arguments = "reset","HEAD~"
I guess there's some more auto escaping going on with this method.
|
[
"stackoverflow",
"0041486495.txt"
] | Q:
Why is `NaN` considered "smaller" than `-np.inf` in numpy?
What is the reason that NaN's are considered less than -np.inf in any comparisons involving np.min or np.argmin?
import numpy as np
In [73]: m = np.array([np.nan, 1., 0., -np.inf])
In [74]: n = np.array([-np.inf, 1., 0., np.nan])
# Huh??
In [75]: np.min(m)
Out[75]: nan
In [76]: np.min(n)
Out[76]: nan
# Same for np.argmin
In [77]: np.argmin(m)
Out[77]: 0
In [78]: np.argmin(n)
Out[78]: 3
# Its all false!
In [79]: np.nan < -np.inf
Out[79]: False
In [80]: np.nan > -np.inf
Out[80]: False
# OK, that seems to fix it, but its not necessarily elegant
In [81]: np.nanmin(m)
Out[81]: -inf
In [82]: np.nanargmin(m)
Out[82]: 3
I would guess that its probably a side effect of any comparisons with NaN values returning False, however this imho leads to some rather annoying effects when you "happen" to sometimes end up with a NaN value in your array. The usage of np.nanmin or np.nanargmin some feels like a quickfix that was somehow stapled on top of the existing behaviour.
Apart from that note in the docs: "NaN values are propagated, that is if at least one item is NaN, the corresponding min value will be NaN as well. To ignore NaN values (MATLAB behavior), please use nanmin., I haven't found anything that explains the rationale behind that behaviour. Is this wanted or a side effect of a particular internal representation of NaN values? And why?
A:
As @Dunno mentioned in a comment, it does not give much meaning to compare a NaN with a number, so this behaviour is probably ok. The IEEE 754 standard says this about comparing NaNs with numbers:
Four mutually exclusive relations are possible: less than, equal, greater than, and unordered. The last case
arises when at least one operand is NaN. Every NaN shall compare unordered with everything, including
itself
According to the standard this:
# Its all false!
In [79]: np.nan < -np.inf
Out[79]: False
would result in an "unordered" result, so it is not true that it is belongs to the relation "less than".
|
[
"gis.stackexchange",
"0000013153.txt"
] | Q:
How to label raster cells in QGIS?
I try to show a small resolution raster file in the QGIS Print Manager tool.
I would like to show a small label with each cell value (position - circa middle of each cell).
How I can do it? Is there any plugin which can help me to accomplish this task?
My idea is to use gdal2xyz, load such file using CSV plugin and then save it as a vector file. Unfortunately it is much work, because I have many raster files.
Another idea is to use gdal2xyz.py, then ogr2ogr to save it as vector file.
Is there any way to batch this process? Is there any open-source program where I can do it much more easily?
A:
There doesn't seem to be a plugin for or functionality in QGIS to label cells.
Using a converted vector file to label the centres of the cells is probably your best bet. The open-source statistics package R has a lot of excellent spatial tools and can batch or quickly process raster files to create shapefiles (vector/points).
library(maptools)
library(raster)
# Load the raster from a file
r <- raster("/workspace/TEMP/raster.asc")
# Convert to spatial points
p <- as(r, "SpatialPointsDataFrame")
# Save as a shapefile
writeSpatialShape(p, "/workspace/TEMP/raster_points")
The shapefile will have column with the raster values for each point. The points can then be loaded into QGIS, given a size of 0 and labelled appropriately; they appear in the centre of cells.
To go through, for example, all the TIF files in a directory:
for (file in dir("/workspace/TEMP/", pattern="*.tif")) { # list all .tif files
r <- raster(file)
p <- as(r, "SpatialPointsDataFrame")
writeSpatialShape(p, substr(file, start = 1, stop = nchar(file) -4)) # substr() removes extension.
}
A:
In case R is not available (or, want to do it within QGIS environment), there is now SAGA tool in the processing toolbox, Raster values to points to extract cell values.
We can label the output Shapes layer and overlay it with the original raster.
|
[
"stackoverflow",
"0036981688.txt"
] | Q:
python how are sets items arranged (Ordered)
I am Confused Of how Sets Items are Arranged Cause for Example :
s1 = {2,1,3,6}
print(s1) ===> {1,2,3,6}
s1 = {2,1,30,6}
print(s1) ===> {1,2,6,60}
s1 = {2,1,300,6}
print(s1) ===> {1,2,300,6}
s1 = {2,1,3,6}
print(s1) ===> {3000,1,2,6}
But For Alphapetic Characters It Seems Random for Example :
s1 = {'A','B','C','D'}
first Run ====> {'D', 'C', 'B', 'A'}
Second Run ===> {'B', 'A', 'C', 'D'}
Third Run ====> {'C', 'B', 'A', 'D'}
it Keeps Changing so It Is Kinda Random But For Numbers It is Constant
A:
A few things to say:
There is an inconsistency on your fourth line - the definition of s1 should be s1 = {2,1,3000,6} - to match with your console output;
I don't know what you mean by 'runs' but, when opening an instance of the Python console (version 3.4.3 for me), when I type in s1 = {2,1,6,3} then print(s1), the console outputs {1, 2, 3, 6}; however, when I type s1 = {'1','2','3','6'} then print(s1), the console outputs {'2', '4', '3', '1'} so I can say, from observation, that this random ordering of objects seems to affect strings but not integers - it seems these are ordered correctly automatically. The second output also occurs with other object types (typing in s2 = {'a','b','c','d'} then print(s2) gave me {'c', 'b', 'd', 'a'});
When doing the exact same inputs as above after closing and reopening the Python console, the following output appeared for me: {1, 2, 3, 6}, {'3', '2', '1', '4'}, {'b', 'c', 'd', 'a'}. So it seems to change every time you open a new Python console. I know that sets are unordered collections of unique objects (the same object can't be repeated twice in the same set - it will be removed automatically when outputted), but I don't know the reason behind that.
That's all I have to say about your question - if you want to find out more, I would suggest a google search on set ordering in python 3 or any other search to help you find more information.
Edit
According to the book Learning Python 5th Edition, the definition of a set is:
an unordered collection of unique and immutable objects that supports operations corresponding to mathematical set theory.
It may be that the creators of Python wanted sets to order mathematical values to make the application of sets in mathematical areas that little bit easier.
|
[
"ru.stackoverflow",
"0000584006.txt"
] | Q:
Как при клике показать другую половину div?
Добрый день! Как сделать, что при начальном состоянии показывалось 50% этого div, а после нажатия на кнопку показывалась другие 50%?
<script>
function change(idName) {
if(document.getElementById(idName).style.display=='none') {
document.getElementById(idName).style.display = '';
} else {
document.getElementById(idName).style.display = 'none';
}
return false;
}
</script>
<div style="display:none;" id="test">
<div class="hide">
Подкатегории:
<a href="#"> Белые комоды</a>
<a href="#"> Большие</a>
<a href="#"> В гостиную</a>
</div>
</div>
<a href="#" onclick="change('test')">Ещё</a>
A:
Если допускается использование jquery, то можно так:
$(function(){
var h=$(".hide").height(); //получаем высоту блока с контентом
$(".hide").css({"height": h/2}); //устанавливаем высоту блока с контентом в 50%
$(".button").click(function(){ //нажатие на кнопку
if(h==$(".hide").height()){ //если высота блока на момент нажатия на кнопку равно изначальной высоте блока то
$(".hide").css({"height": h/2}); //устанавливаем высоту блока в 50% от изначальной
}
else { //иначе
$(".hide").css({"height": h}); //устанавливаем высоту блока в 100%
}
});
});
.hide {
overflow: hidden;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="test">
<div class="hide">
Подкатегории: <br/>
<a href="#"> Белые комоды</a><br/>
<a href="#"> Большие</a> <br/>
<a href="#"> В гостиную</a> <br/>
</div>
<button class="button">Ещё</button>
</div>
|
[
"stackoverflow",
"0054077082.txt"
] | Q:
Aggregate consecutive values BigQuery
I need to aggregate consecutive values in a table with BigQuery, as shown in the example
Segment can be only 'A' or 'B'. Value is a String.
Basically, for each id i need to consider only segment='A' taking into account the gaps.
It should be ORDER BY date_column ASC
Example
id, segment, value, date_column
1, A, 3, daytime
1, A, 2, daytime
1, A, x, daytime
1, B, 3, daytime
1, B, 3, daytime
1, B, 3, daytime
1, A, 7, daytime
1, A, 3, daytime
1, B, 3, daytime
1, A, 9, daytime
1, A, 9, daytime
2, A, 3, daytime
2, B, 3, daytime
2, A, 3, daytime
2, A, m, daytime
Expected result
id, agg_values_A_segment
1, ['32x', '73', '99']
2, ['3', '3m']
How can I achieve this result?
I'm struggling with the 'gap' between the segments.
A:
Below options for BigQuery Standard SQL
Option 1 - using window analytics functions
#standardSQL
SELECT id, ARRAY_AGG(values_in_group ORDER BY grp) agg_values_A_segment
FROM (
SELECT id, grp, STRING_AGG(value, '' ORDER BY date_column) values_in_group
FROM (
SELECT id, segment, value, date_column, flag,
COUNTIF(flag) OVER(PARTITION BY id ORDER BY date_column) grp
FROM (
SELECT *, IFNULL(LAG(segment) OVER(PARTITION BY id ORDER BY date_column), segment) != segment flag
FROM `project.dataset.table`
)
)
WHERE segment = 'A'
GROUP BY id, grp
)
GROUP BY id
You can test, play with above using sample data from your question as in below example:
#standardSQL
WITH `project.dataset.table` AS (
SELECT 1 id, 'A' segment, '3' value, DATETIME '2019-01-07T18:46:21' date_column UNION ALL
SELECT 1, 'A', '2', '2019-01-07T18:46:22' UNION ALL
SELECT 1, 'A', 'x', '2019-01-07T18:46:23' UNION ALL
SELECT 1, 'B', '3', '2019-01-07T18:46:24' UNION ALL
SELECT 1, 'B', '3', '2019-01-07T18:46:25' UNION ALL
SELECT 1, 'B', '3', '2019-01-07T18:46:26' UNION ALL
SELECT 1, 'A', '7', '2019-01-07T18:46:27' UNION ALL
SELECT 1, 'A', '3', '2019-01-07T18:46:28' UNION ALL
SELECT 1, 'B', '3', '2019-01-07T18:46:29' UNION ALL
SELECT 1, 'A', '9', '2019-01-07T18:46:30' UNION ALL
SELECT 1, 'A', '9', '2019-01-07T18:46:31' UNION ALL
SELECT 2, 'A', '3', '2019-01-07T18:46:32' UNION ALL
SELECT 2, 'B', '3', '2019-01-07T18:46:33' UNION ALL
SELECT 2, 'A', '3', '2019-01-07T18:46:34' UNION ALL
SELECT 2, 'A', 'm', '2019-01-07T18:46:35'
)
SELECT id, ARRAY_AGG(values_in_group ORDER BY grp) agg_values_A_segment
FROM (
SELECT id, grp, STRING_AGG(value, '' ORDER BY date_column) values_in_group
FROM (
SELECT id, segment, value, date_column, flag,
COUNTIF(flag) OVER(PARTITION BY id ORDER BY date_column) grp
FROM (
SELECT *, IFNULL(LAG(segment) OVER(PARTITION BY id ORDER BY date_column), segment) != segment flag
FROM `project.dataset.table`
)
)
WHERE segment = 'A'
GROUP BY id, grp
)
GROUP BY id
-- ORDER BY id
with result
Row id agg_values_A_segment
1 1 32x
73
99
2 2 3
3m
Option 2 - above option should work for big volumes of rows per id, but looks a little heavy - so second option is more of simple option but assumes you have some character or sequence of chars that you sure will not be result from combining your values, for example pipe char or tab or as in below example I choose word 'delimiter' assuming it will not appear as a result of concatenation
#standardSQL
SELECT id,
ARRAY(SELECT part FROM UNNEST(parts) part WHERE part != '') agg_values_A_segment
FROM (
SELECT id,
SPLIT(STRING_AGG(IF(segment = 'A', value, 'delimiter'), ''), 'delimiter') parts
FROM `project.dataset.table`
GROUP BY id
)
You can test, play with above using same sample data:
#standardSQL
WITH `project.dataset.table` AS (
SELECT 1 id, 'A' segment, '3' value, DATETIME '2019-01-07T18:46:21' date_column UNION ALL
SELECT 1, 'A', '2', '2019-01-07T18:46:22' UNION ALL
SELECT 1, 'A', 'x', '2019-01-07T18:46:23' UNION ALL
SELECT 1, 'B', '3', '2019-01-07T18:46:24' UNION ALL
SELECT 1, 'B', '3', '2019-01-07T18:46:25' UNION ALL
SELECT 1, 'B', '3', '2019-01-07T18:46:26' UNION ALL
SELECT 1, 'A', '7', '2019-01-07T18:46:27' UNION ALL
SELECT 1, 'A', '3', '2019-01-07T18:46:28' UNION ALL
SELECT 1, 'B', '3', '2019-01-07T18:46:29' UNION ALL
SELECT 1, 'A', '9', '2019-01-07T18:46:30' UNION ALL
SELECT 1, 'A', '9', '2019-01-07T18:46:31' UNION ALL
SELECT 2, 'A', '3', '2019-01-07T18:46:32' UNION ALL
SELECT 2, 'B', '3', '2019-01-07T18:46:33' UNION ALL
SELECT 2, 'A', '3', '2019-01-07T18:46:34' UNION ALL
SELECT 2, 'A', 'm', '2019-01-07T18:46:35'
)
SELECT id,
ARRAY(SELECT part FROM UNNEST(parts) part WHERE part != '') agg_values_A_segment
FROM (
SELECT id,
SPLIT(STRING_AGG(IF(segment = 'A', value, 'delimiter'), ''), 'delimiter') parts
FROM `project.dataset.table`
GROUP BY id
)
-- ORDER BY id
obviously with same result
Row id agg_values_A_segment
1 1 32x
73
99
2 2 3
3m
note: second option can result with resources exceeded for case when you have too many rows per id - you just need to try it on your real data
|
[
"stackoverflow",
"0049981367.txt"
] | Q:
pig: getting count of strings from file A from file B
I am new to PIG, I am looking for help.
I have two files A(templates) and B(data) both are having huge unstructured content.
Agenda is to traverse the file B(data) and find the count against each template(line) of file A.
I think it should work in a loop with the nested statement but I do not know how can I achieve the same in pig.
example:-
file1.txt
hello ravi
hi mohit
bye sameer
hi mohit
hi abc
hello cds
hi assaad
file2.txt
hi mohit
hi assaad
I need a count of file2 both lines.
The expected output may look like:-
hi mohit: 2
hi assaad: 1
Please do let me know.
A:
Lets start by loading both your datasets:
data = LOAD 'file1.txt' AS (line:chararray);
templates = LOAD 'file2.txt' AS (template:chararray);
Now we essentially need to JOIN the above relations on the templates. Once joined, we can GROUP on the template to get counts for each template. However that would required 2 map-reduce stage, one for the JOIN and one for the GROUP BY. Here is where you can use COGROUP. It is an extremely useful operation and you can read more about it here: https://www.tutorialspoint.com/apache_pig/apache_pig_cogroup_operator.htm
cogroupedData = COGROUP data BY line, templates BY template;
templateLines = FILTER cogroupedData BY (NOT ISEmpty(templates));
templateCounts = FOREACH templateLines GENERATE
group AS template,
COUNT(data.line) AS templateCount;
DUMP templateCounts;
What COGROUP does is essentially similar to a JOIN and then a GROUP BY on the same key (template in this case). It takes only one map-reduce stage. The filter applied above is to remove records which did not have a template in file2.txt
|
[
"stackoverflow",
"0060107054.txt"
] | Q:
C++ equivalent to Java Map getOrDefault?
Java's getOrDefault was a nice construct for one line access to a map value or the starting point if one does not exist. I do not see anything in the map reference in C++ with a parallel. Does something exist or is it build your own?
I have objects in the map that I would update if they exist, but construct new if they do not. With getOrDefault, I could construct the object on the default side, or access it if it exists.
http://www.cplusplus.com/reference/map/map/
https://www.geeksforgeeks.org/hashmap-getordefaultkey-defaultvalue-method-in-java-with-examples/
A:
I have objects in the map that I would update if they exist, but
construct new if they do not. With getOrDefault, I could construct the
object on the default side, or access it if it exists.
Use emplace.
auto& element = *map.emplace(key, value).first;
emplace inserts a new element if the key is not present, and returns a pair consisting of an iterator to the element (inserted or already existent) and a bool value indicating whether insertion took place.
|
[
"stackoverflow",
"0002814305.txt"
] | Q:
CSS Columns and printing
In Mozilla, applying a css rule like
-moz-column-count: 2;
gets you 2 columns that are the full height of the page. From what their MDC suggests, this is called "Height Balancing".
Webkit has something similar:
-webkit-column-count: 2;
I'm not completely sure if Webkit has "Height Balancing" or not (this may be the root of my problem, honestly). In Webkit, this is displayed the same way on the page. However, when you print the page with said columnar content, in Firefox, the printed pages end up looking like this:
A C
B D
---
E G
F H
whereas Webkit displays like this:
A E
B F
---
C G
D H
Is there a way to make Webkit print like Mozilla?
A:
This was a bug in WebKit. It's been replaced by another bug when multi-column was disabled for printing:
https://www.webkit.org/blog/88/css3-multi-column-support/#comment-16854
https://code.google.com/p/chromium/issues/detail?id=99358
There is a related stackoverflow question: CSS columns breaking when printing
|
[
"stackoverflow",
"0008598956.txt"
] | Q:
Getting Value From A Third Table
SELECT POSTS.*
FROM POSTS
LEFT JOIN SUBSCRIBERS
ON POSTS.AUTHORID = SUBSCRIBERS.PROFILEID
WHERE POSTS.AUTHORID = ?
OR SUBSCRIBERS.SUBSCRIBERID = ?
ORDER BY POSTID DESC
LIMIT ?
The above is the query I'm using and this will select posts from the profiles a user is subscribed to. Now this works fine, but now I want to grab another column from another table.
In my third table USERS, I have an "AVATARID" which I want to access.
In my fetch loop for this query, it echos out the username of the post author, and the post body. What I want it to do is also echo out the avatarID of the user who wrote the post. I tried adding in another query inside my while loop, but I find that sloppy, and it also doesn't work :S
So, simple question: How do I access the AvatarID from the table USERS with the USERID of the AUTHORID from the post?
A:
Something like...
SELECT POSTS.*, USERS.AVATARID
FROM POSTS
LEFT JOIN SUBSCRIBERS ON POSTS.AUTHORID = SUBSCRIBERS.PROFILEID
JOIN USERS ON POSTS.AUTHORID = USERS.USERID
WHERE POSTS.AUTHORID = ?
OR SUBSCRIBERS.SUBSCRIBERID = ?
ORDER BY POSTID DESC
LIMIT ?
|
[
"stackoverflow",
"0042093727.txt"
] | Q:
Generate time between events giving wrong info
The Issue
In our calendar users can make events that will load into a MySQL database. The start time is stored and the end time is stored. In the database they are stored like this
start_time_first, start_time_second, end_time
example:
`9`, `30`, `11:00` (9:30 - 11:00)
`13`, `10`, `14:25` (1:10 - 2:25)
I then split the variables up when loaded to give me 4 variables which all works like expected using the following:
$real_time_start = $time_start[0] . $time_start[1]; // gives something like 930
$real_time_end = $time_end[0] . $time_end[1]; // gives something like 1100
$difference = $real_time_end - $real_time_start; // find the difference
// pad the difference for 30 minutes
// and then format it for display
$difference = str_pad($difference, 3, '0', STR_PAD_LEFT);
$difference = $difference[0].":".substr($difference, -2, 2);
The obvious issue I am having is that if the time_end event is 1100 and the start is 930 that when I subtract them the value I get is 70 instead of 30. If the time_end[1] is lower than the time_start[1] then it will give me a bad value that doesn't work for time.
Here is a visual representation. As you can see the one value is correct while the other... not so much:
Is there a better way to simulate time between the two events in the way I am doing it or a better math I am missing to fix this issue? I had a go at writing a long way around it but it's much more difficult to get every occurrence the way I had written it. Hopefully this can help someone else in the future as well.
The database structure
A:
You can't use the decimal system to subtract day times because minutes flow from 60 to the next hour and not from 100. PHP provides the DateTime/DateInterval classes for this:
$start=new DateTime('9:30');
$end=new DateTime('11:00');
$diff=$start->diff($end);
var_dump($diff->format('%H:%i'));
(This is just to demonstrate; theoretically this can be problematic with DST, so if you can you should include the date as well to have an exact solution.)
|
[
"stackoverflow",
"0057504142.txt"
] | Q:
how to get rid of TypeError: Cannot read property 'map' of undefined error?
I am trying to get id, first and last name of users using createListItems() inside user-list.js file.
But, I got
"TypeError: Cannot read property 'map' of undefined"
error when I ran the program, and (line7 / user-list.js) return this.props.users.map(user => { is red (not working).
I do not know why I get this error, and how to fix it.
Does anyone know how to get rid of this error?
user-list.js
import React, { Component } from "react";
import { bindActionCreators } from "redux";
import { connect } from "react-redux";
class UserList extends Component {
createListItems() {
return this.props.users.map(user => {
return (
<li key={user.id}>
{user.first}
{user.last}
</li>
);
});
}
render() {
return <ul>{this.createListItems()}</ul>;
}
}
function mapStateToProps(state) {
return {
users: state.users
};
}
export default connect(mapStateToProps)(UserList);
index.js
import React, { Component } from "react";
import UserList from "../containers/user-list";
class Index extends Component {
state = {};
render() {
return (
<div>
<h2>username list:</h2>
<UserList />
<hr />
<h2>user details:</h2>
</div>
);
}
}
export default Index;
A:
As warkentien2 mentioned, you're not passing the users array to the <UserList /> component. You need to create an array in index.js of your users (manually or pulled from somewhere else) and pass it off like this: <UserList users={[{id: 1, first: "John", last: "Doe"}]} />
|
[
"stackoverflow",
"0045579489.txt"
] | Q:
How to write 'utf-8' to a new CSV file using python3 with Anaconda?
How to write 'utf-8' to a new CSV file using python3 with Anaconda?
I'm a new python and pandas learner. The version I use is python3. I run it with Anaconda platform, an IDE as similar as PyCharm IDE.
I have two arrays to record all words and their frequency from a long text. All the word is kept in form of string which include 'utf-8' character:
value = [13, 4, 3, 3, 3, 3, 3, 3, 3, 2, 2, 2, 2, 2, 2, 2, 2, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]
key = ['-', 'Span', 'Found', 'Not', '404.0', '详细', '8.5', 'IIS', 'Details', '错误', 'Machine,', 'K', 'Ltd.', 'Co.,', 'Contact', 'Group', 'Large', 'qinwomachine', 'Trading', 'Qinwo', 'Shanghai', 'Manufacturer', 'Machine', 'Super', 'Abm240', 'Abm120', 'Mic240', 'Mic120', 'Forming', 'Roll', 'wubianstar', 'Electrical', 'Hont', 'China', 'tileformer', '\ufeffContact']
Now I'm trying to write those value and key array to a new CSV file called split_word.csv using python3 with Anaconda. My code is as follows:
# read the arrays as dataframe, also set the column name 'word' and 'frequency'
df = pd.DataFrame({"word" : newkey, "frequency" : newvalue})
# write dataframe into a new csv file
df.to_csv("split_word.csv", index=False)
My expected result in the csv is two new columns:
frequency word
13 -
4 Span
3 Found
3 Not
3 404
3 详细
3 8.5
3 IIS
3 Details
2 错误
2 Machine,
2 K
2 Ltd.
2 Co.,
2 Contact
But there's something wrong with the actual result. '详细' and '错误' are missing:
frequency word
13 -
4 Span
3 Found
3 Not
3 404
3 ????
3 8.5
3 IIS
3 Details
2 ????
2 Machine,
2 K
2 Ltd.
2 Co.,
2 Contact
So the only problem is the 'utf-8' input. Should I add decode or encode into the code? How can I solve the simple but annoying problem?
Thank you so much!
A:
You just need to specify the encoding:
df.to_csv("split_word.csv", index=False, encoding="utf-8")
|
[
"stackoverflow",
"0013322305.txt"
] | Q:
create sql update for each control in vb6
So I've got this code to loop through each controls in a form and create and update sql based on their names and values, text or caption.
Dim sql as String
Dim ctr as Control
sql = "update table set "
For Each ctr In Me.Controls
If TypeOf ctr Is TextBox Then
If ctr.Container = "Carton Config data input" Then
sql = sql & ctr.name & " = " & "'" & ctr.Text & "',"
End If
ElseIf TypeOf ctr Is OptionButton Then
If ctr.Value = True Then
sql = sql & " status = '" & ctr.Caption & "',"
End If
ElseIf TypeOf ctr Is CheckBox Then
If ctr.Value = 1 Then
sql = sql & ctr.name = "'OK',"
ElseIf ctr.Value = 0 Then
sql = sql & ctr.name = "'',"
End If
End If
Next
After that I add the where conditions of course but it doesn't matter now.
The problem is when it gets to a checkbox, the sql's value will be "False" and I have no idea why.
The length of the string shouldn't be a problem, the first checkbox that makes this is the 4th object, so the string is not too long. Besides, without the checkbox part, it works like a charm.
So could someone help me?
Thanks in advance.
A:
I found the problem so I will just answer it for those who might need it.
It was a simple syntax error:
Just replaced:
If ctr.Value = 1 Then
sql = sql & ctr.name = "'OK',"
ElseIf ctr.Value = 0 Then
sql = sql & ctr.name = "'',"
End If
With:
If ctr.Value = 1 Then
sql = sql & ctr.name & " = 'OK',"
ElseIf ctr.Value = 0 Then
sql = sql & ctr.name & " = '',"
End If
|
[
"stackoverflow",
"0043917871.txt"
] | Q:
inconsistence between mapper and randint python modules
I'd like to understand why the output of the following python code shows two lists.
Removing mapper module, the output is as expected.
MWE
from random import randint
import mapper as mp
x=[randint(0,9) for p in range(0,10)]
print(x)
output
[5, 7, 1, 2, 2, 1, 6, 6, 4, 6]
[0, 2, 7, 6, 8, 4, 6, 3, 5, 1]
A:
Make sure that your script file is not named mapper.py. Otherwise, importing the mapper will load the script twice causing print different random number sequences twice.
You should also make sure there's no mapper.pyc remain.
|
[
"stackoverflow",
"0037636450.txt"
] | Q:
undefined local variable or method `days_till_expired'
Currently I have a method called days_till_expired defined in my subscriber model. I'm trying to call it in the controller but it doesn't seem to be working? I must be missing something obvious because this should be a simple implementation. I'll post my code for clarity.
MODEL METHOD:
def days_till_expired
((created_at + 1.year) - DateTime.now).to_i / 1.day
end
CONTROLLER:
def visit
@subscriber = Subscriber.find_by_phone_number(params[:phone_number])
if @subscriber
@subscriber.visit =+ 1
@subscriber.save
flash[:notice] = "Thank You! You have #{days_till_expired} until renewal"
redirect_to subscribers_search_path(:subscriber)
else
render "search"
end
end
As you can see I'm simple trying to call the method with interpolation inside the flash notice but I keep getting this ERROR:
A:
You are not calling to the methods, if you have days_till_expired on your model you forgot to use your model @subscriber.days_till_expired
flash[:notice] = "Thank You! You have #{@subscriber.days_till_expired} until renewal"
If I were you, I would try to move that counter logic to the model.
|
[
"stackoverflow",
"0027823715.txt"
] | Q:
wxformbuilder and unicode labels
Is there a way to get Unicode characters into label code generated by wxFormBuilder?
For example, to get an Angstrom character the generated string should read u"\u212b".
I tried entering \u212b in the label property field but the resulting string reads u"u212b". So I tried escaping the backslash as \\u212b but that gave me u"\\u212b".
I'm using wxFormBuilder v3.5 - beta. Generating Python code, although the C++ code shows the same behaviour.
A:
By default, wxFormBuilder includes this command (# -- coding: utf-8 --
) on the first line at least for the python code generated.
So I went into MS word and inserted the Angstrom character Å, I then copied it into wxFormBuilder (Version 3.5 - RC1) statictext control and it worked on running the code.
Try my approach above instead of typing "u212b". Or type directly in your code like so: u"Hello... Å"
|
[
"stackoverflow",
"0025501031.txt"
] | Q:
QCustomPlot example turn off layout
I have example project with QCustomPlot in QT in Eclipse. Link is http://www.qcustomplot.com/index.php/download. I am trying case of setupQuadraticDemo(). Example is allright, I can build and run project without problems. But QCustomPlot is anchor on left side using by layout. But I want move QCustomPlot on MainWindow by mouse movement. So I want turn off layout using. In Property Explorer I can set Layout Direction only on LeftToRight or RightToLeft. But I want cancel layout using in this project. How I can this in this example project? I am newbie in QT. Must I some edit in ui_mainwindow.h or qcustomplot.ccp or somewhere else? Thanks
A:
OK I resolve this. I right click on MainWindow. Then I choose option Lay out. Then I clicked on Break Layout. Now I can displace elements on MainWindow via mouse movement.
|
[
"stackoverflow",
"0008357130.txt"
] | Q:
How to initialize the bean when the custom scope is created
I have a custom scope defined for my Spring configuration, I want to initialize some of my beans "right after" my custom scope is created. At the moment my bean is not initialized because probably it is not called on right time when the scope is ready yet.
"myScope" is created through Java code.
<bean id="myAdvice" class="com.myclass" scope="myScope">
<property name="name1" ref="ref1" />
</bean>
A:
"myScope" is created through Java code.
Well then either switch to XML or to Java-based configuration. If you do, your scope can have lifecycle callback methods, implement InitializingBean etc.
If you don't you have to do all that yourself programmatically when you initialize your scope. You would use applicationContext.getAutowireCapableBeanfactory() and use the AutowireCapableBeanFactory to wire the scope manually, using something like
AutowireCapableBeanFactory.initializeBean(Object, String) to post-process the scope (which will also execute any registered lifecycle callbacks).
|
[
"stackoverflow",
"0049191237.txt"
] | Q:
How to use scanner to read accented characters from file in correct way?
I have this method:
public static void readFile(String input)
throws FileNotFoundException, IOException{
try (Scanner sc = new Scanner(new File(input));){
while (sc.hasNextLine()){
String currentLine = sc.nextLine();
if(sc.hasNextLine()){
String nextLine = sc.nextLine();
System.out.println("currentLine\t"+currentLine);
System.out.println("nextLine\t"+nextLine);
}
}
}
}
It works correctly, without any errors, or any problems, but this not write any content from the file. In the file I have some basic "lorem ipsum" text, just to see how this works.
If in the file only latin characters are then this works correctly, but if is there any other characters (ex: áéűőúüöó) then this not write any content from the file. Where can I have the problem? How can I resolve this?
A:
You probably have just single line and the bug is here:
while (sc.hasNextLine()){
String currentLine = sc.nextLine();
if(sc.hasNextLine()){
you get the current line but print it only when there is next line.
In this way last line will be missing.
Please remove the IF condition.
EDIT:
After question editing please try to give proper encoding ex for UTF8:
new Scanner(new File(fileName), StandardCharsets.UTF_8.name());
|
[
"stackoverflow",
"0060834866.txt"
] | Q:
Does each stacked transaction use a separate connection?
I have multiple stacked transactions created by calling stacked methods with:
@Transactional(propagation = Propagation.REQUIRES_NEW)
so the result is transaction waiting for new transaction waiting for new transaction...
Do each of these transactions use a separate db connection from the connection pool, possibly starving the pool?
P.S.: I know that I shouldn't stack new transactions due to errors not rolling back all transactions, but I'm curious about the behaviour.
A:
Yes, when you are using REQUIRES_NEW you will get a new transaction for every method call . New transaction means, new database connection from the pool is being used.
And yes, that means potentially starving it.
You might enjoy this database transactions book for more detailed information including lots of code examples: https://www.marcobehler.com/books/1-java-database-connections-transactions
|
[
"stackoverflow",
"0019911685.txt"
] | Q:
CakePHP trying to send a ajax request
I'm trying to send a ajax requistion to a controller, that it should returns something, but isn't.
My element (View/Elements/list.ctp):
<script type="text/javascript">
$(document).ready(function(){
$('#click').click(function(){
$.ajax({
type: "POST",
url: '<?php echo Router::url(array('controller' => 'products', 'action' => 'showProducts')); ?>',
success: function(data){
alert(data);
}
});
});
});
</script>
<p id="click">Click me!</p>
Controller products:
<?php
class ProductsController extends AppController {
public $helpers = array('Js' => array('Jquery'));
public $components = array('RequestHandler');
var $name = 'Products';
function showProducts(){
return 'This should to return in jQuery data';
}
}
?>
A:
In cakePHP 2.x your controller needs to be in this way to return json data to the $.ajax request :
<?php
App::uses('AppController', 'Controller');
App::uses('JsBaseEngineHelper', 'View/Helper');
class AjaxtestsController extends AppController {
function beforeFilter() {
parent::beforeFilter();
}
public function returnsSomthing()
{
$layout = 'ajax'; // you need to have a no html page, only the data.
$this->autoRender = false; // no need to render the page, just plain data.
$data = array();
$jquerycallback = $_POST["callback"];
//do something and then put in $data those things you want to return.
//$data will be transformed to JSON or what you configure on the dataType.
echo JsBaseEngineHelper::object($data,array('prefix' => $jquerycallback.'({"totalResultsCount":'.count($data).',"ajt":','postfix' => '});'));
}
}
Improved Answer
You can use your controller's methods to search data on the db: find(), but I move the search queries to the Model:
First: Add the marked lines at the model code
App::uses('AppModel', 'Model');
App::uses('Sanitize', 'Utility'); // <---
App::uses('JsBaseEngineHelper', 'View/Helper'); // <---
Second: Create a Model method that executes the search:
public function getdata(){
$input = NULL;
$query = array();
$sql = NULL;
$data = array();
$i = 0;
$input = $_GET["name_startsWith"]; // <-- obtains the search parameter
$input = Sanitize::clean($input); // <-- prepares the search parameter
$sql = "select * from atable where condition like '".$input."%';";
$query = $this->query($sql); // <-- the model execute the search
if ($query){
$c = count($query);
for($i=0;$i<$c;$i++){ // <-- iterate over the returned data
$json['id'] = $query[$i][0]['id'];
$json['column1'] = $query[$i][0]['column1'];
$json['column2'] = $query[$i][0]['column2'];
$data[] = $json; // <-- the data it's stored on an multiarray, to be converted to JSON
}
}
$jquerycallback = $_GET["callback"];
echo JsBaseEngineHelper::object($data,array('prefix' => $jquerycallback.'({"totalResultsCount":'.count($query).',"search":','postfix' => '});')); //<-- the data it´s returned as JSON
}
Then: On the controller create a method to call the search
public function getdata()
{
$layout = 'ajax'; //<-- No LAYOUT VERY IMPORTANT!!!!!
$this->autoRender = false; // <-- NO RENDER THIS METHOD HAS NO VIEW VERY IMPORTANT!!!!!
$this->Cliente->getclient(); // <-- Get the data
}
You can call this method via ajax like this:
$.ajax({
url: "/application/controller/getdata",
dataType: "jsonp",
data: {
featureClass: "P",
style: "full",
maxRows: 10,
name_startsWith: request.term
},
success: function( data ) {
response( $.map( data.search, function( item ) {
return {
value: item.id,
label: item.column1+" "+item.column2
}
}));
}
});
Check this for more info:
CakePHP Controller:autorender
CakePHP JsonView
|
[
"stackoverflow",
"0060324614.txt"
] | Q:
suppress output on library import in python
I have a library that I need to import on my code. However, whenever it is imported it outputs several lines of data to the console. How can I suppress the output?
Thanks
A:
import os
import sys
# silence command-line output temporarily
sys.stdout, sys.stderr = os.devnull, os.devnull
# import the desired library
import library
# unsilence command-line output
sys.stdout, sys.stderr = sys.__stdout__, sys.__stderr__
|
[
"stackoverflow",
"0012042730.txt"
] | Q:
debug variable in xcode
A variable in my code is being de-allocated somewhere, and i don't know where. I'm trying to debug it, but there is a lot of code to search through.
Is there a way to follow a variable, and show where it is being modified?
A:
Right click on the variable in XCode's debugging window, and select "Watch variable".
Alternatively, use gdb:
http://scottmcpeak.com/memory-errors/
This is discussed here in a similar topic:
Tracking variable or memory change in Xcode?
|
[
"stackoverflow",
"0055762658.txt"
] | Q:
How to repeat character in HTML with responsive resizing?
I am trying to create rows in a DIV where there are three pieces of information to display. A left align text, a right align text, and repeat character "." between the two
I tried this using the HTML below. But it is not working with a div for each piece.
<div style="margin-bottom:5px"><!-- row 1 -->
<div style="float:left;">Left</div> <!-- left column -->
<div style="display: inline-block;">...</div> <!-- center column -->
<div style="float:right;">Right</div> <!-- center column -->
</div><!-- row 1 -->
I believe it most likely has to be done using just one div displaying one piece of text/string where the "." character gets repeated between the other two pieces of text. I cant figure it out so that the string changes with the DIV size - in order to keep it responsive.
A:
You could achieve that rather simply with flexbox and a dotted border.
.row { display: flex; }
.center {
flex-grow: 1;
border-bottom: 2px dotted black;
margin: 0 4px 4px;
}
<div class="row">
<div class="left">Left</div>
<div class="center"></div>
<div class="right">Right</div>
</div>
<div class="row">
<div class="left">This is some longer left text</div>
<div class="center"></div>
<div class="right">Right</div>
</div>
<div class="row">
<div class="left">Left</div>
<div class="center"></div>
<div class="right">This is some longer right text</div>
</div>
Make parent display: flex so that children align side-by-side.
Add flex-grow: 1 to the center so that it fills empty space
Add border-bottom: 2px dotted black to achieve your dotted line
Add some margins to position and pad the dotted line properly
|
[
"stackoverflow",
"0053784998.txt"
] | Q:
How are the pytorch dimensions for linear layers calculated?
In the PyTorch tutorial, the constructed network is
Net(
(conv1): Conv2d(1, 6, kernel_size=(5, 5), stride=(1, 1))
(conv2): Conv2d(6, 16, kernel_size=(5, 5), stride=(1, 1))
(fc1): Linear(in_features=400, out_features=120, bias=True)
(fc2): Linear(in_features=120, out_features=84, bias=True)
(fc3): Linear(in_features=84, out_features=10, bias=True)
)
And used to process images with dimensions 1x32x32. They mention, that the network cannot be used with images with a different size.
The two convolutional layers seem to allow for an arbitrary number of features, so the linear layers seem to be related to getting the 32x32 into into 10 final features.
I do not really understand, how the numbers 120 and 84 are chosen there and why the result matches with the input dimensions.
And when I try to construct a similar network, I actually get the problem with the dimension of the data.
When I for example use a simpler network:
Net(
(conv1): Conv2d(3, 8, kernel_size=(5, 5), stride=(1, 1))
(conv2): Conv2d(8, 16, kernel_size=(5, 5), stride=(1, 1))
(fc1): Linear(in_features=400, out_features=3, bias=True)
)
for an input of the size 3x1200x800, I get the error message:
RuntimeError: size mismatch, m1: [1 x 936144], m2: [400 x 3] at /pytorch/aten/src/TH/generic/THTensorMath.cpp:940
Where does the number 936144 come from and how do I need to design the network, such that the dimensions are matching?
A:
The key step is between the last convolution and the first Linear block. Conv2d outputs a tensor of shape [batch_size, n_features_conv, height, width] whereas Linear expects [batch_size, n_features_lin]. To make the two align you need to "stack" the 3 dimensions [n_features_conv, height, width] into one [n_features_lin]. As follows, it must be that n_features_lin == n_features_conv * height * width. In the original code this "stacking" is achieved by
x = x.view(-1, self.num_flat_features(x))
and if you inspect num_flat_features it just computes this n_features_conv * height * width product. In other words, your first conv must have num_flat_features(x) input features, where x is the tensor retrieved from the preceding convolution. But we need to calculate this value ahead of time, so that we can initialize the network in the first place...
The calculation follows from inspecting the operations one by one.
input is 32x32
we do a 5x5 convolution without padding, so we lose 2 pixels at each side, we drop down to 28x28
we do maxpooling with receptive field of 2x2, we cut each dimension by half, down to 14x14
we do another 5x5 convolution without padding, we drop down to 10x10
we do another maxpooling, we drop down to 5x5
and this 5x5 is why in the tutorial you see self.fc1 = nn.Linear(16 * 5 * 5, 120). It's n_features_conv * height * width, when starting from a 32x32 image. If you want to have a different input size, you have to redo the above calculation and adjust your first Linear layer accordingly.
For the further operations, it's just a chain of matrix multiplications (that's what Linear does). So the only rule is that the n_features_out of previous Linear matches n_features_in of the next one. Values 120 and 84 are entirely arbitrary, though they were probably chosen by the author such that the resulting network performs well.
|
[
"stackoverflow",
"0056400930.txt"
] | Q:
Create counter column based on values in 2 dataframe columns
I am looking to create a counter column based on row values in 2 dataframe columns, represented here at Col1 and Col2.
An example of the dataset is as follows:
Col1 Col2
a 0
a 0
a 0
a 1
a 0
a 0
a 0
a 1
a 1
b 0
b 0
b 1
b 1
b 0
b 0
Where Col1 is an identification variable, and where I want the counter to start over when a new identification variable comes across (so when 'a' switches to 'b', the counter returns to 0).
Col2 is an indication of a new input in the data. When a 1 arises, a new input arises, and the 0s after that correspond to measurements in that input. Each time a 1 arises, I want the counter variable to increment 1. Each time the 1 returns to a 0 (and vice versa), I also want the counter to increment 1. Based on the above dataset, I want the output to look like the following in Col3:
Col1 Col2 Col3
a 0 0
a 0 0
a 0 0
a 1 1
a 0 2
a 0 2
a 0 2
a 1 3
a 1 4
b 0 0
b 0 0
b 1 1
b 1 2
b 0 3
b 0 3
So basically every time Col2 switches from a 0 to a 1, and each time a 1 arises, I want the counter to increment. Each time a 0 is present in Col2, I want the counter to remain the same value. And every time Col1 changes to a new ID (in this case, from 'a' to 'b') I want the counter to start over at 0.
I've been mainly doing this with conditional statements, but there are a ton of them and I'm looking to run this on a large dataset, which would take hours to run. Is there a quick and easy way to run something like this, with these conditions on both columns? Or does anyone have suggestions on transformations to this data that would make running a categorization like this easier?
I understand that this is a slightly confusing request, so please let me know if there is anything I can do to provide more clarity into what I'm looking for.
Thanks!
A:
df.assign(Col4=df1.groupby('Col1').Col2.apply(lambda x:
pd.Series(pd.np.r_[False,(x[1:]==1) |(x.values[1:] != x.values[:-1])].cumsum())).values)
Col1 Col2 Col3 Col4
0 a 0 0 0
1 a 0 0 0
2 a 0 0 0
3 a 1 1 1
4 a 0 2 2
5 a 0 2 2
6 a 0 2 2
7 a 1 3 3
8 a 1 4 4
9 b 0 0 0
10 b 0 0 0
11 b 1 1 1
12 b 1 2 2
13 b 0 3 3
14 b 0 3 3
|
[
"stackoverflow",
"0037781646.txt"
] | Q:
android- How to make screen helpers
I've seen this in lots of applications , when you open the application for the first time, to shows a semi transparent screen and mark a tools and shows some description about it .
like this :
as you can see,it marks an icon on menu and shows some text about it and there is a button at the end of the page .
How can I make something like this ?
A:
Try this way to get Showcase
View showcasedView = findViewById(R.id.view_to_showcase);
ViewTarget target = new ViewTarget(showcasedView);
ShowcaseView.insertShowcaseView(target, this, R.string.showcase_title, R.string.showcase_details);
OR you can try with TourGuide
|
[
"ru.stackoverflow",
"0001077780.txt"
] | Q:
Хранение абстрактного типа в stl::vector C++
Пытаюсь хранить в контейнере абстрактный тип "Weapon", но возникает ошибка.
Код:
class Ismth { // Абстрактный класс
virtual void draw() = 0;
};
class Weapon : public Ismth{ // Weapon наследуется от абстрактного класса. Без наследования ошибки не возникает
public:
Weapon() = default;
void draw() override {};
};
class Shotgun : public Weapon { // Конкретная реализация Weapon.
public:
Shotgun() = default;
void draw() override {}; // Именно тут я хочу реализовать draw() из Ismth
};
void main() {
vector<Weapon> weapons;
Shotgun weapon1;
weapons.push_back(weapon1);
}
Подскажите, пожалуйста, в чем может быть проблема? Возможно, в таком случае нужно использовать не vector?
Выдаёт:
In file included from D:/mingw64/lib/gcc/x86_64-w64-mingw32/7.3.0/include/c++/x86_64-w64-mingw32/bits/c++allocator.h:33:0,
from D:/mingw64/lib/gcc/x86_64-w64-mingw32/7.3.0/include/c++/bits/allocator.h:46,
from D:/mingw64/lib/gcc/x86_64-w64-mingw32/7.3.0/include/c++/string:41,
from D:/mingw64/lib/gcc/x86_64-w64-mingw32/7.3.0/include/c++/bits/locale_classes.h:40,
from D:/mingw64/lib/gcc/x86_64-w64-mingw32/7.3.0/include/c++/bits/ios_base.h:41,
from D:/mingw64/lib/gcc/x86_64-w64-mingw32/7.3.0/include/c++/ios:42,
from D:/mingw64/lib/gcc/x86_64-w64-mingw32/7.3.0/include/c++/ostream:38,
from D:/Libraries/SFML/include/SFML/System/Err.hpp:32,
from D:/Libraries/SFML/include/SFML/System.hpp:34,
from D:/Libraries/SFML/include/SFML/Audio.hpp:32,
from D:\ivan\Study\C & C++\problems3_laptop2\Pseudo3DEngine\main.cpp:1:
D:/mingw64/lib/gcc/x86_64-w64-mingw32/7.3.0/include/c++/ext/new_allocator.h: In instantiation of 'void __gnu_cxx::new_allocator<_Tp>::construct(_Up*, _Args&& ...) [with _Up = Weapon; _Args = {const Weapon&}; _Tp = Weapon]':
D:/mingw64/lib/gcc/x86_64-w64-mingw32/7.3.0/include/c++/bits/alloc_traits.h:475:4: required from 'static void std::allocator_traits<std::allocator<_CharT> >::construct(std::allocator_traits<std::allocator<_CharT> >::allocator_type&, _Up*, _Args&& ...) [with _Up = Weapon; _Args = {const Weapon&}; _Tp = Weapon; std::allocator_traits<std::allocator<_CharT> >::allocator_type = std::allocator<Weapon>]'
D:/mingw64/lib/gcc/x86_64-w64-mingw32/7.3.0/include/c++/bits/stl_vector.h:943:30: required from 'void std::vector<_Tp, _Alloc>::push_back(const value_type&) [with _Tp = Weapon; _Alloc = std::allocator<Weapon>; std::vector<_Tp, _Alloc>::value_type = Weapon]'
D:\ivan\Study\C & C++\problems3_laptop2\Pseudo3DEngine\Camera.h:112:34: required from here
D:/mingw64/lib/gcc/x86_64-w64-mingw32/7.3.0/include/c++/ext/new_allocator.h:136:4: error: invalid new-expression of abstract class type 'Weapon'
{ ::new((void *)__p) _Up(std::forward<_Args>(__args)...); }
^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
In file included from D:\ivan\Study\C & C++\problems3_laptop2\Pseudo3DEngine\main.cpp:12:0:
D:\ivan\Study\C & C++\problems3_laptop2\Pseudo3DEngine\Camera.h:31:7: note: because the following virtual functions are pure within 'Weapon':
class Weapon : virtual public Idrawable {
^~~~~~
In file included from D:\ivan\Study\C & C++\problems3_laptop2\Pseudo3DEngine\Object2D.h:11:0,
from D:\ivan\Study\C & C++\problems3_laptop2\Pseudo3DEngine\Poligon2D.h:8,
from D:\ivan\Study\C & C++\problems3_laptop2\Pseudo3DEngine\main.cpp:8:
D:\ivan\Study\C & C++\problems3_laptop2\Pseudo3DEngine\Idrawable.h:12:18: note: virtual void Idrawable::draw(sf::RenderWindow&)
virtual void draw(sf::RenderWindow& window) = 0;
^~~~
In file included from D:/mingw64/lib/gcc/x86_64-w64-mingw32/7.3.0/include/c++/bits/stl_tempbuf.h:60:0,
from D:/mingw64/lib/gcc/x86_64-w64-mingw32/7.3.0/include/c++/bits/stl_algo.h:62,
from D:/mingw64/lib/gcc/x86_64-w64-mingw32/7.3.0/include/c++/algorithm:62,
from D:/Libraries/SFML/include/SFML/System/Utf.hpp:32,
from D:/Libraries/SFML/include/SFML/System/String.hpp:32,
from D:/Libraries/SFML/include/SFML/System.hpp:42,
from D:/Libraries/SFML/include/SFML/Audio.hpp:32,
from D:\ivan\Study\C & C++\problems3_laptop2\Pseudo3DEngine\main.cpp:1:
D:/mingw64/lib/gcc/x86_64-w64-mingw32/7.3.0/include/c++/bits/stl_construct.h: In instantiation of 'void std::_Construct(_T1*, _Args&& ...) [with _T1 = Weapon; _Args = {Weapon}]':
D:/mingw64/lib/gcc/x86_64-w64-mingw32/7.3.0/include/c++/bits/stl_uninitialized.h:83:18: required from 'static _ForwardIterator std::__uninitialized_copy<_TrivialValueTypes>::__uninit_copy(_InputIterator, _InputIterator, _ForwardIterator) [with _InputIterator = std::move_iterator<Weapon*>; _ForwardIterator = Weapon*; bool _TrivialValueTypes = false]'
D:/mingw64/lib/gcc/x86_64-w64-mingw32/7.3.0/include/c++/bits/stl_uninitialized.h:134:15: required from '_ForwardIterator std::uninitialized_copy(_InputIterator, _InputIterator, _ForwardIterator) [with _InputIterator = std::move_iterator<Weapon*>; _ForwardIterator = Weapon*]'
D:/mingw64/lib/gcc/x86_64-w64-mingw32/7.3.0/include/c++/bits/stl_uninitialized.h:289:37: required from '_ForwardIterator std::__uninitialized_copy_a(_InputIterator, _InputIterator, _ForwardIterator, std::allocator<_Tp>&) [with _InputIterator = std::move_iterator<Weapon*>; _ForwardIterator = Weapon*; _Tp = Weapon]'
D:/mingw64/lib/gcc/x86_64-w64-mingw32/7.3.0/include/c++/bits/stl_uninitialized.h:311:2: required from '_ForwardIterator std::__uninitialized_move_if_noexcept_a(_InputIterator, _InputIterator, _ForwardIterator, _Allocator&) [with _InputIterator = Weapon*; _ForwardIterator = Weapon*; _Allocator = std::allocator<Weapon>]'
D:/mingw64/lib/gcc/x86_64-w64-mingw32/7.3.0/include/c++/bits/vector.tcc:426:6: required from 'void std::vector<_Tp, _Alloc>::_M_realloc_insert(std::vector<_Tp, _Alloc>::iterator, _Args&& ...) [with _Args = {const Weapon&}; _Tp = Weapon; _Alloc = std::allocator<Weapon>; std::vector<_Tp, _Alloc>::iterator = __gnu_cxx::__normal_iterator<Weapon*, std::vector<Weapon> >; typename std::_Vector_base<_Tp, _Alloc>::pointer = Weapon*]'
D:/mingw64/lib/gcc/x86_64-w64-mingw32/7.3.0/include/c++/bits/stl_vector.h:948:21: required from 'void std::vector<_Tp, _Alloc>::push_back(const value_type&) [with _Tp = Weapon; _Alloc = std::allocator<Weapon>; std::vector<_Tp, _Alloc>::value_type = Weapon]'
D:\ivan\Study\C & C++\problems3_laptop2\Pseudo3DEngine\Camera.h:112:34: required from here
D:/mingw64/lib/gcc/x86_64-w64-mingw32/7.3.0/include/c++/bits/stl_construct.h:75:7: error: invalid new-expression of abstract class type 'Weapon'
{ ::new(static_cast<void*>(__p)) _T1(std::forward<_Args>(__args)...); }
^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
mingw32-make.exe[3]: *** [CMakeFiles\Pseudo3DEngine.dir\build.make:63: CMakeFiles/Pseudo3DEngine.dir/main.cpp.obj] Error 1
mingw32-make.exe[3]: *** Waiting for unfinished jobs....
In file included from D:/mingw64/lib/gcc/x86_64-w64-mingw32/7.3.0/include/c++/x86_64-w64-mingw32/bits/c++allocator.h:33:0,
from D:/mingw64/lib/gcc/x86_64-w64-mingw32/7.3.0/include/c++/bits/allocator.h:46,
from D:/mingw64/lib/gcc/x86_64-w64-mingw32/7.3.0/include/c++/vector:61,
from D:\ivan\Study\C & C++\problems3_laptop2\Pseudo3DEngine\Object2D.h:9,
from D:\ivan\Study\C & C++\problems3_laptop2\Pseudo3DEngine\Camera.h:8,
from D:\ivan\Study\C & C++\problems3_laptop2\Pseudo3DEngine\Camera.cpp:7:
D:/mingw64/lib/gcc/x86_64-w64-mingw32/7.3.0/include/c++/ext/new_allocator.h: In instantiation of 'void __gnu_cxx::new_allocator<_Tp>::construct(_Up*, _Args&& ...) [with _Up = Weapon; _Args = {const Weapon&}; _Tp = Weapon]':
D:/mingw64/lib/gcc/x86_64-w64-mingw32/7.3.0/include/c++/bits/alloc_traits.h:475:4: required from 'static void std::allocator_traits<std::allocator<_Tp1> >::construct(std::allocator_traits<std::allocator<_Tp1> >::allocator_type&, _Up*, _Args&& ...) [with _Up = Weapon; _Args = {const Weapon&}; _Tp = Weapon; std::allocator_traits<std::allocator<_Tp1> >::allocator_type = std::allocator<Weapon>]'
D:/mingw64/lib/gcc/x86_64-w64-mingw32/7.3.0/include/c++/bits/stl_vector.h:943:30: required from 'void std::vector<_Tp, _Alloc>::push_back(const value_type&) [with _Tp = Weapon; _Alloc = std::allocator<Weapon>; std::vector<_Tp, _Alloc>::value_type = Weapon]'
D:\ivan\Study\C & C++\problems3_laptop2\Pseudo3DEngine\Camera.h:112:34: required from here
D:/mingw64/lib/gcc/x86_64-w64-mingw32/7.3.0/include/c++/ext/new_allocator.h:136:4: error: invalid new-expression of abstract class type 'Weapon'
{ ::new((void *)__p) _Up(std::forward<_Args>(__args)...); }
^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
In file included from D:\ivan\Study\C & C++\problems3_laptop2\Pseudo3DEngine\Camera.cpp:7:0:
D:\ivan\Study\C & C++\problems3_laptop2\Pseudo3DEngine\Camera.h:31:7: note: because the following virtual functions are pure within 'Weapon':
class Weapon : virtual public Idrawable {
^~~~~~
In file included from D:\ivan\Study\C & C++\problems3_laptop2\Pseudo3DEngine\Object2D.h:11:0,
from D:\ivan\Study\C & C++\problems3_laptop2\Pseudo3DEngine\Camera.h:8,
from D:\ivan\Study\C & C++\problems3_laptop2\Pseudo3DEngine\Camera.cpp:7:
D:\ivan\Study\C & C++\problems3_laptop2\Pseudo3DEngine\Idrawable.h:12:18: note: virtual void Idrawable::draw(sf::RenderWindow&)
virtual void draw(sf::RenderWindow& window) = 0;
^~~~
In file included from D:/mingw64/lib/gcc/x86_64-w64-mingw32/7.3.0/include/c++/vector:62:0,
from D:\ivan\Study\C & C++\problems3_laptop2\Pseudo3DEngine\Object2D.h:9,
from D:\ivan\Study\C & C++\problems3_laptop2\Pseudo3DEngine\Camera.h:8,
from D:\ivan\Study\C & C++\problems3_laptop2\Pseudo3DEngine\Camera.cpp:7:
D:/mingw64/lib/gcc/x86_64-w64-mingw32/7.3.0/include/c++/bits/stl_construct.h: In instantiation of 'void std::_Construct(_T1*, _Args&& ...) [with _T1 = Weapon; _Args = {Weapon}]':
D:/mingw64/lib/gcc/x86_64-w64-mingw32/7.3.0/include/c++/bits/stl_uninitialized.h:83:18: required from 'static _ForwardIterator std::__uninitialized_copy<_TrivialValueTypes>::__uninit_copy(_InputIterator, _InputIterator, _ForwardIterator) [with _InputIterator = std::move_iterator<Weapon*>; _ForwardIterator = Weapon*; bool _TrivialValueTypes = false]'
D:/mingw64/lib/gcc/x86_64-w64-mingw32/7.3.0/include/c++/bits/stl_uninitialized.h:134:15: required from '_ForwardIterator std::uninitialized_copy(_InputIterator, _InputIterator, _ForwardIterator) [with _InputIterator = std::move_iterator<Weapon*>; _ForwardIterator = Weapon*]'
D:/mingw64/lib/gcc/x86_64-w64-mingw32/7.3.0/include/c++/bits/stl_uninitialized.h:289:37: required from '_ForwardIterator std::__uninitialized_copy_a(_InputIterator, _InputIterator, _ForwardIterator, std::allocator<_Tp>&) [with _InputIterator = std::move_iterator<Weapon*>; _ForwardIterator = Weapon*; _Tp = Weapon]'
D:/mingw64/lib/gcc/x86_64-w64-mingw32/7.3.0/include/c++/bits/stl_uninitialized.h:311:2: required from '_ForwardIterator std::__uninitialized_move_if_noexcept_a(_InputIterator, _InputIterator, _ForwardIterator, _Allocator&) [with _InputIterator = Weapon*; _ForwardIterator = Weapon*; _Allocator = std::allocator<Weapon>]'
D:/mingw64/lib/gcc/x86_64-w64-mingw32/7.3.0/include/c++/bits/vector.tcc:426:6: required from 'void std::vector<_Tp, _Alloc>::_M_realloc_insert(std::vector<_Tp, _Alloc>::iterator, _Args&& ...) [with _Args = {const Weapon&}; _Tp = Weapon; _Alloc = std::allocator<Weapon>; std::vector<_Tp, _Alloc>::iterator = __gnu_cxx::__normal_iterator<Weapon*, std::vector<Weapon> >; typename std::_Vector_base<_Tp, _Alloc>::pointer = Weapon*]'
D:/mingw64/lib/gcc/x86_64-w64-mingw32/7.3.0/include/c++/bits/stl_vector.h:948:21: required from 'void std::vector<_Tp, _Alloc>::push_back(const value_type&) [with _Tp = Weapon; _Alloc = std::allocator<Weapon>; std::vector<_Tp, _Alloc>::value_type = Weapon]'
D:\ivan\Study\C & C++\problems3_laptop2\Pseudo3DEngine\Camera.h:112:34: required from here
D:/mingw64/lib/gcc/x86_64-w64-mingw32/7.3.0/include/c++/bits/stl_construct.h:75:7: error: invalid new-expression of abstract class type 'Weapon'
{ ::new(static_cast<void*>(__p)) _T1(std::forward<_Args>(__args)...); }
^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
mingw32-make.exe[3]: *** [CMakeFiles\Pseudo3DEngine.dir\build.make:105: CMakeFiles/Pseudo3DEngine.dir/Camera.cpp.obj] Error 1
mingw32-make.exe[2]: *** [CMakeFiles\Makefile2:72: CMakeFiles/Pseudo3DEngine.dir/all] Error 2
mingw32-make.exe[1]: *** [CMakeFiles\Makefile2:84: CMakeFiles/Pseudo3DEngine.dir/rule] Error 2
mingw32-make.exe: *** [Makefile:117: Pseudo3DEngine] Error 2
A:
А как вы себе представляете экземпляр абстрактного типа?...
Да даже если бы и можно было - то получали бы вы при хранении потомков срезку. Например, добавив потомку какой-нибудь int - он бы при сохранении срезался.
Так что лучше храните, например, указатели на Weapon.
Можно поиграться с reference_wrapper и хранить якобы ссылки, но это только лишние телодвижения и сложности без ощутимой выгоды.
|
[
"stackoverflow",
"0037880834.txt"
] | Q:
scala - cannot resolve symbol Map
I´m writing a simple code to test CEP library in Scala, maven dependency version 1.1-SNAPSHOT. My code:
val res = igd.filter(_._2 == 13)
val pattern: Pattern[(Long,String,String,Long), _] = Pattern.begin[(Long,String,String,Long)]("start").where(_._3 == true).next("end").where(_._3 == false)
val patternStream: PatternStream[(Long,String,String,Long)] = CEP.pattern(res, pattern)
def selectFn(pattern : mutable.Map[String,(Long,String,String,Long)]): String = {
val startEvent = pattern.get("start").get
"Alerta:"+startEvent._1+": Pattern"
}
val patternStreamSelected = patternStream.select(selectFn(_)).print
In selecFn the Map is in red with the message cannot resolve symbol Map
Where is the problem?? Thank you in advance.
A:
oh, my..., i was importing scala.collection.parallel.mutable instead of scala.collection.mutable. Anyway, i think the scala lib still does not work, my little test didn´t do it, you can read Simple Scala API for CEP example don't show any output
|
[
"stackoverflow",
"0047945260.txt"
] | Q:
Create content which updates asynchronously PHP
I'm trying to create a trading bot with PHP.
I would like to get the value of the currency and update it even without refreshing the page.
In order to do this I should execute this call every 5-10 seconds.
Is that correct?
$summ = $d->getMarketSummary("USDT-BTC");
Is there a way to do this asynchronously? Even if user doesn't reload the whole page.
I've heard of AJAX, but it's Javascript.
Thank you in advance.
A:
You've heard it correctly, you need to do this in JavaScript, with AJAX. There are two parts for this:
1) You need to make an API in PHP, a route that will only respond with the data you want. So a page that when called:
<?php
$summ = $d->getMarketSummary("USDT-BTC");
echo $summ;
?>
And mapped to a url, let's say /data.
2) You need to make a JS in your page that calls that newly created route every-so-often; for that your need to use ajax (xmlhttprequest or Fetch API), and use the setInterval function to call it regularly and update the data in your page accordingly.
|
[
"stackoverflow",
"0039110644.txt"
] | Q:
Sections with different cell size with UICollectionView
I have to create a view in a Swift project with two differentiate sections.
The first one has seven cells with square shape. The second one has three cells with rectangular shape. Data inside cells are static.
In all cases, the sections should fit the entire screen width (mostly in landscape mode).
I don't have much experience using UICollectionViewController so I decided to accomplish this using one UICollectionViewController class and two reusable cells, but when I set the first section cell width the second one is also affected and then cells width is cut.
Is my point correct?
Shall I use different UICollectionViewControllers (one per section)?
Update: My Controller code
import UIKit
class InverterController: UICollectionViewController, UICollectionViewDelegateFlowLayout {
let moduleCell = "moduleCell"
let parameterCell = "parameterCell"
func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, referenceSizeForHeaderInSection section: Int) -> CGSize {
if section > 0 {
return CGSizeZero
} else {
return CGSize(width: collectionView.frame.width, height: CGFloat(195))
}
}
func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAtPath indexPath: NSIndexPath) -> CGSize {
var newSize = CGSizeZero
if indexPath.section == 0 {
newSize = CGSizeMake(CGFloat(105), CGFloat(105))
} else {
newSize = CGSizeMake(CGFloat(313), CGFloat(200))
}
return newSize
}
override func collectionView(collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, atIndexPath indexPath: NSIndexPath) -> UICollectionReusableView {
switch kind {
case UICollectionElementKindSectionHeader:
let headerView = collectionView.dequeueReusableSupplementaryViewOfKind(kind, withReuseIdentifier: "inverterHeader", forIndexPath: indexPath)
return headerView
default:
assert(false, "Unexpected element kind")
}
}
/**
Two sections in this UICollectionView: First one for clock items, second one for other parameters.
*/
override func numberOfSectionsInCollectionView(collectionView: UICollectionView) -> Int {
return 2
}
/**
First section contains one cell
Second section contains three cells
*/
override func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
var items = 0
if section == 0 {
items = 7
} else {
items = 3
}
return items
}
override func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
var cellIdentifier = ""
if indexPath.section == 0 {
cellIdentifier = moduleCell
} else {
cellIdentifier = parameterCell
}
let cell = collectionView.dequeueReusableCellWithReuseIdentifier(cellIdentifier, forIndexPath: indexPath)
cell.layer.cornerRadius = 6
cell.layer.masksToBounds = true
return cell
}
}
Interface Builder configuration for CollectionView
Simulator screenshot (non desired result; all cells have the same width)
A:
You can use collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAtIndexPath indexPath: NSIndexPath) -> CGSize delegate method to adjust cell size.
In your case you could write something like this:
func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAtIndexPath indexPath: NSIndexPath) -> CGSize {
let width : CGFloat
let height : CGFloat
if indexPath.section == 0 {
// First section
width = collectionView.frame.width/7
height = 50
return CGSizeMake(width, height)
} else {
// Second section
width = collectionView.frame.width/3
height = 50
return CGSizeMake(width, height)
}
}
Put this code inside your collectionViewController class.
Set height to what your cell height should be. You might want to adjust width if you're using spacing between cells or insets in your collectionView.
|
[
"stackoverflow",
"0023144643.txt"
] | Q:
Use callback function to create variables and use in a html element
Firstly excuse my ignorance with any inaccurate information I provide I a very new to javascript, jquery and json.
Anyway I have a script which pulls data from a json file and displays in a webpage with the help of javascript, jquery, ajax(i think) and json.
There is a callback for when I get back the results:
function searchCallback(data) {
$(document.body).append('<h1>' + data.title + '</h1>');
}
And it works fine the like this. However I want data.title (json object) to be displayed in a html element of my choice without having to use $(document.body) because my page won't display correctly at I have other html elements outside the script.
As far as I know (excuse ignorance) with javascript I can possible add a variable and use it as follows:
var title = data.title;
And in my html:
<span id="title"></span>
or maybe there is cleaner way?
Anyway how do I achieve this. Thank you for any help!!
A:
If you want to find an element and modify, jQuery makes this easy. Instead of $(document.body).append find an existing element by it's id, and then call the text method on it to replace the text inside that element with something new.
$('#title').text(data.title);
|
[
"stackoverflow",
"0009806368.txt"
] | Q:
how to display dicom image in matlab?
I want to ask about this function in matlab dicomread
example :
a = dicomread ('m.dcm');
imshow(a)
the image showed in the screen but it is very dark.....I wonder way it is dark and not normal.
I checked with different dicom images but the problem remain.
I hope you can help me and
thanks in advance.
A:
If you are dealing with monochrome images, you can set a linear scaling between a minimum and maximum pixel value as follows:
img = dicomread('filename');
imshow(img, [minAllowedPixValue maxAllowedPixValue]);
Alternately, you can display the image at full dynamic range:
imshow(img, []);
A:
I think you need to read the image colormap together with the data, then pass it to IMSHOW:
[a, amap] = dicomread ('m.dcm');
imshow(a,amap)
|
[
"stackoverflow",
"0027973879.txt"
] | Q:
insertBefore() an iframe jquery problems
I have to handle content from a WISIWYG where the user could potentially imbed a youtube video.
I need to search the container that the WISIWYG is outputted to for any iframe, and then wrap that iframe in a <div class="video-wrapper"> tag. Heres what I've tried:
$('div.content').each(function () {
var iframe = $(this).find('iframe');
$('<div class="video-wrapper">').insertBefore(iframe);
$('</div>').insertAfter(iframe);
});
This doesnt work and will end up just adding the div (including closing tag) right before the iframe.
Ideas?
A:
You should be using $.wrap. See: http://api.jquery.com/wrap/
$('div.content').each(function () {
$(this).find('iframe').wrap('<div class="video-wrapper"></div>');
});
A:
Use wrap - you can't add partial HTML like that, it's invalid:
var iframe = $(this).find('iframe');
iframe.wrap("<div class='video-wrapper' />");
|
[
"worldbuilding.stackexchange",
"0000060789.txt"
] | Q:
A fossilised ninetails
Background I'm doing a prehistoric nine-tails which would be believed to the common ancestor of the kitsune, the kumiho and the huli jing and five more species I made up, this early specimen lives in the Tibetan plateau during the Pliocene era just before the ice age started. The remains of this prehistoric fox was excavated from rocks up to 4,730 metres
Question How can the fossil be presented as, since the extra tails are merely dreads of matted fur? How can the pseudonym for my book tell it's a nine-tailed fox and not just another fox species?
A:
The tails could have anchoring points or vestigial joints where they connected even though they were just dreads of matted fur.
Alternatively in some circumstances impressions of fur could be left behind in a similar way to the way we've found fossilized feathers.
|
[
"stackoverflow",
"0013083925.txt"
] | Q:
How to solve this HTML/CSS bug?
It's a fairly complex page where the logic and tags looks like this (please don't worry about the scriplets, it's just for testing:
<div id="avd" <%if(request.getParameter("s")==null || !request.getParameter("s").equals("avd")) { %>style="display: none;"<%} %>>
<div class="fr10 smallg">
Förnamn Efternamn,<br>handläggarkod
</div>
<div class="fl10"></div>
<div class="fl20">Avdelad från:</div>
<div class="fl20">
<input type="text" id="avd_date" value="<%=ansokanInfo.getAvdf()%>" name="<%=PandoraFieldConstants.FIELD_AVDF%>"><input type="button" value="Sök" onClick="getElementById('popupA').style.display=''">
</div>
<div class="clear"></div>
<div class="fl10"></div>
<div class="fl20">Datum ingivningsdag:</div>
<div class="fl20">
<input type="text" id="avd_ing" value="<%=ansokanInfo.getAvdIngivningsdag()%>" name="<%=PandoraFieldConstants.FIELD_AVD_INGIVNINGSDAG%>" value="<%=ansokanInfo.getIngivningsDatum()%>"> <a href="#"><img src="images/cal.gif" alt="" width="16" height="15" border="0" onclick="javascript:openCalWin('620','300','<%=PandoraFieldConstants.FIELD_AVD_INGIVNINGSDAG%>')">
</a>
</div>
</div>
The display get to look like this:
The expected look is this:
What is wrong?
* {font-family:arial;}
.avnamn{
color: #90002b;
font-size: 140%;
display: inline;
vertical-align: 3%;
margin-left: 1%;
}
.b{border:1px solid #000;}
.readonly{background-color: #CCC;}
.Webdings{
font-family: Webdings;
}
ul{margin-top: 0px}
.mt3{margin-top:-3px;}
.mt5p{margin-top:5px;}
.fontS80 {font-size: 80%;}
a:link{color:#000; text-decoration:none; }
a:visited{color:#000; text-decoration:none; }
a:hover{color:#000; text-decoration:none; }
a:active{color:#000; text-decoration:none; }
.fontS75 {font-size: 75%;}
.link{color: #003366;
text-decoration: underline;
cursor: pointer;
font-weight: bold;}
.link_sm{color: #003366;
text-decoration: underline;
cursor: pointer;}
.link_sm{font-size: 70%;cursor: pointer;}
.small{font-size: 75%;}
.smallg{font-size: 75%;
color: #555;}
.ssmall{
font-size: 65%;
font-weight: bold;
color: #555;
}
.small60{font-size: 60%;}
.small50{
font-size: 50%;
color: #333;
}
.smallb{font-size: 85%;}
table{display:inline;}
h1{font-size: 130%;display:inline;}
h2{font-size: 100%;display:inline;}
h3{
font-size: 80%;
display:inline;
font-family: "Arial Unicode MS", Arial, Helvetica, sans-serif;
}
h4{font-size: 70%;display:inline;}
h5{
font-size: 80%;
display:inline;
font-family: "Arial Unicode MS", Arial, Helvetica, sans-serif;
}
.hthin{
font-size: 125%;
}
.th {text-align: left;}
td, th{font-size: 75%;
vertical-align: text-top;}
.td_link{cursor: pointer;}
.td40{height:40px;}
.td60{height:60px;}
.thkant{
border-top: 1px solid #000;
border-bottom: 1px solid #000;
font-size: 70%;
text-align: left;
}
.bb{border-bottom: 1px solid #000;}
.bbV{border-bottom: 1px solid #FFF;}
.TB_nbA {background-color:#CCC;}
.TB_bt, .TB_nb, .TB_db, .TB_bb {background-color:#efefdc;}
.hk {background-color:#d9ddb3;}
.hknot {background-color:#f9faf2;}
/*<!--F8F8F1-->*/
.TB_bt{border-top: 1px solid #FFF;}
.TB_bt5{border-top: 5px solid #FFF;}
.TB_bb{border-bottom: 1px solid #999;}
.TB_bb2{border-bottom: 2px solid #c1c1b3;}
.TB_db{border-bottom: 1px solid #000; border-top: 1px solid #000;}
.TB_tb{border-top: 2px solid #efefdc;}
.TB_bo{border: 2px solid #efefdc;}
.TB_bo_hk{border-top: 1px solid #efefdc;}
.TB_bo2{border: 1px solid #efefdc;}
.TB_bo2B{
border-top: 2px solid #c1c1b3;
border-left: 3px solid #efefdc;
border-right: 3px solid #efefdc;
border-bottom: 2px solid #c1c1b3;
}
.TD_bo{
border-right: 1px solid #c1c1b3;
width: 9%;
font-size: 70%;
text-align: center;
}
.TD_bo2{
border-right: 0;
width: 9%;
font-size: 70%;
text-align: center;
}
.ytb{
border-left:3px solid #efefdc;
border-right:3px solid #efefdc;
}
.datum {
font-size: 70%;
padding-right: 5px;
vertical-align: text-top;}
.sub {background:#EAEAEA;}
.sub_meny, .sub_meny_r, .sub_meny_active, .sub_meny_sm{
font-size: 70%;
padding-left: 20px;
padding-right: 20px;
vertical-align: text-top;}
.sub_meny_sm {
font-size: 60%;
vertical-align: middle;
padding-left: 10px;
padding-right: 10px;
}
.sub_meny_search{
position: absolute;
right: 265px;
font-size: 70%;
vertical-align: text-top;
}
.sub_meny_r{
float:right;
font-size: 70%;
padding-left: 8px;
padding-right: 8px;}
.sub_meny_rm{margin-top:4px;}
.sub_meny_active{font-weight: bold;}
.flikkant1 {
background-image: url(../images/fl1k.jpg);
background-position: center;
z-index: -1;}
.inl_namn{
font-weight: bold;
font-size: 70%;
color: Black;
text-decoration: none;}
.th{text-align: left;}
.tr{text-align: right;}
.g1{
background-color: #FFF;
line-height: 20px;
}
.g2{
background-color: #EEE;
line-height: 20px;
}
.g3{
background-color: #DCDCDC;
line-height: 20px;
font-weight: bold;
font-size: 100%;
}
.g4{
background-color: #CCC;
line-height: 20px;
}
.popuphandlaggare{
border-color: #000;
border-style: groove;
border-width: 2px;
padding: 0px;
background-color: #FFF;
font-size: 70%;
position: absolute;
top: 900px;
}
.popupN{
background-color: #F0F0E3;
color: #000;
width: 100%;
display: inline;
font-weight: bold;
height: auto;
padding: 2px;
border-bottom: 1px solid #000;
}
.pin{padding: 6px;}
.fl10, .fl20, .fl30, .fl40, .fl50, .fl60, .fl70, .fl80, .fl90, .fl100 {
padding-bottom:4px;color: #000000;
}
.over{
background-color: #EFEFDC;
line-height: 20px;
}
.half{
line-height:50%;
}
.quarter{
line-height:25%;
}
.lh10{
line-height:10%;
}
.checkmargin {margin-right: 25px;}
.checkmarginL {margin-left: 25px;}
.pusher {padding-left: 15px;}
.pusherR {margin-right: 40px;}
.rand3{background-color: #FFF; line-height: 3px;}
.rand1{background-color: #FFF; line-height: 1px;}
.whiteborder { color: #ffffff; border: 4px solid #ffffff; padding: 10px; margin: 10px; }
#details { width: 700px; color: #ffffff; }
.column1 { color: #000000; margin: 0; padding: 0; width: 600px; border:0; float: left; }
.column2 { color: #000000;margin: 0; padding: 0; border:0; width: 80px; float: right; }
.f200 {
color: #000000;
}
.f210 {
color: #000000;float: left;
}
.f220 {
width: 400px;
}
.f1450 {
width: 600px;
float:left;
}
.f1550 {
width: 150px;
float:left;
padding:15px;
}
.paddedcell {
padding:15px;
}
.b2{border:2px solid #efefdc;}
.inp_sel{width: 80%;}
.fl21{float:left; padding:5px; margin:5px; width:150px;} .fl455{float:left; padding:5px; margin:5px; width:120px;}
.form-bg {
background: #eeefdf;
width:1000px;
overflow:hidden;
}
.form-bg2 {
background: #eeefdf;
width:100%;
overflow:hidden;
}
.data-bar {
border-bottom:1px solid #fbfbf7;
display:inline-block;
padding:10px 10px;
}
.left {
float:left;
width:200px;
}
.discount {
float:right;
width:500px;
}
.discounts {
width:900px;
}
.right {
float:right;
width:700px;
}
.yta20 {
background: #eeefdf;
width:1100px;
}
.yta2 {
width:1100px;
}
.data-box {
width:650px;
height:100px;
border:1px solid #cbcbcb;
}
#table td {
margin:120px;
}
#personName { float:left; width:300px; } #otherDetails { float:right; width:450px; }
.th_rad_sort {border-bottom: 2px solid #000000; text-decoration: none;}
a img { border: 0; outline:0;}
.f { float: right; color: white; }
.handlaggare { width: 1000px; }
div.data-box-nat{
margin-bottom: 10px;
padding: 2px;
border: 2px solid gray;
width: 600px;
}
div.data-box-pct{
margin-bottom: 10px;
border: 2px solid gray;
width: 600px;
}
.popup{
border-color: #000;
border-style: groove;
border-width: 2px;
padding: 0px;
background-color: #FFF;
font-size: 75%;
}
.horizontal-gradient {
background: #1a2adb; /* Old browsers */
background: -moz-linear-gradient(left, #1a2adb 0%, #a1e6ed 100%); /* FF3.6+ */
background: -webkit-gradient(linear, left top, right top, color-stop(0%,#1a2adb), color-stop(100%,#a1e6ed)); /* Chrome,Safari4+ */
background: -webkit-linear-gradient(left, #1a2adb 0%,#a1e6ed 100%); /* Chrome10+,Safari5.1+ */
background: -o-linear-gradient(left, #1a2adb 0%,#a1e6ed 100%); /* Opera 11.10+ */
background: -ms-linear-gradient(left, #1a2adb 0%,#a1e6ed 100%); /* IE10+ */
background: linear-gradient(left, #1a2adb 0%,#a1e6ed 100%); /* W3C */
filter: progid:DXImageTransform.Microsoft.gradient( startColorstr='#1a2adb', endColorstr='#a1e6ed',GradientType=1 ); /* IE6-9 */
color: white;
width: 1055px;
}
#topBar {width:100%; background-color:#EFEFDC; display:inline-block;}
#topBar h2 {float:left}
#close {position:relative; float:right;}
.fl1, .fl2, .fl5, .fl10, .fl15, .fl20, .fl22, .fl25, .fl30, .fl35, .fl40, .fl45, .fl50, .fl55, .fl60, .fl65, .fl70, .fl75, .fl80, .fl85, .fl90, .fl95, .fl100 { float: left;}
.fl1 {width: 1%;}
.fl2 {width: 2%;}
.fl5 {width: 5%;}
.fl10 {width: 10%;}
.fl13 {width: 13%;}
.fl15 {width: 15%;}
.fl20 {width: 20%;}
.fl21 {width: 21%;}
.fl22 {width: 22%;}
.fl23 {width: 23%;}
.fl24 {width: 23%;}
.fl25 {width: 25%;}
.fl30 {width: 30%;}
.fl35 {width: 35%;}
.fl40 {width: 40%;}
.fl45 {width: 45%;}
.fl50 {width: 50%;}
.fl55 {width: 55%;}
.fl60 {width: 60%;}
.fl65 {width: 65%;}
.fl70 {width: 70%;}
.fl75 {width: 75%;}
.fl80 {width: 80%;}
.fl85 {width: 85%;}
.fl90 {width: 90%;}
.fl95 {width: 95%;}
.fl100 {width: 100%;}
.fr1, .fr5, .fr10, .fr15, .fr20, .fr25, .fr30, .fr35, .fr40, .fr45, .fr50, .fr55, .fr60, .fr65, .fr70, .fr75, .fr80, .fr85, .fr90, .fr95, .fr100 {
float: right;
}
.fr1 {width: 1%;}
.fr5 {width: 5%;}
.fr10 {width: 10%;}
.fr15 {width: 15%;}
.fr20 {width: 20%;}
.fr25 {width: 25%;}
.fr30 {width: 30%;}
.fr35 {width: 35%;}
.fr40 {width: 40%;}
.fr45 {width: 45%;}
.fr50 {width: 50%;}
.fr55 {width: 55%;}
.fr60 {width: 60%;}
.fr65 {width: 65%;}
.fr70 {width: 70%;}
.fr75 {width: 75%;}
.fr80 {width: 80%;}
.fr85 {width: 85%;}
.fr90 {width: 90%;}
.fr95 {width: 95%;}
.fr100 {width: 100%;}
.clearL {clear: left;}
.clearR {clear: right;}
.clear {clear: both;}
A:
It looks like you need to clear the float before these lines:
<div class="fl10"></div>
<div class="fl20">Avdelad från:</div>
Just add <div class="clear"></div> like you did here:
<div class="clear"></div>
<div class="fl10"></div>
<div class="fl20">Datum ingivningsdag:</div>
Or even better, add the .clearL class to the first div, like this:
<div class="fl10 clearL"></div>
<div class="fl20">Avdelad från:</div>
|
[
"stackoverflow",
"0039098364.txt"
] | Q:
Compare session variable with post variable via ajax request
I want when captcha code complete from user a request sent to a page and compare input string by user with value of captcha image (this value is stored in session value)
This is page contain ajax request(here isn't img tag but it isn't important!):
<html>
<body>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<input id="captcha" maxlength="5" onkeyup="myFunction()" value="">
<script>
function myFunction() {
var x = document.getElementById("captcha");
if(x.value.length==5){
$(document).ready(function(){
$.get("test.php",
function(data, status){
alert("Data: " + data + "\nStatus: " + status);
});
});
}
}
</script>
</body>
</html>
and this page is that get post request:
<?php
session_start();
$c=$_POST['captcha']; echo $c;echo gettype($c);
$s=$_SESSION['captcha']; echo $s;echo gettype($s);
if($c==$s) {
echo 'correct';
} else {
echo 'incorrect';
}
?>
But in response: type of session variable is NULL! Why?!
But type of post variable is string, but I'm sure session and post are equal.
And now how compare with together?
A:
This problem sloved! but i don't how exactly!
I work on serach ajax and of course again start sessions.
but it doesn't have problem before and after work on it.
but i thought better is on page that send request, session started.
and it worked!
then i deleted session_start() statement but it still worked :D
i think the code not in the mood :))
code of page send request:
<html dir="rtl">
<body>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<img id="captcha" src="captcha.php" width="160" height="45" border="1" alt="CAPTCHA">
<small><a href="#" onclick="
document.getElementById('captcha').src = 'captcha.php?' + Math.random();
document.getElementById('captcha_code').value = '';
return false;
">refresh</a></small>
<input id="fname" type="text" name="captcha" size="6" maxlength="5" onkeyup="myFunction()" value="">
<small id="massage-captcha">input number show on the image.</small>
<script>
function myFunction() {
var x = document.getElementById("fname");
if(x.value.length==5){
document.getElementById("massage-captcha").innerHTML = "please wait!";
$(document).ready(function(){
$.post("test.php",
{
captcha: x.value
},
function(data,status){
if(data=="correct"){
document.getElementById("massage-captcha").innerHTML = "correct";}else{
document.getElementById("massage-captcha").innerHTML = "incorrect";
}
});
});
}
else{
b.value="";
}
}
</script>
and file recive request:
<?php
session_start();
if($_POST['captcha']==$_SESSION['captcha']){echo 'correct';}
else{echo 'incorrect';}
?>
my last idea: session on the server removed after past pne day and now work fine!
|
[
"stackoverflow",
"0038357743.txt"
] | Q:
Pass void pointer as function parameter and cast it to timeval array
Assume I have a function calc_sum() and I want to measure its execution time. I have a callback function info_callback() which prints a message and calculates execution time, it takes void pointer as parameter. I want to cast void* to struct timeval * to retrieve start/end of execution time and calculate the difference, but I can't understand how to pass the pointer to array struct timeval * so that I can access its elements from within info_callback() function.
Whatever I try, I get segmentation fault...
How should I pass and cast pointers to get it work?
EDIT: fixed error in code as Andy Schweig suggested
#include <stdio.h>
#include <sys/time.h>
void calc_sum(int a, int b)
{
int k = a + b;
printf("sum = %d\n", k);
}
void info_callback(const char *msg, void *client_data)
{
struct timeval *t = (struct timeval *) client_data;
double time = (t[1].tv_sec - t[0].tv_sec) * 1000.0; // !!!SEGMENTATION FAULT!!!
time += (t[1].tv_usec - t[0].tv_usec) / 1000.0; //
printf("[TIME] %s: %f, ms", msg, time);
}
int main(int argc, char *argv[])
{
struct timeval t1, t2;
gettimeofday(&t1, NULL);
calc_sum(2, 3);
gettimeofday(&t2, NULL);
struct timeval * tr = (struct timeval*) malloc(2 * sizeof(struct timeval));
tr[0] = t1;
tr[1] = t2;
double time = (tr[1].tv_sec - tr[0].tv_sec) * 1000.0; // sec to ms
time += (tr[1].tv_usec - tr[0].tv_usec) / 1000.0; // us to ms
printf("time = %f, ms\n", time);
info_callback("Execution time", tr);
free(tr);
}
A:
You should pass tr to info_callback instead of &tr. tr points to the array you allocated; &tr is a pointer to the pointer tr.
By the way, any particular reason for using void * instead of the actual type? If you had used the actual type, the compiler would have flagged this.
|
[
"electronics.stackexchange",
"0000037212.txt"
] | Q:
Short Channel Effects and FinFET?
I read that FinFET transistors were introduced to avoid the problems due to downscaling of MOSFET size, ie reduce the Short Channel Effects (SCEs) like DIBL, Hot Electron effects etc.
But how does the FinFET overcome these problems?
Or am I wrong? Is FinFET released to overcome any other problems in present planar MOSFETs?
A:
finFETs are new generation transistors which utilize tri-gate structure. In contrast to planar transistors where the Gate electrode was (usually) above the channel, the Gate electrode "wraps" the channel from three sides in finFETs:
The immediate and obvious advantage of finFETs is that the effective width of the channel becomes:
$$W_{eff}=2H_{Si}+W_{Si}$$
The above dependence is revolutionary in that the current capability of the transistor (which is lineaw in \$W_{eff}\$) may be increased by employing the "vertical dimension" - the transistor's height affects its current capability. However, it is not that simple to increase the height of the fins - there are many physical issues which must be addressed.
There are basically two major technologies for finFETs manufacturing: Silicon-on-Insulator (SOI) finFETs and Bulk finFETs:
The very first finFETs were manufactured on top of insulating layer. The fact that the current can't flow "underneath" the gate when the transistor is in OFF state reduces the leakage current. Alternative techniques for stopping leakage current from flowing in the bulk were introduced later, which allowed for manufacturing of Bulk finFETs. This technique utilizes very high doping gradients along the height of the fin in order to prevent the current from flowing in the bulk.
It is true that finFETs allow for reducing of DIBL effect due to intrinsically higher level of Gate control over the channel. This control comes from the fact that may depletion regions are bounded by the fin itself and do not extend into the bulk. However DIBL is still one of the major factors which affects finFETs threshold voltages. The following graph shows the profiles of constant DIBL on height ratio vs. width ratio graph:
One of the advantages of Bulk finFETs is apparent from the above graph: constrained by the same DIBL level, higher doping Bulk finFETs allow for physically higher fins (higher \$W_{eff}\$) as compared to SOI ones.
The fact that there is tight connection between \$W_{eff}\$ and \$L_D\$ is not special for finFETs - all deep submicron planar technologies also suffer from narrow width effects.
This was the basic overview of finFETs. I'm not that into their physics for more elaborate explanations.
As for finFETs adoption: Intel has already adopted finFETs (if I'm not mistaken, starting with 22nm technology). TSMC and Global Foundries are going to introduce their finFET processes in a few months (or, maybe, they have already introduced them).
|
[
"mathoverflow",
"0000233044.txt"
] | Q:
On generalization of rearrangement inequality
In fact, I'm intrested in such a question:
If $\sigma$ and $\pi$ are two permutations of $\{1,2,\ldots,n\}$
what is necessary and sufficient condition to be the following statement true. For all $a_1\geqslant a_2\geqslant \ldots \geqslant a_n$ and $b_1\geqslant b_2\geqslant \ldots \geqslant b_n$
$$
a_1b_{\sigma(1)}+a_2b_{\sigma(2)}+\ldots+a_nb_{\sigma(n)}\geqslant a_1b_{\pi(1)}+a_2b_{\pi(2)}+\ldots+a_nb_{\pi(n)}
$$
Consider graph $G$ with elements of $S_n$ as a vertices and connect $\sigma$ and $\pi$ from $\sigma$ to $\pi$ when $\sigma(i)=\pi(i)$ for all $i\in \{1,2,\ldots,n\}\setminus \{k,l\}$, $\sigma(k)=\pi(l)$, $\sigma(l)=\pi(k)$ and $\sigma(k)>\sigma(l)$.
Then for all $a_1\geqslant a_2\geqslant \ldots \geqslant a_n$ and $b_1\geqslant b_2\geqslant \ldots \geqslant b_n$ we have
$$
a_kb_{\sigma(k)}+a_lb_{\sigma(l)}-a_kb_{\pi(k)}-a_l{\pi(l)}=
(a_k-a_l)(b_{\sigma(k)}-b_{\sigma(l)})\geqslant 0
$$
In fact, if we can go from $\sigma$ to $\pi$ in $G$ then we can with certainty state that the inequality holds.
On the other hand, let's consider $\sigma$, $\pi\in S_3$:
$\sigma(1)=1$, $\sigma(2)=3$, $\sigma(3)=2$ and $\sigma(1)=2$, $\sigma(2)=1$, $\sigma(3)=3$. Then
$$
1\cdot 1+0\cdot 0+0\cdot 0\geqslant 1\cdot 0+0\cdot 1+0\cdot 0
$$
and
$$
0\cdot 0+0\cdot (-1)+(-1)\cdot 0\leqslant 0\cdot 0+0\cdot 0+(-1)\cdot (-1)
$$
So, I have no idea what to do in most general case.
A:
Necessary and sufficient condition is the following: for all $k\in \{1,\dots,n\}$, the sequence $\sigma(1),\dots,\sigma(k)$ strongly minorates $\pi(1),\dots,\pi(k)$, that means: if $u_1\leqslant \dots \leqslant u_k$ is increasing permutation of $\sigma(1),\dots,\sigma(k)$ and $v_1\leqslant \dots \leqslant v_k$ is increasing permutation of $\pi(1),\dots,\pi(k)$, then $u_i\leqslant v_i$ for all $i=1,\dots,k$.
At first, why is it necessary. Assume that it fails for some $k$, choose such a $k$ and set $a_1=\dots=a_i=1$, $a_{i+1}=\dots=a_n=0$. We get $b_{\sigma(1)}+\dots+b_{\sigma(k)}\geqslant b_{\pi(1)}+\dots+b_{\pi(k)}$. Fix $i\leqslant k$ such that $u_i>v_i$ and consider a sequence $b_m=\chi_{m\leqslant v_i}$. Then $b_{\pi(1)}+\dots+b_{\pi(k)}=i$, $b_{\sigma(1)}+\dots+b_{\sigma(k)}\leqslant i-1$, a contradiction.
Now why is it sufficient. As usual in such situations, we apply Abel transform. Denote $a_k=a_n+(c_{k}+\dots+c_{n-1})$ for $k=1,\dots,n-1$. Then $c_i\geqslant 0$ and we have
$$
\sum a_ib_{\sigma(i)}=a_n\sum b_i+\sum_{k=1}^{n-1} c_k(b_{\sigma(1)}+\dots+b_{\sigma(k)}).
$$
Rewrite analogously $\sum a_ib_{\pi(i)}$ and note that for each $k$
$$
b_{\sigma(1)}+\dots+b_{\sigma(k)}=b_{u_1}+\dots+b_{u_k}\geqslant
b_{v_1}+\dots+b_{v_k}=b_{\pi(1)}+\dots+b_{\pi(k)}.
$$
|
[
"stackoverflow",
"0035582932.txt"
] | Q:
bignum multiplication in SBCL
Yesterday I tried to figure out the size of the new Mersenne Prime (http://www.mersenne.org/primes/?press=M74207281)
on my SBCL box (v. 1.3.2 (x64), Windows 10, Dell Core i5 8GB RAM)
After almost one hour I gave up and interrupted the calculation.
Below the resulting screen:
This is SBCL 1.3.2, an implementation of ANSI Common Lisp.
More information about SBCL is available at <http://www.sbcl.org/>.
SBCL is free software, provided as is, with absolutely no warranty.
It is mostly in the public domain; some portions are provided under
BSD-style licenses. See the CREDITS and COPYING files in the
distribution for more information.
WARNING: the Windows port is fragile, particularly for multithreaded
code. Unfortunately, the development team currently lacks the time
and resources this platform demands.
* (- (expt 2 74207281) 1)
debugger invoked on a SB-SYS:INTERACTIVE-INTERRUPT in thread
'#<THREAD "main thread" RUNNING {1002A9BD03}>:'
Interactive interrupt at #x100008BD9E.
Type HELP for debugger help, or (SB-EXT:EXIT) to exit from SBCL.
restarts (invokable by number or by possibly-abbreviated name):
0: [CONTINUE] Return from SB-WIN32::SIGINT.
1: [ABORT ] Exit debugger, returning to top level.
1
(SB-BIGNUM:MULTIPLY-BIGNUMS #<unavailable argument> #<unavailable argument>)
0] 1
To me this was interesting, because I tried the same expression on Racket 6.4, on the same machine,
And it took (comparatively) only 1m08s to start spitting numbers.
In Haskell, again on the same machine, with
GHCi, version 7.10.3: http://www.haskell.org/ghc/ :? for help
Prelude> 2^74207281 - 1
it took only 8s to start the numbers' exhibition.
Despite the fact that it could be a bug, do anyone know how SBCL do bignum multiplication? Would its way of doing it be the possible cause of delay?
Thanks in advance!
*EDIT
After Sylvester´s comment, maybe the right question is: What is preventing the big number from been shown? Yes, it is really big (Racket and Haskell versions wrote it to a text file of 21 MB), but it seems that there is something more than its size preventing the task´s completion.
A:
The actual calculation is pretty fast on my machine, less than a second in fact.
(defun make-prime ()
(declare (optimize (safety 0)(debug 0)(speed 3)))
(time (- (expt 2 74207281) 1)))
(defparameter *prime* (make-prime))
;Evaluation took:
; 0.000 seconds of real time
; 0.000017 seconds of total run time (0.000015 user, 0.000002 system)
; 100.00% CPU
; 1,292 processor cycles
; 0 bytes consed
; ==> *PRIME*
However printing the number is a whole other matter.
|
[
"stackoverflow",
"0002536010.txt"
] | Q:
VSTO and Office 2010
Does VSTO 2008 work for Office 2010 or will it only be VSTO 2010? If it is VSTO 2010 then does this mean that I have to update all my clients to .NET 4.0?
A:
Yes, it will work, but there may be a few settings to tinker with. Unless VSTO 2008 allows building to .NET 4.0, it will still build for 3.5.
|
[
"stackoverflow",
"0061025839.txt"
] | Q:
Arrays.binarySearch() returns wrong insertion point
This is the code:
public class Main {
public static Scanner scanner = new Scanner(System.in);
public static void main(String[] args) throws IOException {
int arr[] = {10,50,999,1000};
int index = Arrays.binarySearch(arr,55);
System.out.println(index);
}
}
The output here is '-3', if the output from this formula "(-(insertion point) - 1)" that means the insertion point is '4' and that is not right.
So what i am missing?
A:
The insertion point is 2, not 4.
According to the official documentation:
The insertion point is defined as the point at which the key would be inserted into the array: the index of the first element greater than the key [...]
Your array with indices is
[10, 50, 999, 1000]
0 1 2 3
The first element greater than 55 is 999 at index 2. Remember that indices start counting at 0.
So the insertion point is 2. With the formula (-(insertion point) - 1) the return value must thus be:
(-(2) - 1) = -3
Which is exactly what you got.
|
[
"stackoverflow",
"0048443480.txt"
] | Q:
select data from multiple tables with total and other advance sql
i am having below table structure in my database
table1
userid, userName, userAddress
1,Manish,india
2,rita,usa
3,mariya,vietnam
table2
userid(fk table1),transactionType,transactionDesc,transactionAmt
1, credit, 10 installations, 50
2, credit, 8 installations, 40
1, debit, 1 Cust. Complain, 5
1, debit, 2 uninformed leave, 10
3, credit, 2 installations, 10
scenario
i wanted to build an sql query for selection of below structured data
userName,balanceToPay
manish, 35
rita, 40
mariya, 10
what i was doing was
datatable users = select * from table1
then foreach id in users
{ int total_credit = 0,total_debit=0
datatable credits = select transactionAmt from table2 where transactionType='credit' and userid = id
foreach TransAmt in credits
total_credit += transAmt
datatable debits = select transactionAmt from table2 where tansactionType = 'debit' and userid=id
foreach TransAmt in debits
total_debit += transAmt
publish row userName, balanceToPay(total_credits - total_debits)
}
it was working well when data was small like upto 30-40 users
but now its required for 3000-4000 users
if same applied in 3000 users then system will be waiting for longer n longer.
so i need experts to help me out in building an sql query
i tried SUM() but then it will only reduce inner loop.
so i thought of taking help of stack experts
A:
You should be executing a single aggregation query:
select t2.userid,
sum(case when t2.transactionType = 'credit' then transactionAmt
when t2.transactionType = 'debit' then -transactionAmt
else 0
end) as balanceToPay
from table2 t2
group by t2.userid;
I'll leave it to you adding the join to bring in the name.
|
[
"stackoverflow",
"0020916771.txt"
] | Q:
JMS not found in jboss 6?
I have run sample JMS application using Jboss 6.
This is hornetq-jms.xml file
<configuration xmlns="urn:hornetq"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="urn:hornetq /schema/hornetq-jms.xsd">
<connection-factory name="NettyConnectionFactory">
<connectors>
<connector-ref connector-name="netty"/>
</connectors>
<entries>
<entry name="/ConnectionFactory"/>
<entry name="/XAConnectionFactory"/>
</entries>
</connection-factory>
<connection-factory name="NettyThroughputConnectionFactory">
<connectors>
<connector-ref connector-name="netty-throughput"/>
</connectors>
<entries>
<entry name="/ThroughputConnectionFactory"/>
<entry name="/XAThroughputConnectionFactory"/>
</entries>
</connection-factory>
<connection-factory name="InVMConnectionFactory">
<connectors>
<connector-ref connector-name="in-vm"/>
</connectors>
<entries>
<entry name="java:/ConnectionFactory"/>
<entry name="java:/XAConnectionFactory"/>
</entries>
</connection-factory>
<queue name="DLQ">
<entry name="/queue/DLQ"/>
</queue>
<queue name="ExpiryQueue">
<entry name="/queue/ExpiryQueue"/>
</queue>
<queue name="testQueue">
<entry name="queue/queueA"/>
</queue>
<topic name="testTopic">
<entry name="/topic/topicA"/>
</topic>
</configuration>
After that i have run the sample program to send message to jms and got following error message
javax.naming.NameNotFoundException: jms not bound
at org.jnp.server.NamingServer.getBinding(NamingServer.java:771)
at org.jnp.server.NamingServer.getBinding(NamingServer.java:779)
at org.jnp.server.NamingServer.getObject(NamingServer.java:785)
at org.jnp.server.NamingServer.lookup(NamingServer.java:396)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
at java.lang.reflect.Method.invoke(Method.java:597)
at sun.rmi.server.UnicastServerRef.dispatch(UnicastServerRef.java:305)
at sun.rmi.transport.Transport$1.run(Transport.java:159)
at java.security.AccessController.doPrivileged(Native Method)
at sun.rmi.transport.Transport.serviceCall(Transport.java:155)
at sun.rmi.transport.tcp.TCPTransport.handleMessages(TCPTransport.java:535)
at sun.rmi.transport.tcp.TCPTransport$ConnectionHandler.run0(TCPTransport.java:790)
at sun.rmi.transport.tcp.TCPTransport$ConnectionHandler.run(TCPTransport.java:649)
at java.util.concurrent.ThreadPoolExecutor$Worker.runTask(ThreadPoolExecutor.java:886)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:908)
at java.lang.Thread.run(Thread.java:662)
This is sample program
import java.util.Properties;
import java.util.Scanner;
import javax.jms.*;
import javax.naming.Context;
public class QueueExample implements MessageListener
{
public void example() throws Exception
{
String destinationName = "queue/queueA";
Context ic = null;
ConnectionFactory cf = null;
Connection connection = null;
try
{
ic = getInitialContext();
cf = (ConnectionFactory)ic.lookup("/ConnectionFactory");
Queue queue = (Queue)ic.lookup(destinationName);
connection = cf.createConnection();
Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
MessageProducer publisher = session.createProducer(queue);
MessageConsumer subscriber = session.createConsumer(queue);
subscriber.setMessageListener(this);
connection.start();
TextMessage message = session.createTextMessage("Hello!");
publisher.send(message);
Scanner keyIn = new Scanner(System.in);
System.out.print("JMS Server listening. Type a Key + CR to exit\n");
keyIn.next();
}
finally
{
if(ic != null)
{
try
{
ic.close();
}
catch(Exception e)
{
e.printStackTrace();
//throw e;
}
}
// ALWAYS close your connection in a finally block to avoid leaks.
// Closing connection also takes care of closing its related objects e.g. sessions.
closeConnection(connection);
}
}
public synchronized void onMessage(Message message)
{
TextMessage text = (TextMessage)message;
String strMessage = null;
try {
strMessage = text.getText();
} catch (JMSException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("Message received: "+strMessage);
}
private void closeConnection(Connection con)
{
try
{
if (con != null)
{
con.close();
}
}
catch(JMSException jmse)
{
System.out.println("Could not close connection " + con +" exception was " + jmse);
}
}
protected boolean isQueueExample()
{
return true;
}
public static void main(String[] args) throws Exception
{
new QueueExample().example();
}
public static Context getInitialContext( )
throws javax.naming.NamingException {
Properties p = new Properties( );
p.put(Context.INITIAL_CONTEXT_FACTORY,
"org.jnp.interfaces.NamingContextFactory");
p.put(Context.URL_PKG_PREFIXES,
" org.jboss.naming:org.jnp.interfaces");
p.put(Context.SECURITY_PRINCIPAL, "testuser");
p.put(Context.SECURITY_CREDENTIALS, "test");
p.put(Context.PROVIDER_URL,"jnp://localhost:1099");
return new javax.naming.InitialContext(p);
/*Properties props = new Properties();
props.put(Context.INITIAL_CONTEXT_FACTORY, "org.jboss.naming.remote.client.InitialContextFactory");
props.put(Context.PROVIDER_URL, "remote://localhost:4447");
props.put(Context.SECURITY_PRINCIPAL, "testuser");
props.put(Context.SECURITY_CREDENTIALS, "password");
InitialContext context = new InitialContext(props);*/
}
}
How to resolve this Error? Is there anything wrong for configuration?
Please someone help me.
A:
It seems that your program wants to look-up some object from jndi within the path "jms". You may look in JBoss JNDI-tree where your objects are bound. Maybe it is "queueA".
I would try to use
String destinationName = "/queue/queueA";
and
<queue name="testQueue">
<entry name="/queue/queueA"/>
</queue>
instead of "queue/queueA" to put the queue into the global namespace.
For the start with JMS i would try a servlet as producer and a MDB as consumer. I think that would be easier.
|
[
"magento.stackexchange",
"0000054029.txt"
] | Q:
getChildHtml on category view
I want to load getChildHtml on category view. I just tried this:
Inside list.phtml I added this line:
<?php echo $this->getChildHtml('specificaties'); ?>
In local.xml I added this line inside
<catalog_category_layered>
<reference name="content"> :
<block type="catalog/product_list" name="specificaties" as="specificaties" template="catalog/product/list/specificaties.phtml"/>
And inside the specificaties.phtml I added this code:
<?php
$_helper = $this->helper('catalog/output');
$_product = $this->getProduct();
$theme = $this->helper('ultimo');
$helperSnippets = $this->helper('ultimo/rsnippets');
?>
<?php $yourCatIds = array(235);
$productCats = $_product->getAvailableInCategories();
if (count(array_intersect($yourCatIds,$productCats))) {
echo '<li class="test even">' . $_product->getAttributeText('i_display_diagonal_944_1') . '</li>';
echo '<li class="test even">' . $_product->getAttributeText('i_processor_family_2196_1') . '</li>';
echo '<li class="test even">' . $_product->getAttributeText('i_internal_memory_11381_1') . '</li>';
}
?>
But that breaks down the page. What am I doing wrong?
A:
Your attributes are most likely not set to "Use in product listing". This means there are no columns named i_display_diagonal_944_1 and so on in the table catalog_category_flat_store_X where X is the store id of the store view. In addition it's very likely that they are not in the result of the collection.
First you have to mark each attribute as "used in product listen" via manage attributes in the backend:
Then specifically for flat catalog, you have to write an observer that adds them to the result set:
Event: catalog_category_flat_loadnodes_before
Method details:
public function onCatalogCategoryFlatLoadnodesBefore($observer)
{
$extra = array('my_attribute', 'my_other_attribute');
$observer->getSelect()->columns($extra);
}
Edit (above is not the problem at all):
Your block isn't a product list: it doesn't handle the product collection, it handles one item of it. So $this->getProduct() doesn't give you anything, since Mage_Catalog_Block_Product_List has no method getProduct() nor a product attribute. Look into this piece of code (in a Magento 1.9.1 rwd template) that has hooks for things you want shown after the standard details:
<?php
// Provides extra blocks on which to hang some features for products in the list
// Features providing UI elements targeting this block will display directly below the product name
if ($this->getChild('name.after')) {
$_nameAfterChildren = $this->getChild('name.after')->getSortedChildren();
foreach ($_nameAfterChildren as $_nameAfterChildName) {
$_nameAfterChild = $this->getChild('name.after')->getChild($_nameAfterChildName);
$_nameAfterChild->setProduct($_product);
echo $_nameAfterChild->toHtml();
}
}
?>
So it's probably easiest to hook in there and the important part is that the product is passed on to the template. The same applies to for example <?php echo $this->getPriceHtml($_product, true) ?>, where again the product is passed onto the template.
Edit 2:
If you choose to split it out and use the parent's variable names, then change the type to core/template, as it doesn't need the catalog/product_list block information:
<block type="core/template" name="specificaties" template="catalog/product/list/specificaties.phtml"/>
|
[
"fitness.stackexchange",
"0000001762.txt"
] | Q:
Is it a good idea to use an exercise ball as a chair?
Does using an exercise ball help strengthen your core and back muscles?
Are there any concerns or downside with using a body exercise ball as a chair?
A:
Using an exercise ball as a desk chair is not a magic bullet. It will not work for all people and may actually hurt some. There is no replacement for strength training if you want a stronger core (including back muscles). Some articles I've read (I couldn't find a source other than the article themselves) suggest that you may be compressing your spine and discs while sitting on an exercise ball due to the constant muscles strain caused by trying to keep yourself balanced. These articles and other also suggest there is not good replacement for a fully ergonomic desk chair.
Like running barefoot or weight lifting, if you're going to switch to using a exercise ball as a chair you should transition slowly to allow your body to get use to it. I have personally used an exercise ball as a chair and loved it. I only stopped when my cats decided it was good fun to deflate the ball when I was sitting on it.
A:
Depends - If you tend to sit for prolonged periods without moving, sitting on an exercise ball (for part of the time) can help by giving you a more dynamic posture as your trunk muscles make frequent adjustments. I think of the effect as improving muscle control, so in that respect you could say it is strengthening your core and postural muscles.
For me, sitting on an exercise ball keeps me from slumping. I sit with a better posture and I feel that I have some carry over when I sit in my regular chair. I only use my ball intermittently.
Some down sides of using an exercise ball as a desk chair:
It may cause discomfort or pain depending on your back condition, especially if you use it for too long when you begin. (The up side is that it may make your back feel better.)
You can fall off :(
You may find sitting on plastic is not as comfortable as a padded chair.
Also, there is study that says in essence that the advantages of the increased trunk motion and muscle activity from sitting on an exercise ball, may be offset by the disadvantage of increased spinal shrinkage as compared to sitting in a regular chair. (This may be the study Sparafusile mentioned.)
If you sit on the ball to the point where your muscles fatigue, you are left with no back support, unlike you would have with an ergonomic chair.
|
[
"stackoverflow",
"0012231001.txt"
] | Q:
Like permalink on typepad?
I'm having an issue with http://blogs.salesforce.com. The like buttons should like the targeted blog however it does not actually share the page on facebook or do anything for that matter.
Any help is greatly appreciated.
Thanks!
Eric
A:
Eric,
Running one of the blog posts through the Debugger tool shows an issue with the og:url tag. It can't be empty, and should point to a valid url (current url), same for description. Without that, the Likes on the blog will work but they won't be Share-able on Facebook.
|
[
"stackoverflow",
"0044296561.txt"
] | Q:
Which data type and length is most suitable for an auto increment id column in database?
I am developing a website and using SQL Server as my database. I have a lot of entries every day and the id is auto incremented.
Should I use INT or BIGINT, or is there another suitable datatype?
A:
With a type of INT, starting at 1, you get over 2 billion possible rows - that should be more than sufficient for the vast majority of cases.
If you use an INT IDENTITY starting at 1, and you insert a row every second of every minute of every hour of every day, then you need 66.5 years before you hit the 2 billion limit ....
With BIGINT, you get roughly 922 quadrillion (922 with 15 zeros - 9'220'000 billions) - enough for you??
If you use a BIGINT IDENTITY starting at 1, and you insert one thousand rows every second, you need a mind-boggling 292 million years before you hit the 922 quadrillion limit ....
Read more about it (with all the options there are) in the MSDN Books Online.
|
[
"stackoverflow",
"0030199185.txt"
] | Q:
XSLT: Retain span between xml tag after transformation
I have a simple xml and xsl which is as follows:
XML
<p><span>a</span> <span>b</span></p>
XSL
<xsl:variable name="output">
<xsl:apply-templates select="//p"/>
</xsl:variable>
<xsl:value-of select="$output" />
<xsl:template match="p">
<xsl:apply-templates/>
</xsl:template>
<xsl:template match="span">
<xsl:if test="string-length(normalize-space(.)) > 0">
<xsl:apply-templates/>
</xsl:if>
</xsl:template>
Please note the space between the closing of first span tag and opening of second span tag.
Currently the output of this transformation gives:
Output
ab
Is there a way in XSLT where in we can retain the space between the span tag after transformation.
Desired Output
a b
Tried specifying xml:space="preserve" in both p and span template match tags. It just puts a lot of space.
Also my scenario doesn't give me option to add a place holder tag which could have been translated to empty whitespace.
A:
In the absence of any other overriding templates I would expect that fragment of XSLT to produce your desired result, unless you have an xsl:strip-space instruction at the top level of your stylesheet. If you have one of those declarations then you should remove it, or at least add
<xsl:preserve-space elements="p"/>
to countermand the strip-space for p elements specifically.
|
[
"stackoverflow",
"0011385019.txt"
] | Q:
How to get multiple values from jquery hash
How can i get multiple values in a jquery hash?
Example:
http://mysite.com/#l:value&v:id1212 same as but without page refresh http://mysite.com/?l=value&v=id1212
I thought something like:
var hash = location.hash.replace(/^.*?#/, '');
var lVal = (/^l:/.test( hash ));
var vVal = (/^v:/.test( hash ));
but how can i fix that var lVal only reads untill the & sign?
Am i on the right direction?
A:
Try to split your string by & sign and then retrieve values:
var hash = location.hash.replace(/^.*?#/, '');
var pairs = hash.split('&');
var lVal = pairs[0].split(':')[1];
var vVal = pairs[1].split(':')[1];
A:
I believe you might be looking for something like History.js to help you ease the pain. Also URI.js has a fragment-abuse plugin for data fragments. Otherwise try something like
var data = {};
var tokens = location.hash.substring(1).split('&');
for (var i=0, l=tokens.length; i < l; i++) {
var token = tokens[i].split(':');
// maybe token[1] is escaped or something?!
data[token[0]] = token[1];
}
console.log(data);
|
[
"stackoverflow",
"0063180393.txt"
] | Q:
Modify dateformat angular datepicker
I can't figure out how to change the date format to this DD/MM/YYYYY format and how to retrieve YYYYY-MM-DD to which I would add this without the 'T00:00:00Z' tildes.
Currently I have this type of format display side: 7/15/2020 or MM/DD/YYYYYY.
There are several threads that talk about this but none for what I want or something recent. I'm on Angular 10 with an Angular Material template.
historisation.component.html
<mat-form-field appearance="fill" >
<mat-label>Enter a date range</mat-label>
<mat-date-range-input [rangePicker]="picker">
<input matStartDate placeholder="Start date">
<input matEndDate placeholder="End date">
</mat-date-range-input>
<mat-datepicker-toggle matSuffix [for]="picker"></mat-datepicker-toggle>
<mat-date-range-picker #picker></mat-date-range-picker>
</mat-form-field>
</mat-card-content>
historisation.component.ts
I tried this without success
import { Component, OnInit, Injectable, ViewChild, ChangeDetectorRef } from '@angular/core';
import { RestApiService } from '../../shared/rest-api.service';
import { NotificationsService } from '../../shared/notifications.service';
import { FormControl } from '@angular/forms';
import { Observable, of, Subscription } from 'rxjs';
import { tap, startWith, debounceTime, switchMap, map, filter, distinctUntilChanged } from 'rxjs/operators';
import {MatPaginator} from '@angular/material/paginator';
import {MatSort} from '@angular/material/sort';
import {MatTableDataSource} from '@angular/material/table';
import {MomentDateAdapter} from '@angular/material-moment-adapter';
import {DateAdapter, MAT_DATE_FORMATS, MAT_DATE_LOCALE} from '@angular/material/core';
export const DD_MM_YYYY_Format = {
parse: {
dateInput: 'LL',
},
display: {
dateInput: 'DD/MM/YYYY',
monthYearLabel: 'MMM YYYY',
dateA11yLabel: 'LL',
monthYearA11yLabel: 'MMMM YYYY',
},
};
@Injectable({
providedIn: 'root'
})
@Component({
selector: 'app-historisation-deploiements',
templateUrl: './historisation-deploiements.component.html',
styleUrls: ['./historisation-deploiements.component.scss'],
providers: [
{provide: MAT_DATE_FORMATS, useValue: DD_MM_YYYY_Format},
]
})
I hope someone have an example for doing what i want. thanks !
A:
This answer respond to what you need. Hope it's OK.
On your app.module.ts :
import { registerLocaleData } from '@angular/common';
import localeFr from '@angular/common/locales/fr';
registerLocaleData(localeFr);
...
...
{ provide: LOCALE_ID, useValue: 'fr-FR' }
With this, you datepicker is displaying data in FR.
Now to convert it to another thing in your component :
import { DatePipe } from '@angular/common';
On your constrcutor : private datePipe: DatePipe
Create a function for testing :
const SearchStartDate = this.datePipe.transform(this.range.value.start,'yyyy-MM-dd');
const SearchEndDate = this.datePipe.transform(this.range.value.end,'yyyy-MM-dd');
console.log(SearchStartDate);
console.log(SearchEndDate);
On app.module side :
import { DatePipe } from '@angular/common';
Add Provider : DatePipe
Html Side updated like this :
<mat-date-range-input [rangePicker]="picker" [formGroup]="range">
<input matStartDate placeholder="Start date" formControlName="start">
<input matEndDate placeholder="End date" formControlName="end">
</mat-date-range-input>
<mat-datepicker-toggle matSuffix [for]="picker"></mat-datepicker-toggle>
|
[
"stackoverflow",
"0047484251.txt"
] | Q:
Stop PyCharm running pip as root
I need to create Django project in PyCharm. I'm using interpreter 3.6.3 at /usr/bin/python3.6. After creating it, I'm getting message Authentication is needed to run /usr/bin/python3.6 as the superuser. I clicked cancel and I've got:
Executed command: pip install Django
Error occurred: Non-zero exit code (126)
Proposed solution:
Try to run this command from the system terminal. Make sure that you use correct version of 'pip' installed for your Python interpreter located at '/usr/bin/python3.6'.
Command output:
Error executing command as another user: Request dismissed
However, if I'll give my password and click Authenticate then pip, pip3 and virtualenv will be broken because IDE is trying to install Django as root. How can I stop PyCharm running pip as root?
A:
to make PyCharm play nice with virtual environments, do the following:
1 - use shell to create virtualenv
create virtual environment: virtualenv <virtualEnvName>
activate virtual environment: . <virtualEnvName>/bin/activate
download packages into virtual environment: pip install <pkg>
2 - tell PyCharm about virtualenv you've created
open project in PyCharm: File > Open > urProject
select interpreter from virtualenv: PyCharm Community Edition > Preferences > Project > Project Interpreter
|
[
"stackoverflow",
"0014001475.txt"
] | Q:
How to display newer Google Map InfoWindows on top of older ones
I am having Google Map with InfoWindows being added dynamically. The issue is, when two InfoWindows overlap, the recent one won't always be on top of older ones.
How can I make sure latter InfoWindow always show up on top of all other InfoWIndows using Javascript/jQuery?
The InfoWindows are added when I receive new images and coordinates through websocket. Here is my code:
function addToMap(image) {
console.log("In addToMap...");
coordinates = image[2].split(',');
pin=new google.maps.LatLng(coordinates[0], coordinates[1]);
if(marker) {
marker.setMap(null);
}
var markerIcon = image_car_icon;
marker=new google.maps.Marker({
position:pin,
zIndexProcess: function( m )
{
return 9999999 + pin_count;
},
icon:markerIcon
});
marker.setMap(map);
map.setCenter(marker.getPosition());
pin_count++;
if(image[0] != "NOP") {
popup = new google.maps.InfoWindow({
content:'<image id="pin_' + pin_count + '" src="data:image/png;base64,' + image[1] +'"/>',
});
popup.open(map, marker);
}
}
popup is the InfoWindow created when I get a new image. Suppose two images have almost same coordinates, I want the second InfoWindow to be on top (z-index). But, most of the time, the first window stays on top.
A:
I have found out a solution. I am manually modifying the z-index of the marker by using the image as the handle. marker_count is a running marker, so the z-index will be greater than the previous marker.
google.maps.event.addListener(popup, 'domready', function() {
console.log("DOM READY...........................");
// Bring latest Image to top
e = $('#pin_' + img_count).parent().parent().parent().parent();
e.css({
'z-index' : (99999 + marker_count),
});
});
|
[
"math.stackexchange",
"0002862359.txt"
] | Q:
Finding global maxima with Kuhn-Tucker conditions (and distinguish them from other critical points)
We want to maximize $(x-1)^2 + (y-1)^2$ restricted to $x + y \le 2$ and $x, y \ge 0$.
I tried the following combinations:
$x \gt 0, y \gt 0$ This led me to no critical point.
$x \gt 0, y = 0$ This led me to these two critical points: $P_1(1, 0), \lambda = 0$ and $P_2(2, 0), \lambda = -2$.
$x = 0, y \gt 0$ This led me to these two critical points: $P_1(0, 1), \lambda = 0$ and $P_2(0, 2), \lambda = -2$.
$x = 0, y = 0$ This led me to these two critical points: $P_1(0, 0), \lambda = 0$ and $P_2(0, 0), \lambda \lt 2$.
My handbook says the global optima are: $x = 2, y = 0, \lambda = -2$ and $x = 0, y = 0, \lambda = 0$.
So here I have several questions:
1) How do I distinguish between global and local optima in these cases? The hessian matrix does not seem to be useful in this case. For example, how can I know that $x = 2, y = 0, \lambda = -2$ is a global optima, but $x = 1, y = 0, \lambda = 0$ is not? Intuition can help, but I want the method.
2) Why would $x = 2, y = 0, \lambda = -2$ be a global optima, and $x = 0, y = 2, \lambda = -2$ would not?
3) Why would $x = 0, y= 0, \lambda = 0$ be a global maxima? It is a bit counterintuitive.
4) Would it be impossible to determine the value of $\lambda$ in $P_2$ of $x = 0, y = 0$ combination? (This is the case in which we assume $\lambda \lt 0$, while in $P_1$ we assumed $\lambda = 0$).
5) Feel free to add any information needed to understand why the answer of my handbook is the correct one (which are the global maxima) and not all of above critical points, in case this is not clear with the answers to questions 1, 2, 3 and 4.
Thank you very much for your time.
A:
Graphically, refer to the graph:
$\hspace{0.5cm}$
The green area is the feasible region.
The red circle center $C$ and passing through the points $A$, $B$ and $O$ is the largest contour curve. Hence, the global maxima is at $A(0,2)$, $B(2,0)$ and $O(0,0)$.
The red point $C$ is the smallest contour curve. Hence, the global minima is at $C(1,1)$.
|
[
"sharepoint.stackexchange",
"0000236333.txt"
] | Q:
Tool to Delete users from SharePoint Online UserInfo hidden list
In SharePoint Online I notice deleting users from Office 365 does not delete them from groups in SharePoint Online https://support.microsoft.com/en-gb/help/3026385/how-to-remove-users-from-sharepoint-online
You have to delete them from every site collection from the hidden UserInfo List.
This is loads of admin when you have thousand of users and hundreds of site collection – Microsoft should delete them here as well?
Has anybody a full-proof script/tool that does this deletion fron UserInfo for accounts with no Office 365 account?
A:
You can use PowerShell script to check if the users are in Azure AD and remove the Orphaned users from site collection:
Checking the user in Azure AD
function Checkorphaneduser(){
Param( [Parameter(Mandatory=$true)] [string]$AzureUser )
$ADUser=Get-Msoluser -UserPrincipalName $AzureUser -Erroraction SilentlyContinue
if ($ADUser -ne $null)
{
return $true
}
Else
{
return $false
}
}
Get Orphaned Users from Site Collection
$Users = Get-SpoUser "$Sitename"
$OrphanedUsers = @()
foreach($User in $Users)
{
#Exclude Built-in User Accounts , Security Groups
if(($User.DisplayName.ToLower() -ne "nt authority\authenticated users") -and
($User.LoginName.ToLower() -ne "sharepoint\system") -and
($User.LoginName.ToLower() -ne "App@Sharepoint") -and
($User.LoginName.ToLower() -notlike "ylo001\_spocrwl*") -and
($user.IsGroup -eq $false ) #-and
)
{
$AccName = $User.LoginName #UserName
if ( ( Checkorphaneduser $AccName) -eq $false )
{
Write-Host "$($User.LoginName) from $($Sitename) doesn't Exists in Azure AD!"
$strOut += $User.LoginName+"`r`n"
$strOut|Out-File $Output
$OrphanedUsers+=$User.LoginName
}
}
}
Remove Orphaned Users from Site Collection
if($OrphanedUsers.Count -eq 0)
{
Write-host "There is no Orphaned user in $($Sitename)"
}
Else
{
$Remove=Read-Host "Do You want remove Orphaned Users Yes:No :"
If($Remove.ToUpper() -eq "YES")
{
foreach($OrpUser in $OrphanedUsers)
{
Remove-SPOUser -Site $Sitename -LoginName $OrpUser
Write-host "Removed the Orphaned user $($OrpUser) from $($Sitename) "
}
}
Else{
}
}
Get-pssession |Remove-PSSession
More detailed script check the blog: How to find and delete Orphaned Users from SharePoint Online
|
[
"stackoverflow",
"0020829421.txt"
] | Q:
visual basic: object reference not set to an instance of an object
i watched a video tutorial and saw the guy write and execute the code below and worked but when i try to compile mine it says "object reference not set to an instance of an object". i have tried several things to see if i can get what the problem is but to no avail.
Imports System.IO
Public Class Form2
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Try
Dim myline = New StreamReader("TextFile1.txt")
Dim line As String = ""
While Not IsNothing(line)
line = myline.ReadLine
If IsNothing(line) Then
TextBox2.AppendText(line)
End If
End While
myline.Close()
Catch ex As Exception
TextBox2.AppendText(ex.Message)
MsgBox(ex.Message)
End Try
End Sub
End Class
can anyone help please? thanks
A:
I think you are missing a Not:
If Not IsNothing(line) Then
TextBox2.AppendText(line)
End If
|
[
"stackoverflow",
"0050798248.txt"
] | Q:
Error when applying OpenCV SURF to HSV color space in python
I am implementening SURF to HSV image, but It is not working.
And when I am doing same to RGB image, It works fine.
from PIL import Image
import cv2
import numpy as np
import matplotlib
import matplotlib.pyplot as plt
#loaading image
rgb_img_arr= np.array(Image.open("myImage.jpg"))
hsv_image_arr=matplotlib.colors.rgb_to_hsv(rgb_img_arr)
surf = cv2.xfeatures2d.SURF_create()
#it works fine
keypoints, descriptors = surf.detectAndCompute(rgb_img_arr, None)
rgb_img = cv2.drawKeypoints(rgb_img_arr, keypoints, None)
plt.imshow(rgb_img )
#But it doent work
keypoints, descriptors = surf.detectAndCompute(hsv_image_arr, None)
hsv_img = cv2.drawKeypoints(hsv_image_arr, keypoints, None)
plt.imshow(hsv_img )
Error I am getting is -
C:\projects\opencv-python\opencv_contrib\modules\xfeatures2d\src\surf.cpp:892: error: (-215) !_img.empty() && ((imgtype) & ((1 << 3) - 1)) == 0 && (imgcn == 1 || imgcn == 3 || imgcn == 4) in function cv::xfeatures2d::SURF_Impl::detectAndCompute
Please tell me how can i fix this
?
A:
detectAndCompute expects a CV_8U image. (imgtype) & ((1 << 3) - 1)) == 0 is a bit cryptic, but if you follow the error to the source you can see that there: https://github.com/opencv/opencv_contrib/blob/2231018c839d728811a39556ec83741bf9a27614/modules/xfeatures2d/src/surf.cpp#L892
The HSV conversion matplotlib.colors.rgb_to_hsv is returning a float image instead.
Either you convert your float image back to an unsigned one. Or you can directly use the OpenCV color conversion, which will return an 8U image by default:
hsv_image_array = cv2.cvtColor(img, cv2.COLOR_RGB2HSV)
|
[
"stackoverflow",
"0004566271.txt"
] | Q:
Reading environment variables using VBScript or ActiveX on Citrix client
I'm having troubles while accessing environment variables in an html page.
I need to run a web application (php) on a Citrix server distribution.
What I tried to do is the following VBScript code on my html body:
Set oShell = CreateObject( "WScript.Shell" )
comp=oShell.ExpandEnvironmentStrings("%CLIENTNAME%")
It works as long as I login with my admin account (because of the IE running script permissions), but when I enter with the normal user account it doesn't work saying it can't create the object.
The sad thing is that it's not possible to change the normal user profile.
Does someone knows another way to get them?
It's possible to install new software on the machine, but it should be called from a htlm website.
So I'm thinking if could be possible to create some kind of ActiveX or java applet to read those environment variables, but as I'm new on ActiveX/Applets I dont know If I'll need some kind of special setup for those permissions.
Any help will be more than welcome! :)
A:
Probably the simplest way would be to have your app accept a string in the URL with the client name, then have Citrix pass this in when the app is launched (using the %clientname% variable).
|
[
"stackoverflow",
"0039795086.txt"
] | Q:
AWS Cant assign Elastic IP to Network Interface
I have a website that i am hosting on AWS. The ec2 instance is stored in a VPC. The instance is attached to an ELB and Network Interface. What i am trying to do is assign an Elastic IP to the Network interface so that my website has a static IP, while staying on the ELB. The issue is that when i try and assign the elastic IP to the Network Interface, i get the error
"An error occurred while attempting to associate the address
You do not have permission to access the specified resource."
I am the owner of the account.
Is what i am trying to do possible? I must have a static IP because the firewall we have goes by IP Address. Do i need to take it off of the load balancer?
A:
Check if the network interface already has an EIP association. When you try to associate an EIP to a network interface with an association already, the error "You do not have permission to access the specified resource." is thrown.
A:
You can't assign Elastic IP to LB Network Interfaces.
The right way is to use Route 53 point your CNAME or alias to your Load Balancer DNS.
That's it.
See this thread
https://www.reddit.com/r/aws/comments/5sm1ni/attaching_elastic_ip_to_load_balancer/
|
[
"stackoverflow",
"0062822307.txt"
] | Q:
Rendering nested list based on depth data
In React, how can I render the following data
const headings: [
{depth: 2, value: "Ayyy"}
{depth: 2, value: "Beee"}
{depth: 3, value: "Beee One"}
{depth: 3, value: "Beee Two"}
{depth: 3, value: "Beee Three"}
{depth: 2, value: "Ceee"}
];
into the following HTML?
<ol>
<li>Ayyy</li>
<li>
Beee
<ol>
<li>Beee One</li>
<li>Beee Two</li>
<li>Beee Three</li>
</ol>
</li>
<li>Ceee</li>
</ol>
My attempt:
const TableOfContents = ({ headings }) => (
<ol>
{headings.map(heading => {
// Depth 2
if (heading.depth === 2) {
return (
<li>
{heading.value}
</li>
)
}
// Depth 3
else if (heading.depth === 3) {
// Depth 3 ???
// If depth === 3 and previousDepth === 2, render <ol><li>{heading.value}</li>
// If depth === 3 and previousDepth === 3, render <li>{heading.value}</li>
// If depth === 3 and nextDepth === 2, render <li>{heading.value}</li></ol>
}
})}
</ol>
);
A:
You can first change your data structure like this:
const headings: [
{depth: 2, value: "Ayyy"},
{depth: 2, value: "Beee", children: [
{depth: 3, value: "Beee One"}
{depth: 3, value: "Beee Two"}
{depth: 3, value: "Beee Three"}
]},
{depth: 2, value: "Ceee"}
];
and you can write jsx render function like below:
const TableOfContents = ({ headings }) => (
<ol>
{headings.map(heading => {
return (
<li>
{heading.value}
if (heading.children) {
<ol>
heading.children.map(child => <li>{child.value}</li>
</ol>
}
</li>
)
})}
</ol>
);
Hope it helps.
|
[
"superuser",
"0000781350.txt"
] | Q:
Trouble installing Burrows-Wheeler Aligner (Linux)
Please bear with me, I'm just getting into using both virtual machines and linux.
I'm having trouble installing BWA (link) on my linux virtual machine. I've tried several methods, the most complete directions I've found are from from the medical department at Cornell, but I'm probably misunderstanding what they want me to do.
I downloaded the latest version 0.7.9a from sourceforge and moved it into a folder in my home directory. The path to the file is:
/home/jp/bwa/bwa-0.7.9a.tar.bz2
I then unzipped the file:
bunzip2 bwa-0.7.9a.tar.bz2
and then un-tared the file:
tar xvf bwa-0.7.9a.tar
Then I went into the new directory I created:
cd bwa-0.7.9a
I then used the "make command"
make
This is where I get hung up:
The terminal prints this error:
jp@jp-VirtualBox:~/bwa$ cd bwa-0.7.9a
jp@jp-VirtualBox:~/bwa/bwa-0.7.9a$ dir
bamlite.c bwase.c bwtsw2_aux.c kopen.c NEWS.md
bamlite.h bwase.h bwtsw2_chain.c kseq.h pemerge.c
bntseq.c bwaseqio.c bwtsw2_core.c ksort.h QSufSort.c
bntseq.h bwtaln.c bwtsw2.h kstring.c QSufSort.h
bwa.1 bwtaln.h bwtsw2_main.c kstring.h qualfa2fq.pl
bwa.c bwt.c bwtsw2_pair.c ksw.c README.md
bwa.h bwtgap.c ChangeLog ksw.h utils.c
bwa-helper.js bwtgap.h COPYING kthread.c utils.h
bwamem.c bwt_gen.c example.c kvec.h xa2multi.pl
bwamem_extra.c bwt.h fastmap.c main.c
bwamem.h bwtindex.c is.c Makefile
bwamem_pair.c bwt_lite.c kbtree.h malloc_wrap.c
bwape.c bwt_lite.h khash.h malloc_wrap.h
jp@jp-VirtualBox:~/bwa/bwa-0.7.9a$ make
gcc -c -g -Wall -Wno-unused-function -O2 -DHAVE_PTHREAD -DUSE_MALLOC_WRAPPERS utils.c -o utils.o
utils.c:33:18: fatal error: zlib.h: No such file or directory
#include <zlib.h>
^
compilation terminated.
make: *** [utils.o] Error 1
jp@jp-VirtualBox:~/bwa/bwa-0.7.9a$
I'm not sure how to handle this error. Could you guys provide any insight as to what needs to be done?
A second question I have pertaining to the next steps in the instructions provided by the Cornell website. It reads,
"Add bwa to your PATH by editing ~/.bashrc and adding
export PATH=$PATH:/path/to/bwa-0.5.9"
I've located .bashrc in my home directory (I can view it by using ls -a in command line, or using ctrl+h in the explorer). I'm not sure how to go about editing the file to include the appropriate line of code, i.e. do I just paste it anywhere in that file?
I've interpreted their directions to mean I should add something along the lines of
export PATH=$PATH:/home/jp/bwa/bwa-0.7.9a
But I'm not sure if that's correct.
I have installed a much earlier version (0.5) through the following command.
get-apt install bwa
but, I do not want to use an outdated version of this program.
Any help you guys would be able to give me would be greatly appreciated.
Thanks,
Host Machine OS: Windows 7 Home Premium (64 bit) (Service Pack 1)
Virtual Machine Software: Oracle VirtualBox Version 4.3.12
Guest Machine OS: Ubuntu 14.02 (32 bit (I couldn't get the 64 bit to work)
A:
It looks like you are missing the ZLIB header files.
Try:
sudo apt-get install zlib1g-dev
Or maybe:
sudo apt-get install zlib-dev
The first should be the right one, but I don't have a Ubuntu machine to test it on.
Hope this fixes your problem!
EDIT
Created a Ubuntu VM and verified that sudo apt-get install zlib1g-dev is the correct command.
|
[
"stackoverflow",
"0050168640.txt"
] | Q:
comparing strings using equality sign in C programming
#include<stdio.h>
int main()
{
char str1[] = "ComputerProgram";
char str2[] = "ComputerProgram";
(str1==str2)? (printf("Equal")):(printf("unequal"));
return 0;
}
The answer according to me should be equal but it comes out to be unequal.
However if I use strcmp(str1,str2) == 0 answer comes out to be equal. How is it working in == case.? Also, I tried to print the ASCII values of srt1 and str2, they came out to be different. So I think that might be the reason. Now the problem is how does == work for strings?
A:
Your arrays str1 and str2 will decay to pointers to their first elements when you compare them. That is, you compare two pointers that will never be equal.
In short, your comparison str1 == str2 is equal to &str1[0] == &str2[0].
What strcmp does differently is that is compares each character in the first string against each corresponding character in the other string, in a loop.
|
[
"stackoverflow",
"0018091605.txt"
] | Q:
How to avoid manually entering this formula in Excel
I'm trying to calculate a value called, "additional throughput". It is calculated by subtracting the base case module's throughput from a new module's throughput.
In the sheet below you can see that for the third row down (has a blue box in it), that the additional throughput is calculated by the formula "=T6-T4".
The problem is that when I click on this box and drag it down to apply the same formula to the other rows, I want the formula to become "=T7-T4" for the next row. Instead it becomes "=T7-T5". I tried to select multiple cells (where the formula was manually entered) before dragging down so it could recognize that the T4 doesn't change, only the first part. However, that didn't work.
A:
In Excel you can use $ signs before the column or row references to make those references "absolute" (rather than "relative"). For example if you use =A$1 then the 1 doesn't change when you copy down. If you use =$A1 then the A doesn't change when you copy across. If you use =$A$1 then neither changes whichever way you go.
So for your case you need to use
=T6-T$4
when you copy that down T$4 doesn't change
|
[
"stackoverflow",
"0031171593.txt"
] | Q:
decoding two different base64 strings returns two times the same string
base64 encoding / decoding uses deterministic algorithms. Because of that, a given input string will be always encoded to a known output string and vice versa.
Using the browser to access a URL secured with basic authentication, the browser encodes the username:password pair to a base64 string and places that string into the HTTP Authorization request header. Using Firebug it is easy to read that encoded string from the network monitor - let's call it string A.
On a raspberry (running Debian Wheezy) I installed the ddclient to update dns records for my domain using dyndns. The ddclient configuration is provided with the same username:password pair as used to access the URL with a browser. The client even tries to access the same URL (using basic authentication) but the access fails because of a bad authentication. Within the ddclient's debug output I can read the base64 encoded string - let's call it String B.
For any reason String A and String B are different! But they are created from the same username:password pair. If I decode the strings in the Debian shell
echo myBase64EncodedStringGoesHere | base64 --decode
or in the browser console using JavaScript
atob('myBase64EncodedStringGoesHere')
the result is always the same username:password pair, no matter if I decode String A or String B.
My only explanation is that there are maybe some non-visible control characters in the username:password configuration of the ddclient, influencing the base64 encoding result. Thus I checked the ddclient configuration using the vi editor with command
:set list
It looks all good. I am stumped. Does anybody has a glue what's going?
Update 1
because of @C4stor's comment I checked what happens when I take my username:password pair and encode it with the shell command
echo username:password | base64
As result I get String A with padding chars == at the end. Besides from the padding the debian OS created the same string as the web browser (used on Windows) does.
Update 2
As requested by @umläute, here are two demo strings:
Stirng A: bXlkb21haW4uY29tOmRueURucz
String B: bXlkb21haW4uY29tOmR5bkRucz
decoding them in the browser console using
atob('STRING')
gives always the same decoded string.
A:
Within the ddclient's config file there must have been some non-visible control characters, maybe due to a copy & paste...
Using vi I deleted the content from the file and wrote each line manually by hand. Now the ddclient produces the expected base64 encoded string.
I still wonder why I wasn't able to see the characters with vi's :set list command, but at least now the problem is solved.
|
[
"stackoverflow",
"0027058707.txt"
] | Q:
My html page not showing my json data
I am new to json and I am using microsoft visual studio to develop a simple web page. I have created the json file and put it into a drive say D://. Now I have to read the json data and show in my webpage when I click the button. whats going wrong.
<title>Welcome</title>
<script src="Scripts/jquery-1.10.2.min.js"></script>
<script src="Scripts/jquery-1.10.2.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$("#hop").click(function(event) {
$.getJSON('d://final.json', function (jd) {
$("#hi").html('<p>Name :' + jd.name + '</p>')
$('#hi').append('<p>Age : ' + jd.age + '</p>');
});
});
});
</script>
</head>
<body>
<h1>Get Json Data</h1>
<div id="hi">
Hi
</div>
<input type="button" id="hop" value="ShowJsonData"/>
</body>
final.json:
{
"name": "stack"
"age":"15"
}
A:
You cannot make AJAX requests to the local file system due to the security restrictions of modern browsers.
You need to run your code through a web server, such as IIS or Apache, either on the local machine or remotely.
|
[
"stackoverflow",
"0060345972.txt"
] | Q:
Is mark_immutable_if_constexpr needed for more constexpr containers?
The first code example in accepted C++20 proposal "More constexpr containers" (P0784) uses a function std::mark_immutable_if_constexpr. Was that function accepted as part of the same proposal? I see here that GCC 10 supports P0784 within a set of proposals labelled "Relaxations of constexpr restrictions", yet std::mark_immutable_if_constexpr is not included with GCC 10. Is std::mark_immutable_if_constexpr required to use P0784?
A:
Was that function accepted as part of the same proposal?
The function mark_immutable_if_constexpr is not in the proposal, and is not in C++20. It was removed from an earlier draft:
Remove non-transient allocation handling because EWG did not like mark_immutable_if_constexpr and the problem of the R4 status quo is potentially difficult to evolve.
You can also see that the wording for the paper does not introduce this new function.
|
[
"stackoverflow",
"0055071308.txt"
] | Q:
How to return a response from axios in Vue
I read all answered questions on stack overflow but still unable to figure out how to make this work.
File1.js
I send some data to server using axios ajax call as follows:
function ajaxSearchAxios(searchType,searchText){
var searchResults=[];
axios({
method: 'post',
url: 'ajaxSearch/',
data: {
searchType: searchType,
searchText: searchText,
},
responseType: 'json',
})
.then ( function (response){
searchResults = response.data['searchResults']; console.log('JS searchResults=',searchResults[0].value) //this prints nicely to the console
return searchResults
})
.catch ( function (error){
console.log('ajaxSearch error');
});
}
File2.js
Here I have my Vue code where I want to take output of ajaxSearchAxios() and store in Vue data.
new Vue({
el:'#id_1',
data:{
SearchResults:[],
},
methods:{
ajaxSearch:function(searchType){
this.SearchResults= ajaxSearchAxios('s','s1');
console.log('VUE =',this.SearchResults[0].value)
},
},
});
Thanks
A:
Remember, you're dealing with asynchronous functions, so your function needs to return and handle the functionality as a Promise
function ajaxSearchAxios(searchType,searchText){
return axios({ // <--- return the PROMISE
method: 'post',
url: 'ajaxSearch/',
data: {
searchType: searchType,
searchText: searchText,
},
responseType: 'json',
})
.then ( function (response){
return response.data['searchResults'];
})
.catch ( function (error){
console.log('ajaxSearch error');
});
}
and then handle it as a promise, instead of assigning the function to value
new Vue({
el:'#id_1',
data:{
SearchResults:[],
},
methods:{
ajaxSearch:(searchType) => {
// execute axios promise and on success, assign result to var
ajaxSearchAxios('s','s1').then(result => this.SearchResults = result)
},
},
});
|
[
"stackoverflow",
"0046055469.txt"
] | Q:
Playsms folders empty on Ubuntu
I'm using playsms 1.4 with smstools v3.1.20 on Ubuntu 16.04 with apache2, php7. I can send messages from playsms, but "my sent messages" folder is always empty, even though messages are successfully sent.
I've set the directory permission like this:
chown www-data:www-data -R /var/spool/sms
and it looks like this: ls -ltrR /var/spool/sms
/var/spool/sms:
total 28
drwxrwxrwx 2 www-data www-data 4096 Sep 2 12:44 checked
drwxrwxrwx 5 www-data www-data 4096 Sep 2 13:35 backup
drwxrwxrwx 2 www-data www-data 4096 Sep 3 20:46 failed
drwxrwxrwx 2 www-data www-data 4096 Sep 4 13:49 incoming
drwxrwxrwx 2 www-data www-data 4096 Sep 5 15:37 outgoing
drwxrwxrwx 2 www-data www-data 4096 Sep 5 15:37 sent
drwxrwxrwx 2 www-data www-data 4096 Sep 5 15:37 modem1
/var/spool/sms/checked:
total 0
/var/spool/sms/backup:
total 12
drwxrwxrwx 2 www-data www-data 4096 Sep 2 20:13 failed
drwxrwxrwx 2 www-data www-data 4096 Sep 4 13:49 incoming
drwxrwxrwx 2 www-data www-data 4096 Sep 5 15:16 sent
/var/spool/sms/backup/failed:
total 4
-rwxrwxrwx 1 www-data www-data 205 Sep 2 20:13 out.20170902180659.0.1.5
/var/spool/sms/backup/incoming:
total 24
-rwxrwxrwx 1 www-data www-data 180 Sep 2 21:21 modem1.8zQs3w
-rwxrwxrwx 1 www-data www-data 251 Sep 2 21:21 modem1.cASf2P
-rwxrwxrwx 1 www-data www-data 252 Sep 4 13:49 modem1.cY8NyU
/var/spool/sms/backup/sent:
total 80
-rwxrwxrwx 1 www-data www-data 193 Sep 4 13:47 out.20170904114728.0.1.1
-rwxrwxrwx 1 www-data www-data 253 Sep 4 16:32 out.20170904143202.0.1.2
-rwxrwxrwx 1 www-data www-data 253 Sep 5 15:16 out.20170905131603.0.1.3
-rwxrwxrwx 1 www-data www-data 253 Sep 5 15:16 out.20170905131603.0.1.4
/var/spool/sms/failed:
total 44
-rwxrwxrwx 1 www-data www-data 188 Sep 2 20:38 send_Kr8jMv
-rwxrwxrwx 1 www-data www-data 98 Sep 2 20:45 send_mGCCDT
-rwxrwxrwx 1 www-data www-data 97 Sep 2 20:45 send_6I691g
/var/spool/sms/incoming:
total 0
/var/spool/sms/outgoing:
total 0
/var/spool/sms/sent:
total 40
-rwxrwxrwx 1 www-data www-data 135 Sep 2 12:49 send_QKToY1
-rwxrwxrwx 1 www-data www-data 136 Sep 2 13:02 send_TGGpX5
-rwxrwxrwx 1 www-data www-data 142 Sep 2 20:37 send_mI6lvu
-rwxrwxrwx 1 www-data www-data 136 Sep 2 20:47 send_kARqqi
-rw-r--r-- 1 root root 136 Sep 5 15:37 send_9Ka0VL
playsms logs doesn't show anything abnormal, no errors. Notice how the last sent message is under root user, I believe this happens because it was sent after I manually set permission to www-data and smstools is run at system startup as root.
Do you have any suggestions on what I could try to get this working correctly? it's pretty annoying not seeing the messages you've sent and their status. It's just not practical to check the logs.
A:
I got it working by re-installing Ubuntu 16.04 server (this might or might not have been necessary, but I wanted to start fresh). Next I followed the instructions given here to install apache2, php7 and all the required modules, but i skipped installing Nginx because I don't need it.
I also skipped steps 5 and 6 because I don't use Nginx. After finishing those steps I installed smstools 3.1.21 following the instructions given here.
This got everything working like it should, folder are now populated with messages as expected.
|
[
"stackoverflow",
"0008437990.txt"
] | Q:
C prog: Write to and from binary files not working?
I've got a question concerning C programming.It is concerning binary files.In my code I(at least imagined that I) made it read and write from a binary file,but it won't do that for some reason.I've tried changing some things but I just don't see the error anywhere.And it is just this minimal detail which is giving me a hard time,it is all that is left to make in this code before it is done and then I'm done with the program altogether,so it gets on my nerves a bit more than it would usually.Please point out what it is I haven't done and what i should do to make it read from and write to binary files properly:
#define MAX 4
//========================-STRUCTURE-=====================================================================
struct person{
char name[30];
char mail[30];
char tele[30];
};
struct person p[MAX];
//========================-MAIN FUNCT-===============================================================
int main()
{
bool continue=true,exists=false;
int answer,i;
char filnme[20];
FILE *fil;
printf("Would you like to open an already existing file?[y/n]: ");
scanf("%d",&answer);
if(answer=='y'||answer=='Y')
{
finns=true;
}
else finns=false;
getchar();
printf("\n\nType the name of the file you will use: ");
scanf("%s",filnme);
if(exists)
{
fil = fopen(filnme,"rb");
for(i=0;i<MAX;i++)
{
while(feof(fil)==0)
{
fread(&p, MAX, 1, fil);
printf("%s %s %s\n",p.name,p.mail,p.tele);
}
}
fclose(fil);
}
else fil = fopen(filnme,"wb");
do
{
system("cls");
int choice;
printf("What would you like to do?");
printf("\n_______________\n");
printf("1. Add another person to the list\n");
printf("2. Print the entire list\n");
printf("3. Remove information from the list\n");
printf("4. Sort\n");
printf("5. Change information\n");
printf("6. Search\n");
printf("7. Exit\n");
printf("\nChoice: ");
scanf("%d",&choice);
printf("\n");
system("cls");
switch(choice)
{
case 1:
addtolist();
getch();
break;
case 2:
write();
getch();
break;
case 3:
remove();
getch();
break;
case 4:
sort();
getch();
break;
case 5:
change();
getch();
break;
case 6:
search();
getch();
break;
case 7:
continue=false;
break;
default:
printf("Not a valid choice!");
getch();
break;
}
}while(continue);
for(i=1;i<=MAX;i++)
{
fwrite(&p, MAX, 1, fil);
}
fclose(fil);
system("cls");
}
Nevermind the declaration of functions or such,I've got that covered,just the binary file handling I put into the main.
Thanks in advance!
A:
You are not using fread and fwrite correctly.
fread(&p, MAX, 1, fil);
should be:
fread(&p[i], sizeof(person), 1, fil);
Similarly for the fwrite call.
An alternative to calling fread and fwrite in a loop is to read/write the entire array in one go, like so:
fread(&p, sizeof(person), MAX, fil);
|
[
"stackoverflow",
"0026853084.txt"
] | Q:
How do I change the value of a text box from another class file?
I have a windows form up. In my Form1 class, I can set txtBox.Text="text" and it would change and update it.
I have another class, let's call it foo.
How would I in the foo class be able to change txtBox.Text from the foo class?
For example:
Class Form1: Form
{
txtBox.Text="0230104";
}
//In a different class file
Class foo
{
txtBox.Text="0";
}
How would I be able to change the text box with text from another class other than Form1?
A:
Add a property to Form1:
public string TxtBoxText {
get { return txtBox.Text; }
set { txtBox.Text = value;}
}
|
[
"stackoverflow",
"0005642233.txt"
] | Q:
Load javascript before rendering page?
I want to run some jquery code before my page have loaded. Im adding some classes which are changing the css with javascript, and when the page loads i see the "old" css for a short time. Any ideas? Thanks
A:
I want to run some jquery code before my page have loaded.
This is easily done; it's funny because much of the time, people are trying to do it the other way around.
When the browser encounters a script tag, barring your using a couple of special attributes (and the browser supporting them), all processing of the page comes to a screeching halt and the browser hands the script to the JavaScript engine. Only when the script completes does processing of the page continue.
So if you have a script tag in the head section of your page, you can output CSS classes via the document.write function:
<DOCTYPE html>
<html>
<head><title>Foo</title>
<script src='jquery.js'></script>
<script>
if (some_condition) {
document.write("<style>foo { color: blue; }</style>");
}
else {
document.write("<style>foo { color: red; }</style>");
}
</script>
Note that some_condition in the above can only rely on, and refer to, the items above it in the document (since the browser hasn't done anything with the rest of the document yet, as it's waiting to see what document.write content the script is going to output).
Live example (refresh it a few times, half the time it's red, half the time it's blue). It doesn't use jQuery, but you get the idea.
A:
Basically it's a similar problem as to implementing a loader/spinner. You show the animated gif to the user, and when the page finalizes loading, then you remove it.
In this case, instead of showing a gif, we show blank.
There are various ways of accomplishing this result. Here are few ordered in terms of ease and performance.
Global CSS rule.
Hide the body on your global CSS file.
body { display:none; }
And once the document finishes loading, toggle the display:
// Use 'load' instead of 'ready' cause the former will execute after DOM, CSS, JS, Images are done loading
$(window).load(function(){
$(body).show();
});
Demo
Cover page with div layer
Hide the content with a div sitting on top of the page and remove it later.
div#page_loader {
position: absolute;
top: 0;
bottom: 0;
left: 0;
right: 0;
background-color: white;
z-index: 100;
}
Demo
JavaScript snippet
Hide the body before the page renders:
<body onload="document.body.style.display='none';">
Demo
If you use Modernizr, you could also leverage its CSS classes to hide/show the content depending on the user's device or browser.
What I wouldn't recommend though, it's running jQuery scripts at the top of the page, cause that's going to add extra burden, and delay even further page rendering.
A:
Assuming you're already using the onLoad event on body or using the jQuery ready callback, you could start with style="display:none;" on your root div, do your JS stuff and finally set "display:block" on that div when you're ready to expose the content. Voila?
|
Subsets and Splits