Exemplo n.º 1
0
// ====================================================================================
// ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
// IMPORT 
// logFile, path_Dateiname, qsltype, rig, home_id
// ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
void wadif::doImport(QString log,QString fpath, int qslmode, QString rig, int hId)
{
 QString val, token, prog;
 QString Call, qsoDate;
 QString t, z;
 int idx, n, oid, id, sekcnt, vl, len;
 bool ok;
 char buf[255];
    sekcnt = 10;                                      // Sekundenzähler 10..59
    oid = 0;
    QSqlQuery query;
    QFile datei( fpath );
    if(! datei.open(QIODevice::ReadOnly)) {
        state = 1;
        return;                                       // FEHLER
    }
    count = 0;
    QTextStream istream( &datei);
    
    // Header lesen ----------------------------------
    while( istream.atEnd() != true ) {                // HEADER '<eoh>' suchen
        len = 0;
        while(len == 0) {                             // leere zeilen ueberspringen
           t = istream.readLine(0);
           len = t.count();
           if(len != 0) break;                        // zeile mit text gefunden
        }
        idx = 0;                                      // text auswerten
        while(len != idx)
          if(t[idx++] == QChar('<')) break;           // suche '<'
        z = "";
        if(len != idx) {                              // '<' gefunden, text ist gueltig
           while(t[idx] != QChar(':') && t[idx] != QChar('>')) z += t[idx++]; 
           if(t[idx] == QChar('>')) {                 // '>' gefunden, dann ist token ohne text
              z = z.toUpper();                        // token immer groß
              if(z.compare("EOH") == 0) break;        // header_ende ?
           }
           else {                                     
              val = "";                               // ':' gefunden, es gibt text
              idx++;
              if(z.compare("PROGRAMID") == 0)         // wenn ProgrammID
                while(t[idx] != QChar('>')) val += t[idx++]; 
              vl = val.toInt(&ok,10);
              idx++;                                  
              val = "";
              n = vl;                                 // text:_laenge
              while(n-- != 0) val += t[idx++];        // text lesen
              prog = val;
           }
        }
    }
    // Header gelesen 
    
    // ------------ jetzt DATA ---------------------
    Error = "";
    count = 0;                                            // Datensatz Zähler
    while(istream.atEnd() == FALSE) {                     // ADIF_text bis Datei_ende bearbeiten
        i = 0;
        while(i != qsoFields) strcpy(adh[i++].value,"");  // value(datenfelder) QSO_tabelle loeschen
        i = 0;
        while(i != qslFields) strcpy(adhq[i++].value,""); // value(datenfelder) QSL_tabelle loeschen
        i = 0;
        while(i != awdFields) strcpy(adhw[i++].value,""); // value(datenfelder) AWD_tabelle loeschen

        z = istream.readLine(0); // daten_zeile lesen und bearbeiten. Zeile ist: stream ohne '\n' or '\l\r',
                                 // daten_token oder Zeilenanteile, daten_zeile_ende ist <eor> im stream.
        if(z.compare("<EOF>") == 0) break;                // File_ende ?

        while(z.count() == 0) {                 // check: es koennte eine leer_zeile vor <eor> sein
           if(istream.atEnd() == TRUE) break;   // oder eine leer_zeile mitten in der text_zeile (Ucx)
           z = istream.readLine(0);             // suche text
        }
        
        if(istream.atEnd() == TRUE) break;      // ok. ist File_ende
                                              
        len = z.count();                        
        vl = 0;
        Lcn  = "";
        Cqz  = "";
        Ituz = "";
        Dxcc = "";
        t = "";
        n = 0;
        idx = 0;                                     // zeilen_index 
        while( 1 ) {                                 // 1. zeile aus datastream
            while(len != idx) {
               if(z[idx++] == QChar('<')) break;     // gefunden
            }
            if(len == idx) {                         // das war eine leere_restzeile oder
                z = istream.readLine(0);   // zeile war token oder zeilen_anteil; neue zeile (token) lesen
                len = z.count();
                if(len == 0)                         // war leer_zeile
                   z = istream.readLine(0);          // n. zeile lesen
                len = z.count();
                idx = 0;
                while(z[idx] != QChar('<')) idx++;   // suche token_anfang
                idx++; 
            } 
            
            t = "";
            while(z[idx] != QChar(':') && z[idx] != QChar('>')) t += z[idx++]; // ADIF_token_text
            if(z[idx] == QChar('>')) {               // steht am Textende '>' ist token ohne Text
                t = t.toUpper();                     // wenn ja; immer groß
                if((t.compare("EOR") == 0) || (t.compare("EOF") == 0)) // check auf zeilen od. Datei_ENDE
                  break;
            }
            if(t.compare("EOF") == 0) break;         // * schluss *
            token = t;                               // ADIF_token sichern
            t = "";
            idx++;
            while(z[idx] != QChar('>') && z[idx] != QChar(':')) t += z[idx++]; // text_laenge holen
            vl = t.toInt(&ok,10);                    // laenge Datenstring sichern
    
            if(z[idx] == QChar(':')) {               // ist Datum_type <QSL_DATE:8:d>
              idx++;                                 // z.Z ':' überspringen
              idx++;                                 // z.Z 'd' überspringen
            }
            idx++;                                   // '>' überspringen
            t = "";
            n = vl;                                  // nutz_datenstring_laenge
            while(n-- != 0) t += z[idx++];           // nutz_daten lesen
            val = t;
                                                     // token + data bearbeitem
            token = token.toUpper();                 // ADIF_wort immer in groß_Buchstaben
            strcpy(buf,token.toAscii());             // ADIF_name nach ascii
            strcpy(buf,getdbName(buf));              // adif_name nach db_Spalten_name übersetzen
	    
             // <token:n>val im *QSO_Datensatz* gefunden - jetzt namen checken, variable ist in val
            if(strlen(buf) != 0) {          // falls db_spalten_name gefunden, value bearbeiten sonst überspringen      
                if(strcmp(buf,"rufz") == 0) {        // ist es das rufzeichen ?
                  n = val.indexOf("/");              // check Cept_prefix im val
                  if(n != -1) {                      // flush gefunden
                    if( n <= 4 ) {                   // ja ist cept ( es gibt auch prefixe grösser 4 !! )
                      s = val.left(n);               // ja: cept_pref sichern
                      s += "/";                      // flush anhängen
                      val.remove(0,n +1);            // cept_pref vom Rufzeiche entfernen
                      setValue((char *)"cept",s);    // CEPT_prefix setzen
                    }
                  }
                  setValue((char *)"rufz",val);   // Rufzeichen setzen ( ohne cept )
                  Call = val;                     // Rufz merken
                }
                else
                 if(strcmp(buf,"dxcc") == 0) {    // convertiere ADIF_Nr->la_pref
                   n = val.toInt(&ok,10);         // wenn dxcc numerisch
                   if(ok == true )                // wenn Zahl, convertiere nach pref
                     qy = "SELECT lcn,cqz,ituz,ldxcc FROM tla WHERE adif="+s.setNum(n);
                   else
                     qy = "SELECT lcn,cqz,ituz,ldxcc FROM tla WHERE ldxcc='"+val+"'";
                   query.exec(qy);
                   if(query.size() != 0 ) {             // prefix oder adif_nr gefunden
                      query.next();
                      Lcn  = query.value(0).toString(); // hole: cn aus Landestabelle
                      Cqz  = query.value(1).toString(); //       cqz
                      Ituz = query.value(2).toString(); //       ituz
                      Dxcc = query.value(3).toString(); //       dxcc_prefix
                      setValue(buf,Dxcc);               // setze:DXCC_pref -alpha_type
                   }
                   else {                               // nicht gefunden
                     Error += " Call "+getValue((char *)"rufz");
                     Error += " dxcc_prefix < "+val;
                     Error += " > nicht gefunden\n";    // tr() ???
                     state = 1;                         // es ist ein Fehler aufgetreten
                   }
                 }
                else
                 if(strcmp(buf,"band") == 0) {         // check Band
                   val = val.toUpper();
                   val = getSysBand(val);              // übersetze Band_variable
                   setValue(buf,val);                  // setze band
                 }
                else
                 if(strcmp(buf,"day") == 0) {          // check Qso_Tag
                    setValue(buf,val);                 // Tag setzen
                    qsoDate = val;                     // Datun merken
                 }
                else 
                  if(strcmp(buf,"btime") == 0) {       // check Qso_Start_zeit
                    if(vl != 6) {                      // falls Zeit 6.stellig
                      sekcnt++;                        // Sekunden +1
                      if(sekcnt == 60)                 // sek. min 10 <-> 60 max
                        sekcnt = 10;
                      val.append(s.setNum(sekcnt));    // Zeit auf 8.stellig erweitern
                    }
                    setValue(buf,val);                 // setze Zeit
                  }
                else
                  if(strcmp(buf,"etime") == 0) {       // Qso_Ende_zeit
                     if(vl != 6) {
                       sekcnt++;                       // Sekunden +1
                       if(sekcnt == 60)
                         sekcnt = 10;
                       val.append(s.setNum(sekcnt));   // Zeit 8.stellig
                     }
                     setValue(buf,val);                // setze Zeit
                  }
                else 
                  
                  if(strcmp(buf,"qslr") == 0) {  // ---------// QSL_r - Büro --------------------
		     if(val.compare("N") == 0)
		       val = "R";
		     else {
			if(val.compare("Y") == 0)            // QSL eralten ?
			  addQslFlag((char *)"qslRvia","B"); // QSLr_via 'B'
		     }
                     setValue(buf,val);                      // R, Y, I
	          }
                else
                  if(strcmp(buf,"qsls") == 0) {              // qsl_s
		     if( !qslmode )                          // qslMode = 0 ( daten aus contest )
		       val = "";
		     else {                                  // qslMode = 1 ( daten aus anderem LOG ) - wie Import
		       if(val.compare("N") == 0) {
		         val = "R";
			 setValue((char *)"prflg","B");      // QSL_Karte drucken - ja;
		       }
		       else
			 if(val.compare("Y") == 0)           // QSL gesendet - ja;
		          addQslFlag((char *)"qslSvia","B"); // QSLs_via 'B'
                     }
                     setValue(buf,val);                      // val = "", R, Y, I
                  }
                else {
                 setValue(buf,val);                          // gefunden, default - value in arry eintragen
                } 
             }
             else {  // -----------------------------------  // QSL * LOTW
	      strcpy(buf,token.toAscii());
              strcpy(buf,getdbNameQsl(buf));                 // adif_feldname übersetzen
              if(strlen(buf) != 0) {                          // falls Spalten_name gefunden, bearbeiten
                 if(strcmp(buf,"eqsls") == 0) {              // eQSL * eqsl_s    
		   if(val.compare("N") == 0)                 // (UcxL) N = noch nicht gesendet
                      val = "R";                             // setze R_equested
                    else {
                      if(val.compare("Y") == 0) {
                        addQslFlag((char *)"qslSvia","E");   // QSLs_via 'E'
                        setValueQsl(buf,val);                // val eintragen R, Y
		      }
		    }
		 }
	         else                                        // eQSL_r
                  if(strcmp(buf,"eqslr") == 0) {
                    if(val.compare("N") == 0)                // (UcxL) N = noch nicht erhalten
                      val = "R";                             // setze Requested
                    else {
                      if(val.compare("Y") == 0) {            // QSL erhalten ?
                        addQslFlag((char *)"qslRvia","E");   // QSLr_via 'E'
                        setValueQsl(buf,val);                // val eintragen R, Y
		      }
		    }
	        }
	        
	        else       // -------------------------------// LOTW * lotqsl_r
		if(strcmp(buf,"lotqslr") == 0) {             // ---------------
                   if(val.compare("N") == 0)                 // (UcxL) n = nicht erhalten
                      val = "R";                             // setze R_equested
                   else {
                     if(val.compare("Y") == 0) {             // QSL erhalten ?
                       addQslFlag((char *)"qslRvia","L");    // QSLr_via 'L'
                       setValueQsl(buf,val);                 // val eintragen R, Y
		     }
		   }
	        }
		else                                         // lotqsl_s
		if(strcmp(buf,"lotqsls") == 0) {
                   if(val.compare("N") == 0)                 // (UcxL) N = noch nicht erhalten
                      val = "R";                             // setze R_equested
                   else {
                     if(val.compare("Y") == 0) {             // QSL gesendet ?
                       addQslFlag((char *)"qslSvia","L");    // QSLs_via 'L'
                       setValueQsl(buf,val);                 // val eintragen R, Y
		     }
		   }
	        }
	        else
	         setValueQsl(buf,val);                        // default
	      }
              else {   // ----------------------------- AWD_daten_satz
                strcpy(buf,token.toAscii());
                strcpy(buf,getdbNameAwd(buf));         // adif_feldname nach dbname übersetzen
                if(strlen(buf) != 0) {                 // AWD_Type gefunden
                  setValueAwd(buf,val);                // value eintragen
                }
                else {                                 // Fehler_text setzen
                  Error += " Call "+getValue((char *)"rufz");
                  Error += " "+token;
                  Error += " text < "+val;
                  Error += " > nicht gefunden\n";      // tr() ??
                  state = 1;                           // es ist ein Fehler aufgetreten
                }
              } 
            }   // ein tocken bearbeitet
         }      // WHILE( 1 ) <eor> nicht erreicht
         
//--     ENDE_Adif_data_zeile -- <EOR> gefunden
         
          // fehlende Values nachtragen 
         if(getValue((char *)"dxcc").count() == 0) {   // falls dxcc_feld leer
           s = getValue((char *)"rufz");               // hole Rufzeichen
           n = 1;
           z = s.left(n);
           while(getla( z ) == 0) {
              if(n >= 4) {                             // unbekannt
                Error += "dxcc fuer Rufzeichen "+s+" nicht gefunden\n";
                state = 1;                             // es ist ein Fehler aufgetreten
               break;
              }
              z = s.left(++n);
           }
           setValue((char *)"cn",Lcn);
           setValue((char *)"cqz",Cqz);
           setValue((char *)"ituz",Ituz);
           setValue((char *)"dxcc",Dxcc);
         }
         
         if(getValue((char *)"cn").count() == 0) {     // falls Cont fehlt
            setValue((char *)"cn",Lcn);                // setze continent
         }
         
         if(getValue((char *)"cqz").count() == 0) {   // falls CQ_zone fehlt
            setValue((char *)"cqz",Cqz);              // setze..CQzone
         }
         
         if(getValue((char *)"ituz").count() == 0) {  // falls ITU_zone fehlt 
            setValue((char *)"ituz",Ituz);            // setze ..zone
         }
         
         if(getValue((char *)"etime").count() == 0) {             // falls Ende_zeit fehlt
            setValue((char *)"etime", getValue((char *)"btime")); // setze = bzeit
         }
         
         s = s.setNum(hId);                          // portabel_id
         strcpy(buf,s.toAscii());
         setValue((char *)"rig",rig);                // ( ist für DRUCK erforderlich )
         setValue((char *)"qline",(char *)"KW");     // kein ADIF_token - könnte leer bleiben
         setValue((char *)"quarter",buf);            // ist ADIF_import_portabel_type
         setValue((char *)"op",(char *)"0");         // Operator intern_value z.Z.= 0
// ------ DEBUG
/*
         n = 0;    // TEST Data ausgeben
         i = 0;
         while(i != qsoFields) {
            qDebug() << adh[i].pos <<  adh[i].field << adh[i].adifnam << adh[i].value;
            i++;
         }
         n = 0;
         i = 0;
         while(i != qslFields) {
           qDebug() << adhq[i].pos <<  adhq[i].field << adhq[i].adifnam << adhq[i].value;
           i++;
         }
         n = 0;
         i = 0;
         while(i != awdFields) {
           qDebug() << adhw[i].pos <<  adhw[i].field << adhw[i].adifnam << adhw[i].value;
           i++;
         }
         //datei.close(); 
         //return;        
*/
// ----- DEBUG
         QSqlQuery query;
	 
// --    OM --------------------------------------------  alle LOG_Datensatze erzeugen
         qy = "SELECT omid FROM "+log+"om WHERE rufz='";
         qy += Call;
         qy += "'";
         query.exec(qy);
         n = query.size();
         if(n == 0 ) {                                    // ist der OM neu ?
            qy = "INSERT INTO "+log+"om VALUES (0,'";     // ja;
            qy += Call;
            qy += "','";
            qy += adh[2].value;
            qy += "')";
            QSqlQuery query;
            query.exec(qy);
            oid = query.lastInsertId().toInt();           // Datensatz merken
         }
         else {
          query.next();
          oid = query.value(0).toInt();
         } 

         // --    QSO ------------------------------------------
         n = 3;                         // starte auf index_pos_3
         qy = "INSERT INTO "+log+" VALUES (0,"+s.setNum(oid)+",'";
         qy += adh[0].value;            // cept
         while(n != qsoFields -3 ) {    // alle felder übernehmen
           qy += "','";
           qy += adh[n++].value;
         }
         qy += "',";
         qy += adh[n++].value;          // quarter
         qy += ",";
         qy += adh[n++].value;          // Operator
         qy += ")";
         query.exec(qy);                // Datensatz eintragen
         id = query.lastInsertId().toInt();
	 
// --    QSL -------------------------------------------
         n = 0;                         // starte auf index_pos_0  
         qy = "INSERT INTO "+log+"qsl VALUES (0,"+s.setNum(id)+",'";
         qy += Call;
         qy += "','"+qsoDate;
         while(n != qslFields) {         // alle felder übernehmen
           qy += "','";
           qy += adhq[n++].value;
         }
         qy += "')";
         query.exec(qy);                 // Datensatz eintragen
         // qDebug() << query.lastError();
	 
// --    AWD -------------------------------------------
         n = 0;
         while(n != awdFields) {             // alle felder prüfen und übernehmen
          if(strlen(adhw[n].value) != 0) {   // value eingetragen ?
             qy = "INSERT INTO "+log+"awd VALUES (0,"+s.setNum(id)+",'";
             qy += Call;
             qy += "','";
             qy += adhw[n].field;
             qy += "','";
             qy += adhw[n].value;
             qy += "')";
             query.exec(qy);               // Datensatz eintragen
           }
           n++;                            // nächsten awd_type
         }
         count++;                          // 1 Datensatz kompl. bearbeitet - QSO_zähler +1
/*
         if(count == 1) {                   // TEST einen Datensatz bearbeiten
          datei.close();
          return;
         }
*/
     }
     datei.close();
     return;
}
Exemplo n.º 2
0
bool DataManager::saveDatabaseTimeRecord(Map map) {
    qDebug("DataManager::saveDatabaseTimeRecord");
    QString userName;

#if defined(UNICODE)
    if ( QSysInfo::WindowsVersion & QSysInfo::WV_NT_based)
    {
        TCHAR winUserName[UNLEN + 1]; // UNLEN is defined in LMCONS.H
        DWORD winUserNameSize = sizeof(winUserName);
        GetUserName( winUserName, &winUserNameSize );
        userName = QString::fromWCharArray( winUserName );
    } else
#endif
    {
        char winUserName[UNLEN + 1]; // UNLEN is defined in LMCONS.H
        DWORD winUserNameSize = sizeof(winUserName);
        GetUserNameA( winUserName, &winUserNameSize );
        userName = QString::fromLocal8Bit( winUserName );
    }

    qDebug("DataManager::saveDatabaseTimeRecord windows user: %s", userName.toStdString().c_str());
    QString userGuid;
    std::string userGuidSql = "select id from dbo.CoreUser where AccountName = 'VIS_BOG_HQ\\" + userName.toStdString() + "'";
    QSqlQuery sqlUserGuid(QString(userGuidSql.c_str()));
    if (sqlUserGuid.next()) {
        userGuid = sqlUserGuid.value(0).toString();
        qDebug("DataManager::saveDatabaseTimeRecord user guid: %s", userGuid.toStdString().c_str());
    } else {
        qDebug("User %s not found", userName.toStdString().c_str());
        return false;
    }

    int periodId = period(map.date.toQDateTime());
    qDebug("DataManager::saveDatabaseTimeRecord period id: %d", periodId);
    if (periodId == -1) {
        return false;
    }

    int displayOrder = 1;
    QSqlQuery displayOrderSql;
    if (displayOrderSql.prepare("select Max(displayOrder) from dbo.TimeEntry where PeriodId = :Period and CoreUserId = :CoreUserId")) {
        displayOrderSql.bindValue(":Period", periodId);
        displayOrderSql.bindValue(":CoreUserId", userGuid);
        if (displayOrderSql.exec() && displayOrderSql.next()) {
            displayOrder = displayOrderSql.value(0).toInt() + 1;
        } else {
            displayOrder = 1;
        }
    } else {
        qDebug("Error getting the displayOrder");
        return false;
    }
    qDebug("DataManager::saveDatabaseTimeRecord displayOrder: %d", displayOrder);
    std::stringstream ssSql;
    ssSql << "INSERT INTO TimeEntry (PeriodId,ProjectId,TaskId,CoreUserId,Date,Hours,Description,UpdatedOn,DisplayOrder,Version)";
    ssSql << " VALUES (:PeriodId,:ProjectId,:TaskId,:CoreUserId,:Date,:Hours,:Description,:UpdatedOn,:DisplayOrder,:Version)";
    QSqlQuery insert;
    insert.prepare(QString(ssSql.str().c_str()));
    insert.bindValue(":PeriodId", periodId);
    insert.bindValue(":ProjectId", map.coreProject.id);
    insert.bindValue(":TaskId", map.coreTask.id);
    insert.bindValue(":CoreUserId", userGuid);
    insert.bindValue(":Date", map.date.toQDateTime());
    double minutes = ((double)((int)(map.time.totalMinutes() * 100))/(double)100);

    insert.bindValue(":Hours", minutes);
    insert.bindValue(":Description", map.description);
    insert.bindValue(":UpdatedOn", QDateTime::currentDateTime());
    insert.bindValue(":DisplayOrder", displayOrder);
    insert.bindValue(":Version", 2);
    bool updated = insert.exec();
    if (!updated) {
        qDebug("An error has ocurred executing the insertion. Error: %s", insert.lastError().text().toStdString().c_str());
    }

    qDebug("out DataManager::saveDatabaseTimeRecord");
    return updated;
}
Exemplo n.º 3
0
bool MSqlDatabase::OpenDatabase(bool skipdb)
{
    if (!m_db.isValid())
    {
        LOG(VB_GENERAL, LOG_ERR,
              "MSqlDatabase::OpenDatabase(), db object is not valid!");
        return false;
    }

    bool connected = true;

    if (!m_db.isOpen())
    {
        if (!skipdb)
            m_dbparms = GetMythDB()->GetDatabaseParams();
        m_db.setDatabaseName(m_dbparms.dbName);
        m_db.setUserName(m_dbparms.dbUserName);
        m_db.setPassword(m_dbparms.dbPassword);
        m_db.setHostName(m_dbparms.dbHostName);

        if (m_dbparms.dbHostName.isEmpty())  // Bootstrapping without a database?
        {
            connected = true;              // Pretend to be connected
            return true;                   // to reduce errors
        }

        if (m_dbparms.dbPort)
            m_db.setPort(m_dbparms.dbPort);

        // Prefer using the faster localhost connection if using standard
        // ports, even if the user specified a DBHostName of 127.0.0.1.  This
        // will cause MySQL to use a Unix socket (on *nix) or shared memory (on
        // Windows) connection.
        if ((m_dbparms.dbPort == 0 || m_dbparms.dbPort == 3306) &&
            m_dbparms.dbHostName == "127.0.0.1")
            m_db.setHostName("localhost");

        connected = m_db.open();

        if (!connected && m_dbparms.wolEnabled)
        {
            int trycount = 0;

            while (!connected && trycount++ < m_dbparms.wolRetry)
            {
                LOG(VB_GENERAL, LOG_INFO,
                    QString("Using WOL to wakeup database server (Try %1 of "
                            "%2)")
                         .arg(trycount).arg(m_dbparms.wolRetry));

                if (myth_system(m_dbparms.wolCommand) != GENERIC_EXIT_OK)
                {
                    LOG(VB_GENERAL, LOG_ERR,
                            QString("Failed to run WOL command '%1'")
                            .arg(m_dbparms.wolCommand));
                }

                sleep(m_dbparms.wolReconnect);
                connected = m_db.open();
            }

            if (!connected)
            {
                LOG(VB_GENERAL, LOG_ERR,
                    "WOL failed, unable to connect to database!");
            }
        }
        if (connected)
        {
            LOG(VB_GENERAL, LOG_INFO,
                    QString("Connected to database '%1' at host: %2")
                            .arg(m_db.databaseName()).arg(m_db.hostName()));

            // WriteDelayed depends on SetHaveDBConnection() and SetHaveSchema()
            // both being called with true, so order is important here.
            GetMythDB()->SetHaveDBConnection(true);
            if (!GetMythDB()->HaveSchema())
            {
                // We can't just check the count of QSqlDatabase::tables()
                // because it returns all tables visible to the user in *all*
                // databases (not just the current DB).
                bool have_schema = false;
                QString sql = "SELECT COUNT( "
                              "         INFORMATION_SCHEMA.TABLES.TABLE_NAME "
                              "       ) "
                              "  FROM INFORMATION_SCHEMA.TABLES "
                              " WHERE INFORMATION_SCHEMA.TABLES.TABLE_SCHEMA "
                              "       = DATABASE() "
                              "   AND INFORMATION_SCHEMA.TABLES.TABLE_TYPE = "
                              "       'BASE TABLE';";
                // We can't use MSqlQuery to determine if we have a schema,
                // since it will open a new connection, which will try to check
                // if we have a schema
                QSqlQuery query = m_db.exec(sql); // don't convert to MSqlQuery
                if (query.next())
                    have_schema = query.value(0).toInt() > 1;
                GetMythDB()->SetHaveSchema(have_schema);
            }
            GetMythDB()->WriteDelayedSettings();
        }
    }

    if (!connected)
    {
        GetMythDB()->SetHaveDBConnection(false);
        LOG(VB_GENERAL, LOG_ERR, "Unable to connect to database!");
        LOG(VB_GENERAL, LOG_ERR, MythDB::DBErrorMessage(m_db.lastError()));
    }

    return connected;
}
Exemplo n.º 4
0
Database::Database() {
	QSqlDatabase db = QSqlDatabase::addDatabase(QLatin1String("QSQLITE"));
	QSettings qs;
	QStringList datapaths;
	int i;

	datapaths << g.qdBasePath.absolutePath();
#if QT_VERSION >= 0x050000
	datapaths << QStandardPaths::writableLocation(QStandardPaths::DataLocation);
#else
	datapaths << QDesktopServices::storageLocation(QDesktopServices::DataLocation);
#endif
#if defined(Q_OS_UNIX) && ! defined(Q_OS_MAC)
	datapaths << QDir::homePath() + QLatin1String("/.config/Mumble");
#endif
	datapaths << QDir::homePath();
	datapaths << QDir::currentPath();
	datapaths << qApp->applicationDirPath();
	datapaths << qs.value(QLatin1String("InstPath")).toString();
	bool found = false;

	for (i = 0; (i < datapaths.size()) && ! found; i++) {
		if (!datapaths[i].isEmpty()) {
			QFile f(datapaths[i] + QLatin1String("/mumble.sqlite"));
			if (f.exists()) {
				db.setDatabaseName(f.fileName());
				found = db.open();
			}

			//TODO: If the above succeeds, but we also have a .mumble.sqlite, we open another DB!?
			QFile f2(datapaths[i] + QLatin1String("/.mumble.sqlite"));
			if (f2.exists()) {
				db.setDatabaseName(f2.fileName());
				found = db.open();
			}
		}
	}

	if (! found) {
		for (i = 0; (i < datapaths.size()) && ! found; i++) {
			if (!datapaths[i].isEmpty()) {
				QDir::root().mkpath(datapaths[i]);
#ifdef Q_OS_WIN
				QFile f(datapaths[i] + QLatin1String("/mumble.sqlite"));
#else
				QFile f(datapaths[i] + QLatin1String("/.mumble.sqlite"));
#endif
				db.setDatabaseName(f.fileName());
				found = db.open();
			}
		}
	}

	if (! found) {
		QMessageBox::critical(NULL, QLatin1String("Mumble"), tr("Mumble failed to initialize a database in any\nof the possible locations."), QMessageBox::Ok | QMessageBox::Default, QMessageBox::NoButton);
		qFatal("Database: Failed initialization");
	}

	QFileInfo fi(db.databaseName());

	if (! fi.isWritable()) {
		QMessageBox::critical(NULL, QLatin1String("Mumble"), tr("The database '%1' is read-only. Mumble cannot store server settings (i.e. SSL certificates) until you fix this problem.").arg(Qt::escape(fi.filePath())), QMessageBox::Ok | QMessageBox::Default, QMessageBox::NoButton);
		qWarning("Database: Database is read-only");
	}

	{
		QFile f(db.databaseName());
		f.setPermissions(f.permissions() & ~(QFile::ReadGroup | QFile::WriteGroup | QFile::ExeGroup | QFile::ReadOther | QFile::WriteOther | QFile::ExeOther));
	}

	QSqlQuery query;

	execQueryAndLogFailure(query, QLatin1String("CREATE TABLE IF NOT EXISTS `servers` (`id` INTEGER PRIMARY KEY AUTOINCREMENT, `name` TEXT, `hostname` TEXT, `port` INTEGER DEFAULT " MUMTEXT(DEFAULT_MUMBLE_PORT) ", `username` TEXT, `password` TEXT)"));
	query.exec(QLatin1String("ALTER TABLE `servers` ADD COLUMN `url` TEXT")); // Upgrade path, failing this query is not noteworthy

	execQueryAndLogFailure(query, QLatin1String("CREATE TABLE IF NOT EXISTS `comments` (`who` TEXT, `comment` BLOB, `seen` DATE)"));
	execQueryAndLogFailure(query, QLatin1String("CREATE UNIQUE INDEX IF NOT EXISTS `comments_comment` ON `comments`(`who`, `comment`)"));
	execQueryAndLogFailure(query, QLatin1String("CREATE INDEX IF NOT EXISTS `comments_seen` ON `comments`(`seen`)"));

	execQueryAndLogFailure(query, QLatin1String("CREATE TABLE IF NOT EXISTS `blobs` (`hash` TEXT, `data` BLOB, `seen` DATE)"));
	execQueryAndLogFailure(query, QLatin1String("CREATE UNIQUE INDEX IF NOT EXISTS `blobs_hash` ON `blobs`(`hash`)"));
	execQueryAndLogFailure(query, QLatin1String("CREATE INDEX IF NOT EXISTS `blobs_seen` ON `blobs`(`seen`)"));

	execQueryAndLogFailure(query, QLatin1String("CREATE TABLE IF NOT EXISTS `tokens` (`id` INTEGER PRIMARY KEY AUTOINCREMENT, `digest` BLOB, `token` TEXT)"));
	execQueryAndLogFailure(query, QLatin1String("CREATE INDEX IF NOT EXISTS `tokens_host_port` ON `tokens`(`digest`)"));

	execQueryAndLogFailure(query, QLatin1String("CREATE TABLE IF NOT EXISTS `shortcut` (`id` INTEGER PRIMARY KEY AUTOINCREMENT, `digest` BLOB, `shortcut` BLOB, `target` BLOB, `suppress` INTEGER)"));
	execQueryAndLogFailure(query, QLatin1String("CREATE INDEX IF NOT EXISTS `shortcut_host_port` ON `shortcut`(`digest`)"));

	execQueryAndLogFailure(query, QLatin1String("CREATE TABLE IF NOT EXISTS `udp` (`id` INTEGER PRIMARY KEY AUTOINCREMENT, `digest` BLOB)"));
	execQueryAndLogFailure(query, QLatin1String("CREATE UNIQUE INDEX IF NOT EXISTS `udp_host_port` ON `udp`(`digest`)"));

	execQueryAndLogFailure(query, QLatin1String("CREATE TABLE IF NOT EXISTS `cert` (`id` INTEGER PRIMARY KEY AUTOINCREMENT, `hostname` TEXT, `port` INTEGER, `digest` TEXT)"));
	execQueryAndLogFailure(query, QLatin1String("CREATE UNIQUE INDEX IF NOT EXISTS `cert_host_port` ON `cert`(`hostname`,`port`)"));

	execQueryAndLogFailure(query, QLatin1String("CREATE TABLE IF NOT EXISTS `friends` (`id` INTEGER PRIMARY KEY AUTOINCREMENT, `name` TEXT, `hash` TEXT)"));
	execQueryAndLogFailure(query, QLatin1String("CREATE UNIQUE INDEX IF NOT EXISTS `friends_name` ON `friends`(`name`)"));
	execQueryAndLogFailure(query, QLatin1String("CREATE UNIQUE INDEX IF NOT EXISTS `friends_hash` ON `friends`(`hash`)"));

	execQueryAndLogFailure(query, QLatin1String("CREATE TABLE IF NOT EXISTS `ignored` (`id` INTEGER PRIMARY KEY AUTOINCREMENT, `hash` TEXT)"));
	execQueryAndLogFailure(query, QLatin1String("CREATE UNIQUE INDEX IF NOT EXISTS `ignored_hash` ON `ignored`(`hash`)"));

	execQueryAndLogFailure(query, QLatin1String("CREATE TABLE IF NOT EXISTS `muted` (`id` INTEGER PRIMARY KEY AUTOINCREMENT, `hash` TEXT)"));
	execQueryAndLogFailure(query, QLatin1String("CREATE UNIQUE INDEX IF NOT EXISTS `muted_hash` ON `muted`(`hash`)"));
	execQueryAndLogFailure(query, QLatin1String("CREATE TABLE IF NOT EXISTS `volume` (`id` INTEGER PRIMARY KEY AUTOINCREMENT, `hash` TEXT, `volume` FLOAT)"));
	execQueryAndLogFailure(query, QLatin1String("CREATE UNIQUE INDEX IF NOT EXISTS `volume_hash` ON `volume`(`hash`)"));

	//Note: A previous snapshot version created a table called 'hidden'
	execQueryAndLogFailure(query, QLatin1String("CREATE TABLE IF NOT EXISTS `filtered_channels` (`id` INTEGER PRIMARY KEY AUTOINCREMENT, `server_cert_digest` TEXT NOT NULL, `channel_id` INTEGER NOT NULL)"));
	execQueryAndLogFailure(query, QLatin1String("CREATE UNIQUE INDEX IF NOT EXISTS `filtered_channels_entry` ON `filtered_channels`(`server_cert_digest`, `channel_id`)"));

	execQueryAndLogFailure(query, QLatin1String("CREATE TABLE IF NOT EXISTS `pingcache` (`id` INTEGER PRIMARY KEY AUTOINCREMENT, `hostname` TEXT, `port` INTEGER, `ping` INTEGER)"));
	execQueryAndLogFailure(query, QLatin1String("CREATE UNIQUE INDEX IF NOT EXISTS `pingcache_host_port` ON `pingcache`(`hostname`,`port`)"));

	execQueryAndLogFailure(query, QLatin1String("DELETE FROM `comments` WHERE `seen` < datetime('now', '-1 years')"));
	execQueryAndLogFailure(query, QLatin1String("DELETE FROM `blobs` WHERE `seen` < datetime('now', '-1 months')"));

	execQueryAndLogFailure(query, QLatin1String("VACUUM"));

	execQueryAndLogFailure(query, QLatin1String("PRAGMA synchronous = OFF"));
#ifdef Q_OS_WIN
	// Windows can not handle TRUNCATE with multiple connections to the DB. Thus less performant DELETE.
	execQueryAndLogFailure(query, QLatin1String("PRAGMA journal_mode = DELETE"));
#else
	execQueryAndLogFailure(query, QLatin1String("PRAGMA journal_mode = TRUNCATE"));
#endif

	execQueryAndLogFailure(query, QLatin1String("SELECT sqlite_version()"));
	while (query.next())
		qWarning() << "Database SQLite:" << query.value(0).toString();
}
Exemplo n.º 5
0
  bool OSArgumentRecord_Impl::compareValues(const QSqlQuery& query) const {
    OS_ASSERT(query.isValid());
    OS_ASSERT(query.isActive());
    OS_ASSERT(query.isSelect());

    bool result = ObjectRecord_Impl::compareValues(query);

    QVariant value;

    value = query.value(OSArgumentRecordColumns::rubyPerturbationRecordId);
    if (value.isValid() && !value.isNull()) {
      result = result && m_rubyMeasureRecordId && (*m_rubyMeasureRecordId == value.toInt());
    }
    else {
      result = result && !m_rubyMeasureRecordId;
    }

    value = query.value(OSArgumentRecordColumns::rubyContinuousVariableRecordId);
    if (value.isValid() && !value.isNull()) {
      result = result && m_rubyContinuousVariableRecordId && (*m_rubyContinuousVariableRecordId == value.toInt());
    }
    else {
      result = result && !m_rubyContinuousVariableRecordId;
    }

    value = query.value(OSArgumentRecordColumns::argumentType);
    OS_ASSERT(value.isValid() && !value.isNull());
    result = result && (m_argumentType == ruleset::OSArgumentType(value.toInt()));

    value = query.value(OSArgumentRecordColumns::required);
    OS_ASSERT(value.isValid() && !value.isNull());
    result = result && (m_required == value.toBool());

    value = query.value(OSArgumentRecordColumns::argumentValue);
    if (value.isValid() && !value.isNull()) {
      result = result && m_argumentValue && (m_argumentValue.get() == value.toString().toStdString());
    }
    else {
      result = result && !m_argumentValue;
    }

    value = query.value(OSArgumentRecordColumns::defaultArgumentValue);
    if (value.isValid() && !value.isNull()) {
      result = result && m_defaultArgumentValue && (m_defaultArgumentValue.get() == value.toString().toStdString());
    }
    else {
      result = result && !m_defaultArgumentValue;
    }

    value = query.value(OSArgumentRecordColumns::domainType);
    OS_ASSERT(value.isValid() && !value.isNull());
    result = result && (m_domainType == ruleset::OSDomainType(value.toInt()));

    value = query.value(OSArgumentRecordColumns::domainValues);
    if (value.isValid() && !value.isNull()) {
      result = result && m_domain && (m_domain.get() == value.toString().toStdString());
    }
    else {
      result = result && !m_domain;
    }

    value = query.value(OSArgumentRecordColumns::choices);
    OS_ASSERT(value.isValid() && !value.isNull());
    result = result && (m_choices == value.toString().toStdString());

    value = query.value(OSArgumentRecordColumns::choiceDisplayNames);
    OS_ASSERT(value.isValid() && !value.isNull());
    result = result && (m_choiceDisplayNames == value.toString().toStdString());

    value = query.value(OSArgumentRecordColumns::isRead);
    OS_ASSERT(value.isValid() && !value.isNull());
    result = result && (m_isRead == value.toBool());

    value = query.value(OSArgumentRecordColumns::extension);
    OS_ASSERT(value.isValid() && !value.isNull());
    result = result && (m_extension == value.toString().toStdString());

    return result;
  }
Exemplo n.º 6
0
void MainWindow::on_pushButton_2_clicked()
{
    if(ui->B_NIO->text().isEmpty() || ui->S_NO->text().isEmpty()){
        QMessageBox::warning(this,tr("提示"),tr("不能为空"),QMessageBox::Ok);
        ui->B_NIO->clear();
        ui->S_NO->clear();
        return;
    }
    QSqlQuery query;
    QString s_num="";
    QString b_num="";
    QString o_name="";
    QString o_author="";
    QString o_price ="";
    QString s_name="";
    QString b_id="";
    query.prepare("select C_NUM from  COUNT where C_NO = :uid");
    query.bindValue(":uid",ui->S_NO->text());
    query.exec();
    if(query.next()){
        s_num = query.value(0).toString();
    }
    query.prepare("select * from  BOOKS where O_ISBN = :bid");
    query.bindValue(":bid",ui->B_NIO->text());
    query.exec();
    if(query.next()){
        o_name = query.value(1).toString();
        o_author = query.value(2).toString();
        o_price = query.value(4).toString();
        b_num = query.value(5).toString();
    }
    qDebug()<<s_num<<b_num;
    query.prepare("SELECT S_NAME FROM STUDENTS WHERE S_NO = ?");
    query.addBindValue(ui->S_NO->text());
    query.exec();
    if(query.next()){
        s_name = query.value(0).toString();
        qDebug()<<s_name;
    }
    if(s_num.isEmpty()){
        QMessageBox::warning(this,tr("提示"),tr("输入学号错误"),QMessageBox::Ok);
        ui->B_NIO->clear();
        ui->S_NO->clear();
        return;
    }
    if(b_num.isEmpty()){
        QMessageBox::warning(this,tr("提示"),tr("输入ISBN错误"),QMessageBox::Ok);
        ui->B_NIO->clear();
        ui->S_NO->clear();
        return;
    }
    int ss_num=s_num.toInt();
    int bb_num=b_num.toInt();
    ++bb_num;
    ++ss_num;
    qDebug()<<ss_num<<bb_num;
    query.prepare("UPDATE BOOKS SET  O_STORAGE = ? WHERE O_ISBN = ?");
    query.addBindValue(QString::number(bb_num,10));
    query.addBindValue(ui->B_NIO->text());
    query.exec();
    query.prepare("UPDATE COUNT SET  C_NUM = ? WHERE C_NO = ?");
    query.addBindValue(QString::number(ss_num,10));
    query.addBindValue(ui->S_NO->text());
    query.exec();
    QDate date;
    QDate oldDate;
    QString oldDatetem;
    date=date.currentDate();
    QString newdate=date.toString("yyyy.M.d");
    qDebug()<<newdate;
    int countI = ui->tableWidget->rowCount();
    ui->tableWidget->insertRow(countI);
    ui->tableWidget->setItem(countI,0,new QTableWidgetItem(ui->S_NO->text()));
    ui->tableWidget->setItem(countI,1,new QTableWidgetItem(s_name));
    ui->tableWidget->setItem(countI,2,new QTableWidgetItem(ui->B_NIO->text()));
    ui->tableWidget->setItem(countI,3,new QTableWidgetItem(o_name));
    ui->tableWidget->setItem(countI,4,new QTableWidgetItem(o_author));
    ui->tableWidget->setItem(countI,5,new QTableWidgetItem(o_price));
    ui->tableWidget->setItem(countI,6,new QTableWidgetItem(QString(tr("还回"))));
    ui->tableWidget->setItem(countI,8,new QTableWidgetItem(newdate));
    query.prepare("SELECT B_ID,B_TIME FROM BORROW WHERE B_NO = ? AND B_ISBN = ? AND B_ISRENT = 0");
    query.addBindValue(ui->S_NO->text());
    query.addBindValue(ui->B_NIO->text());
    query.exec();
    if(query.first()){
        b_id = query.value(0).toString();
        oldDatetem = query.value(1).toString();
        oldDatetem.replace(QString("-"),QString(""));
        qDebug()<<b_id<<oldDatetem;
    }
    query.prepare("UPDATE BORROW SET B_ISRENT=?,B_RENTTIME=? WHERE B_ID = ?");
    query.addBindValue(1);
    query.addBindValue(newdate);
    query.addBindValue(b_id);
    query.exec();
    oldDate=oldDate.fromString(oldDatetem,"yyyyMMdd");
    qDebug()<<oldDate.toString("yyyy.M.d");
    int timeforBorrow = oldDate.daysTo(date);
    if(timeforBorrow > 30){
        qDebug()<<timeforBorrow;
        QString temOfMessage=QString(tr("超期 %1 天")).arg((timeforBorrow-30));
        QMessageBox::information(this,tr("提示"),temOfMessage,QMessageBox::Ok);
        return;
    }
    query.clear();
}
void TableEditor::setupLayout()
{
    // set up agents tab
    agentsModel = new QSqlTableModel(this);
    agentsModel->setTable("agents");
    if (!tableFilter.isEmpty())
        agentsModel->setFilter(tableFilter);
    agentsModel->setEditStrategy(QSqlTableModel::OnManualSubmit);
    agentsModel->select();

    agentsTable = new QTableView(this);
    agentsTable->setModel(agentsModel);
    agentsTable->resizeColumnsToContents();
    agentsTable->sortByColumn(0,Qt::AscendingOrder);
    agentsTable->setSortingEnabled(true);

    // set up determinations tab
    determinationsModel = new QSqlTableModel(this);
    determinationsModel->setTable("determinations");
    if (!tableFilter.isEmpty())
        determinationsModel->setFilter(tableFilter);
    determinationsModel->setEditStrategy(QSqlTableModel::OnManualSubmit);
    determinationsModel->select();

    determinationsTable = new QTableView(this);
    determinationsTable->setModel(determinationsModel);
    determinationsTable->resizeColumnsToContents();
    determinationsTable->sortByColumn(0,Qt::AscendingOrder);
    determinationsTable->setSortingEnabled(true);

    // set up images tab
    imagesModel = new QSqlTableModel(this);
    imagesModel->setTable("images");
    if (!tableFilter.isEmpty())
        imagesModel->setFilter(tableFilter);
    imagesModel->setEditStrategy(QSqlTableModel::OnManualSubmit);
    imagesModel->select();

    imagesTable = new QTableView(this);
    imagesTable->setModel(imagesModel);
    imagesTable->resizeColumnsToContents();
    imagesTable->sortByColumn(19,Qt::AscendingOrder);
    imagesTable->setSortingEnabled(true);

    // set up taxa tab
    taxaModel = new QSqlTableModel(this);
    taxaModel->setTable("taxa");
    if (!tableFilter.isEmpty())
        taxaModel->setFilter(tableFilter);
    taxaModel->setEditStrategy(QSqlTableModel::OnManualSubmit);
    taxaModel->select();

    taxaTable = new QTableView(this);
    taxaTable->setModel(taxaModel);
    taxaTable->resizeColumnsToContents();
    taxaTable->sortByColumn(1,Qt::AscendingOrder);
    taxaTable->setSortingEnabled(true);

    // set up organisms tab
    organismsModel = new QSqlTableModel(this);
    organismsModel->setTable("organisms");
    if (!tableFilter.isEmpty())
        organismsModel->setFilter(tableFilter);
    organismsModel->setEditStrategy(QSqlTableModel::OnManualSubmit);
    organismsModel->select();

    organismsTable = new QTableView(this);
    organismsTable->setModel(organismsModel);
    organismsTable->resizeColumnsToContents();
    organismsTable->sortByColumn(0,Qt::AscendingOrder);
    organismsTable->setSortingEnabled(true);

    // set up sensu tab
    sensuModel = new QSqlTableModel(this);
    sensuModel->setTable("sensu");
    if (!tableFilter.isEmpty())
        sensuModel->setFilter(tableFilter);
    sensuModel->setEditStrategy(QSqlTableModel::OnManualSubmit);
    sensuModel->select();

    sensuTable = new QTableView(this);
    sensuTable->setModel(sensuModel);
    sensuTable->resizeColumnsToContents();
    sensuTable->sortByColumn(0,Qt::AscendingOrder);
    sensuTable->setSortingEnabled(true);

    tabWidget = new QTabWidget(this);
    tabWidget->addTab(agentsTable,"Agents");
    tabWidget->addTab(determinationsTable,"Determinations");
    tabWidget->addTab(imagesTable,"Images");
    tabWidget->addTab(taxaTable,"Names");
    tabWidget->addTab(organismsTable,"Organisms");
    tabWidget->addTab(sensuTable,"Sensu");

    submitButton = new QPushButton(tr("&Save changes"));
    submitButton->setDefault(true);
    refreshButton = new QPushButton(tr("&Revert unsaved changes\nand refresh database"));
    deleteButton = new QPushButton(tr("&Delete selected rows"));
    quitButton = new QPushButton(tr("&Close"));

    buttonBox = new QDialogButtonBox(Qt::Vertical);
    buttonBox->addButton(submitButton, QDialogButtonBox::ActionRole);
    buttonBox->addButton(deleteButton, QDialogButtonBox::ActionRole);
    buttonBox->addButton(refreshButton, QDialogButtonBox::ActionRole);
    buttonBox->addButton(quitButton, QDialogButtonBox::ActionRole);

    connect(submitButton, SIGNAL(clicked()), this, SLOT(submit())); // this needs to save (submit) all changes from all tables
    connect(refreshButton, SIGNAL(clicked()), this, SLOT(refreshAll())); // this needs to refresh all tables to their current database values
    connect(deleteButton, SIGNAL(clicked()), this, SLOT(removeSelectedRows())); // this needs to remove selected rows ONLY from current tab
    connect(quitButton, SIGNAL(clicked()), this, SLOT(confirmClose()));

    QHBoxLayout *mainLayout = new QHBoxLayout;
    mainLayout->addWidget(tabWidget);
    mainLayout->addWidget(buttonBox);
    setLayout(mainLayout);

    setWindowTitle("Table view");

    QSqlDatabase db = QSqlDatabase::database();
    db.transaction();

    QSqlQuery qry;
    qry.prepare("SELECT value FROM settings WHERE setting = (?)");
    qry.addBindValue("view.table.location");
    qry.exec();
    if (qry.next())
        restoreGeometry(qry.value(0).toByteArray());

    bool wasMaximized = false;
    qry.prepare("SELECT value FROM settings WHERE setting = (?)");
    qry.addBindValue("view.table.fullscreen");
    qry.exec();
    if (qry.next())
        wasMaximized = qry.value(0).toBool();

    if (!db.commit())
    {
        qDebug() << "Problem committing changes to database in TableEditor::setupLayout()";
        db.rollback();
    }

    if (wasMaximized)
        this->showMaximized();
}
Exemplo n.º 8
0
void MainWindow::serv_shareNote(QString noteID, QString name, QString token)
{
    if (!tokens.contains(token))
    {
        connect(client, SIGNAL(readyRead()), this, SLOT(stop()));
        QByteArray data;
        data.append("TOKEN_FAIL");
        send(data);
        ui->textBrowser->append("Data access request. Token: "+token+" expired.");
    }
    else
    {
        QSqlQuery search;
        QString id;
        if (search.exec("select id from users where(nickname=\""+name+"\");"))
        {
            if (search.size()==0)
            {
                QByteArray data;
                data.append("NO_SUCH_USER");
                send(data);
                ui->textBrowser->append("NO_SUCH_USER:"******"select * from access where(user="******" and note="+noteID+");"))
        {
            if (check.size()>0)
            {
                ui->textBrowser->append("Already available.");
                QByteArray data;
                data.append("UNERR");
                send(data);
                return;
            }
        }

        QSqlQuery q;
        if (!q.exec("insert into access(user, note, owner) values("+id+", "+noteID+", 0);"))
        {
            ui->textBrowser->append(q.lastError().text());
            QByteArray data;
            data.append("UNERR");
            send(data);
        }
        else
        {
            QByteArray data;
            data.append("SHARE_NOTE_OK");
            send(data);
            ui->textBrowser->append("Note "+noteID+" was shared to "+id+".");
        }
    }
}
Exemplo n.º 9
0
void MainWindow::serv_createNote(QString note, QString token)
{
    if (token == "")
    {
        QByteArray data;
        data.append("UNERR");
        send(data);
    }
    else if (!tokens.contains(token))
    {
        QByteArray data;
        data.append("TOKEN_FAIL");
        send(data);
        ui->textBrowser->append("Data access request. Token: "+token+" expired.");
    }
    else
    {
        QString user = tokens[token];
        QString noteID;
        QJsonObject o = QJsonDocument::fromJson(note.toUtf8()).object();
        QSqlQuery add;
        if (add.exec("insert into notes(name,data,color) values(\""+o["theme"].toString()+"\", \""+o["text"].toString()+"\", \""+o["color"].toString()+"\");"))
        {
            if (add.exec("select last_insert_id();"))
            {
                add.next();
                noteID = add.value(0).toString();
            }
            QJsonArray arr = o["tags"].toArray();
            foreach(QJsonValue val, arr)
            {
                QJsonObject tag = val.toObject();
                ui->textBrowser->append("searching for "+tag["name"].toString());
                QString id = db_searchForTag(tag["name"].toString(),user);
                QSqlQuery q;
                if (!q.exec("insert into tagnote(tag, note) values("+id+", "+noteID+");"))
                {
                    ui->textBrowser->append("insert into tagnote(tag, note) values("+id+", "+noteID+");");
                    ui->textBrowser->append(q.lastError().text());
                }
            }
            arr = o["cats"].toArray();
            foreach(QJsonValue val, arr)
            {
                QJsonObject tag = val.toObject();
                QString id = db_searchForCategory(tag["name"].toString(),user);
                QSqlQuery q;
                if (!q.exec("insert into catnote(tag, note) values("+id+", "+noteID+");"))
                {
                    ui->textBrowser->append("insert into catnote(tag, note) values("+id+", "+noteID+");");
                    ui->textBrowser->append(q.lastError().text());
                }
            }
            QSqlQuery access;
            if (!access.exec("insert into access(note, user, owner) values("+noteID+", "+user+", 1);"))
            {
                ui->textBrowser->append("insert into access(note, user, owner) values("+noteID+", "+user+", 1);");
                ui->textBrowser->append(access.lastError().text());
            }
            QByteArray data;
            data.append("NEW_NOTE_OK||");
            data.append(db_selectUserNotes(user));
            send(data);
        }
Exemplo n.º 10
0
// ////////////////////////////////////////////////////////////////////////
//Méthode permettant de supprimer un client de la base de données
//Paramètres d'entrée :
//                      - Nom1 : Nom du client
//                      - Prenom1 : Prenom du client
//Aucun paramètre de sortie
//Valeur de retour : return true si le client a été supprimé
bool GestionBDD::supprimerClient(QString Nom1,QString Prenom1)
{

    QSqlQuery query;
    QMessageBox delClientMessage,trouve;
    QMessageBox::StandardButtons verifSuppression;
    verifSuppression=QMessageBox::question(0,"Supprimer client","Etes vous sur de vouloir supprimer le client ?",QMessageBox::Yes|QMessageBox::No);

    QString Nom="";
    QString Prenom="";

    //Si l'utilisateur confirme la suppression alors :
            if(verifSuppression==QMessageBox::Yes)
            {
                //Requête permettant de vérifier si le client est dans la base de données pour pouvoir être supprimé
                if(query.exec("SELECT Nom,Prenom FROM asterisk.client WHERE Nom = '" + Nom1 + "' AND Prenom = '" + Prenom1 +"';"))
                {

                    //trouve.setText("Utilisateur trouvé");
                    //trouve.exec();
                    //En cas de succès, récupération des données
                    while(query.next())
                    {
                        Nom =query.value(0).toString();
                        Prenom=query.value(1).toString();
                    }
                    //Réinitialisation des paramètres pour pouvoir faire une nouvelle éventuelle suppression
                    if(Nom==""&&Prenom=="")
                    {
                        trouve.setText("Utilisateur déjà supprimé");
                        trouve.exec();
                        Nom="";
                        Prenom="";
                    }else
                    {
                        //Vérification que tous les champs sont remplis
                       if(Nom1==""||Prenom1=="")
                       {
                           delClientMessage.setText("Veuillez remplir tout les champs");
                           delClientMessage.exec();
                       }else
                       {
                           //Requête permettant de supprimer un client selon les paramètres rentrés
                            if(query.exec("DELETE FROM asterisk.client WHERE Nom = '" + Nom1 + "' AND Prenom = '" + Prenom1 + "';"))
                            {
                                delClientMessage.setText("Le client a été correctement supprimé");
                                delClientMessage.exec();
                                return true;
                            }else
                            {
                                delClientMessage.setText("Erreur lors de la suppression du client");
                                delClientMessage.exec();
                                return false;
                            }
                        }
                    }
                }
            }else
                {
                delClientMessage.setText("Le client n'a pas été supprimé");
                delClientMessage.exec();
                return false;
                }

}
Exemplo n.º 11
0
// /////////////////////////////////////////////////////////////////////
//Methode permettant d'ajouter un nouveau client dans la base de données
//Parametres d'entrée :
//                      - Nom1 : Nom du client
//                      - Prenom1 : Prenom du client
//                      - AddressIP : Adresse IP du client
//                      - Port : Numéro de port de l'adresse IP
//                      - Adresse : Adresse du client
//                      - oodePostal : Code postal du client
//                      - ville : Ville du client
//                      - NumeroTelApp : Numéro de téléphone (pour les appels)
//                      - NuméroTelSMS : Numéro de téléphone portable du client (pour les SMS)
//Aucun parametre de sortie passé dans la methode
//Valeur de retour: return true si le client a été ajouté
bool GestionBDD::ajouterClient(QString Nom1, QString Prenom1,QString AddressIP,QString Port,QString Adresse,QString codePostal,QString ville,QString NumeroTelApp,QString NumeroTelSMS)
{

    QSqlQuery query;
    QMessageBox clientOK,trouve;
    QString Nom="";
    QString Prenom="";
    QString chaineVerif = "SELECT Nom,Prenom FROM asterisk.client WHERE Nom = '" + Nom1 + "' AND Prenom = '" + Prenom1 +"';";
    QString chainePasseClient = "insert into client(Nom, Prenom,Adresse,CodePostal,Ville,NumeroTelApp,NumeroTelSMS)" "VALUES('" + Nom1 + "', '" + Prenom1 + "' , '" + Adresse + "' , '" + codePostal + "' , '" + ville + "' , '" + NumeroTelApp + "' , '" + NumeroTelSMS + "');";
    QString chainePasseCamera = "insert into camera(AddressIP, Port)" "VALUES('" + AddressIP + "', '" + Port + "');";

    //Requête de vérification de non présence d'un client déjà existant
    if(query.exec(chaineVerif))
    {

        //trouve.setText("Utilisateur trouvé");
        //trouve.exec();

        //Récupération des valeurs selon la réquête demandée
        while(query.next())
        {
            Nom =query.value(0).toString();
            Prenom=query.value(1).toString();
        }

        //Si les valeurs récupérés sont non nulles alors le client existe déjà
        if(Nom!=""&&Prenom!="")
        {
            trouve.setText("Utilisateur déjà existant");
            trouve.exec();
            //Réinitialisation des paramètres afin de pouvoir enchainer plusieurs saisies concécutives sans fermeture de la fenêtre
            Nom="";
            Prenom="";
        }
        else
        {

            //Requête permettant d'ajouter un client
            if(query.exec(chainePasseClient))
            {

                //close(); fermer la fenetre apres la saisie
                //return true;

                //Si l'utilisateur a rempli les champs "Adresse IP" et "Numéro de port"
                if(AddressIP!="" && Port!="")
                {
                    if(query.exec(chainePasseCamera))
                    {
                        clientOK.setText("Une nouveau Client à été correctement ajouté avec une camera");
                        clientOK.exec();
                        return true;
                    }
                }
                else
                {
                    clientOK.setText("Un nouveau Client à été correctement ajouté");
                    clientOK.exec();
                }
            }

            else
            {
                clientOK.setText("Erreur aucun client n'as pu etre ajouté");
                clientOK.exec();
                return false;
            }
        }
    }


}
Exemplo n.º 12
0
void DocDigestDetailView::documentListing( TextTemplate *tmpl, int year, int month )
{

    QString minDate;
    QString maxDate;
    if( month > -1 ) {
        QDate theDate(year, month, 1);
        // not a year
        minDate = theDate.toString("yyyy-MM-dd");
        int lastDay = theDate.daysInMonth();
        theDate.setDate(year, month, lastDay);
        maxDate = theDate.toString("yyyy-MM-dd");
    } else {
        // is is a year
        minDate = QString::number(year)+"-01-01";
        maxDate = QString::number(year)+"-12-31";
    }

    // read data in the given timeframe from database
    QSqlQuery q;
    const QString query = QString("SELECT archDocID, ident, MAX(printDate) FROM archdoc WHERE "
                                  "date BETWEEN date('%1') AND date('%2') "
                                  "GROUP BY ident").arg(minDate, maxDate);

    // qDebug() << "***" << query;
    QMap<QString, QPair<int, Geld> > docMatrix;
    q.prepare(query);
    q.exec();
    while( q.next() ) {
       dbID archDocId(q.value(0).toInt());

       const ArchDoc doc(archDocId);
       const QString docType = doc.docType();
       Geld g;
       int n = 0;
       if( docMatrix.contains(docType)) {
           g = docMatrix[docType].second;
           n = docMatrix[docType].first;
       }
       Geld g1 = doc.nettoSum();
       g += g1;
       docMatrix[docType].first = n+1;
       docMatrix[docType].second = g;
     }

    // now create the template

    tmpl->setValue("I18N_AMOUNT", i18n("Amount"));
    tmpl->setValue("I18N_TYPE",   i18n("Type"));
    tmpl->setValue("I18N_SUM",    i18n("Sum"));

    QStringList doctypes = docMatrix.keys();
    doctypes.sort();

    foreach( const QString dtype, doctypes ) {
        qDebug() << "creating doc list for "<<dtype;
        tmpl->createDictionary( "DOCUMENTS" );
        tmpl->setValue("DOCUMENTS", "DOCTYPE", dtype);
        const QString am = QString::number(docMatrix[dtype].first);
        tmpl->setValue("DOCUMENTS", "AMOUNT", am);
        const QString sm = docMatrix[dtype].second.toString(DefaultProvider::self()->locale());
        tmpl->setValue("DOCUMENTS", "SUM", sm);
    }
Exemplo n.º 13
0
/*!
  Эта реализация writeResults только для League!
  */
void League::writeResults() {
    //проверяем, мб мы уже записали
QSettings stg (workdir + "/settings.ini", QSettings::IniFormat, this);
bool isbonus = QFile::exists(workdir+"/bonus.ini");
QSettings bonus (workdir +"/bonus.ini", QSettings::IniFormat, this);
qDebug() << "writing final!";
stg.beginGroup("Tournament");
bool wrote  = false;
wrote = stg.value("stored", false).toBool();
qDebug() << wrote;

    QSqlDatabase db = QSqlDatabase::database("players");
    QSqlQuery q(db) ;
    QSqlQuery sq;
    QString team, nick;
    sq.prepare("SELECT nick, displayname, points FROM Teams ORDER by ABS (points)");
    if (!sq.exec()) {qDebug() << "write result error!" << sq.lastError().text();}
    else {qDebug() << "Query done! " << sq.lastQuery();}
    int rank = 0;
    while (sq.next()) {
        qDebug() << rank;
        rank ++;
        QString result;
        if (rank == 1)
            result.append("Чемпион, ");
         else
             result.append(QVariant (rank).toString() + " место, ");

         result.append(sq.value(2).toString() + " очко(а, ов)");
         nick = sq.value(0).toString();
         team = sq.value(1).toString();
         qDebug() << nick << team << result;
        q.prepare("SELECT smallname FROM Players WHERE nick=:nick");
        q.bindValue(":nick", nick);
        if (!q.exec()) {qDebug() << "SQL Error: " + q.lastError().text() + ", query " + q.executedQuery();}
else {qDebug() << "Query done: " + q.executedQuery();}
q.first();

QString table = q.value(0).toString();
//проверяем
q.prepare("SELECT COUNT (*) FROM "+ table + " WHERE team=:team AND trn=:trn");
      if (!q.exec()) {qDebug() << "SQL Error: " + q.lastError().text() + ", query " + q.executedQuery();}
else {qDebug() << "Query done: " + q.executedQuery();}
q.first();
if (q.value(0).toInt() == 0) {
q.prepare("INSERT INTO " + table + "(team, result) VALUES (:team, :result)");
q.bindValue(":team", team);
q.bindValue(":trn", _title);
 if (!q.exec()) {qDebug() << "SQL Error: " + q.lastError().text() + ", query " + q.executedQuery();}
else {qDebug() << "Query done: " + q.executedQuery();}
//здесь будет выдача бонусов
if (isbonus)
{
    int bpoints = bonus.value(QVariant(rank).toString(), -1).toInt();
    if (bpoints != -1){
        q.prepare("UPDATE Rating SET bonus=(SELECT bonus FROM Rating WHERE nick=:nick)+"+QVariant(bpoints).toString()+" WHERE nick=:nick");
        q.bindValue(":nick", nick);
         if (!q.exec()) {qDebug() << "SQL Error: " + q.lastError().text() + ", query " + q.executedQuery();}
else {qDebug() << "Query done: " + q.executedQuery();}
syncPoints(nick);
    }

}
}
    }
    stg.setValue("stored", true);
stg.endGroup();
stg.sync();
}
Exemplo n.º 14
0
void MainWindow::search()
{
    QTime time;
    time.start();
    QRgb rgb;

    QImage img=ui->widget_2->getImage();
    for(int i=0;i<128;i++)
        for(int j=0;j<128;j++)
        {
            rgb=img.pixel(i,j);
            yiq[0][i][j].setColor(rgb);
        }
    //YIQ **Pyiq=(YIQ**)yiq,**Pyiqh=(YIQ**)yiqh;
    //Now we need Haar 7 times
    for(int l=6;l>=0;l--)
    {
        int n=1<<l;
        int rule=0,rule1=1;
        //if(rule) rule1=0;
        double norm=sqrt(2<<(l-1));
        if(!norm) norm=1;
        for(int i=0;i<n;i++)
            for(int j=0;j<2*n;j++)
            {
                yiq[rule1][i][j].setColor(( yiq[rule][2*i][j].Y + yiq[rule][2*i+1][j].Y )/2,
                                     ( yiq[rule][2*i][j].I + yiq[rule][2*i+1][j].I )/2,
                                     ( yiq[rule][2*i][j].Q + yiq[rule][2*i+1][j].Q )/2);
                yiq[rule1][i+n][j].setColor(( yiq[rule][2*i][j].Y - yiq[rule][2*i+1][j].Y )/norm,
                                     ( yiq[rule][2*i][j].I - yiq[rule][2*i+1][j].I )/norm,
                                     ( yiq[rule][2*i][j].Q - yiq[rule][2*i+1][j].Q )/norm);

            }


        for(int i=0;i<2*n;i++)
            for(int j=0;j<n;j++)
            {
                yiq[rule][i][j].setColor(( yiq[rule1][i][2*j].Y + yiq[rule1][i][2*j+1].Y )/2,
                                     ( yiq[rule1][i][2*j].I + yiq[rule1][i][2*j+1].I )/2,
                                     ( yiq[rule1][i][2*j].Q + yiq[rule1][i][2*j+1].Q )/2);
                yiq[rule][i][j+n].setColor(( yiq[rule1][i][2*j].Y - yiq[rule1][i][2*j+1].Y )/norm,
                                     ( yiq[rule1][i][2*j].I - yiq[rule1][i][2*j+1].I )/norm,
                                     ( yiq[rule1][i][2*j].Q - yiq[rule1][i][2*j+1].Q )/norm);

            }

    }
    //______________________Now I need to sort results for 60 koefs__________________
    SortArray sArray[3];
    sArray[0].n=0;
    sArray[1].n=0;
    sArray[2].n=0;
    sArray[0].nmax=0;
    sArray[1].nmax=0;
    sArray[2].nmax=0;

                       //means to be 128
    for(int i=0;i<k;i++)
        for(int j=0;j<k;j++)
        {
            if(i!=0 && j!=0)
            {
                if(yiq[0][i][j].Y != 0)
                {
                    sArray[0].points[sArray[0].n].V = fabs(yiq[0][i][j].Y);
                    sArray[0].points[sArray[0].n].X = i;
                    sArray[0].points[sArray[0].n].Y = j;
                    if(sArray[0].points[sArray[0].nmax].V <fabs(yiq[0][i][j].Y)) sArray[0].nmax=sArray[0].n;
                    sArray[0].n++;
                }
                if(yiq[0][i][j].I != 0)
                {
                    sArray[1].points[sArray[1].n].V = fabs(yiq[0][i][j].I);
                    sArray[1].points[sArray[1].n].X = i;
                    sArray[1].points[sArray[1].n].Y = j;
                    if(sArray[1].points[sArray[1].nmax].V <fabs(yiq[0][i][j].I)) sArray[1].nmax=sArray[1].n;
                    sArray[1].n++;
                }
                if(yiq[0][i][j].Q != 0)
                {
                    sArray[2].points[sArray[2].n].V = fabs(yiq[0][i][j].Q);
                    sArray[2].points[sArray[2].n].X = i;
                    sArray[2].points[sArray[2].n].Y = j;
                    if(sArray[2].points[sArray[2].nmax].V <fabs(yiq[0][i][j].Q)) sArray[2].nmax=sArray[2].n;
                    sArray[2].n++;
                }
            }
        }

    //_____________________ Only for Debuging ______________________
    //____________________________________________
    /*QPixmap* haarPixmap=new QPixmap(128,128);

    QPainter painter(haarPixmap);
    for(int i=0;i<128;i++)
        for(int j=0; j<128 ; j++)
        {
            painter.setPen(QColor(yiq[0][i][j].getR(), yiq[0][i][j].getG(), yiq[0][i][j].getB()));
            painter.drawPoint(i,j);
        }
    ui->widget_2->setImage(haarPixmap->toImage());*/
    //_____________________________________________

    PointInfo cap;
    int nY=(sArray[0].n>20)?20:sArray[0].n;
    int nI=(sArray[1].n>20)?20:sArray[1].n;
    int nQ=(sArray[2].n>20)?20:sArray[2].n;
    if(nY)
    {
        for(int k=0;k<=nY;k++)
        {
        cap.V=sArray[0].points[k].V;
        cap.X=sArray[0].points[k].X;
        cap.Y=sArray[0].points[k].Y;
        sArray[0].points[k].V=sArray[0].points[sArray[0].nmax].V;
        sArray[0].points[k].X=sArray[0].points[sArray[0].nmax].X;
        sArray[0].points[k].Y=sArray[0].points[sArray[0].nmax].Y;
        sArray[0].points[sArray[0].nmax].V=cap.V;
        sArray[0].points[sArray[0].nmax].X=cap.X;
        sArray[0].points[sArray[0].nmax].Y=cap.Y;
        sArray[0].nmax=k+1;
        for(int i=k+1 ; i < sArray[0].n ; i++)
            if(sArray[0].points[sArray[0].nmax].V < sArray[0].points[i].V)
                sArray[0].nmax=i;
        }
    }
    if(nI)
    {
        for(int k=0;k<=nI;k++)
        {
        cap.V=sArray[1].points[k].V;
        cap.X=sArray[1].points[k].X;
        cap.Y=sArray[1].points[k].Y;
        sArray[1].points[k].V=sArray[1].points[sArray[1].nmax].V;
        sArray[1].points[k].X=sArray[1].points[sArray[1].nmax].X;
        sArray[1].points[k].Y=sArray[1].points[sArray[1].nmax].Y;
        sArray[1].points[sArray[1].nmax].V=cap.V;
        sArray[1].points[sArray[1].nmax].X=cap.X;
        sArray[1].points[sArray[1].nmax].Y=cap.Y;
        sArray[1].nmax=k+1;
        for(int i=k+1 ; i < sArray[1].n ; i++)
            if(sArray[1].points[sArray[1].nmax].V < sArray[1].points[i].V)
                sArray[1].nmax=i;
        }
    }
    if(nQ)
    {
        for(int k=0;k<=nQ;k++)
        {
        cap.V=sArray[2].points[k].V;
        cap.X=sArray[2].points[k].X;
        cap.Y=sArray[2].points[k].Y;
        sArray[2].points[k].V=sArray[2].points[sArray[2].nmax].V;
        sArray[2].points[k].X=sArray[2].points[sArray[2].nmax].X;
        sArray[2].points[k].Y=sArray[2].points[sArray[2].nmax].Y;
        sArray[2].points[sArray[2].nmax].V=cap.V;
        sArray[2].points[sArray[2].nmax].X=cap.X;
        sArray[2].points[sArray[2].nmax].Y=cap.Y;
        sArray[2].nmax=k+1;
        for(int i=k+1 ; i < sArray[2].n ; i++)
            if(sArray[2].points[sArray[2].nmax].V < sArray[2].points[i].V)
                sArray[2].nmax=i;
        }
    }
    //qDebug()<<time.elapsed();
    //_______________ Ok now we have 60 main points, lets transform it in sign______________
    Sign sign[3];
    for(int i=0;i<nY;i++)
    {
        sign[0].points[i].V = (yiq[0][sArray[0].points[i].X][sArray[0].points[i].Y].Y > 0) ? 1 : -1;
        sign[0].points[i].X = sArray[0].points[i].X;
        sign[0].points[i].Y = sArray[0].points[i].Y;
    }
    for(int i=0;i<nI;i++)
    {
        sign[1].points[i].V = (yiq[0][sArray[1].points[i].X][sArray[1].points[i].Y].I > 0) ? 1 : -1;
        sign[1].points[i].X = sArray[1].points[i].X;
        sign[1].points[i].Y = sArray[1].points[i].Y;
    }
    for(int i=0;i<nQ;i++)
    {
        sign[2].points[i].V = (yiq[0][sArray[2].points[i].X][sArray[2].points[i].Y].Q > 0) ? 1 : -1;
        sign[2].points[i].X = sArray[2].points[i].X;
        sign[2].points[i].Y = sArray[2].points[i].Y;
    }
    qDebug()<<time.elapsed();

    QSqlQuery q;
    QSqlQuery qY,qI,qQ;




    q.exec(QLatin1String("SELECT id,bigPath,smallPath,Y,I,Q FROM images"));
    QList< QPair < int,double > > list; //list of weight
    //QList< QPair < int,double > > listShot; //list of shots
    //______________________________________________________________________

    while(q.next())
    {
        int id=q.value(0).toInt();
        list<< qMakePair(id, w0*(fabs(q.value(3).toInt()-yiq[0][0][0].Y)+fabs(q.value(4).toInt()-yiq[0][0][0].I)
                                +fabs(q.value(5).toInt()-yiq[0][0][0].Q)));


        //listShot<< qMakePair(id, 0.0);
        //_________________________________________________________________

    }
    qY.prepare(QLatin1String("SELECT x,y,sign,imageId FROM Y WHERE x=:x AND y=:y AND sign=:sign "));
    for(int i=0;i<nY;i++)
    {
        /*qY.addBindValue(sign[0].points[i].X);
        qY.addBindValue(sign[0].points[i].Y);
        qY.addBindValue(sign[0].points[i].V);*/

        qY.bindValue(":x",sign[0].points[i].X);
        qY.bindValue(":y",sign[0].points[i].Y);
        qY.bindValue(":sign",sign[0].points[i].V);

        qY.exec();
        //showError(qY.lastError());

        while(qY.next())
        {
            for(int j=0;j<list.size();j++)
            {
                if(list.at(j).first == qY.value(3).toInt())
                {
                    int bin=(log(sign[0].points[i].X)/log(2) > log(sign[0].points[i].Y)/log(2))? floor(log(sign[0].points[i].X)/log(2)) : floor(log(sign[0].points[i].Y)/log(2));
                    bin=(bin > 5) ? 5 : bin;
                    list[j]= qMakePair(list.at(j).first, list.at(j).second - w[0][bin]);
                    //listShot[j]= qMakePair(listShot.at(j).first, listShot.at(j).second + 1);
                    //_____________________________________________________________________
                    break;
                }
            }
        }
    }
    qI.prepare(QLatin1String("SELECT x,y,sign,imageId FROM I WHERE x=:x AND y=:y AND sign=:sign "));

    for(int i=0;i<nI;i++)
    {
        /*qI.addBindValue(sign[1].points[i].X);
        qI.addBindValue(sign[1].points[i].Y);
        qI.addBindValue(sign[1].points[i].V);*/

        qY.bindValue(":x",sign[1].points[i].X);
        qY.bindValue(":y",sign[1].points[i].Y);
        qY.bindValue(":sign",sign[1].points[i].V);

        qI.exec();

        while(qI.next())
        {
            for(int j=0;j<list.size();j++)
            {
                if(list.at(j).first == qI.value(3).toInt())
                {
                    int bin=(log(sign[1].points[i].X)/log(2) > log(sign[1].points[i].Y)/log(2))? floor(log(sign[1].points[i].X)/log(2)) : floor(log(sign[1].points[i].Y)/log(2));
                    bin=(bin > 5) ? 5 : bin;
                    list[j]= qMakePair(list.at(j).first, list.at(j).second - w[1][bin]);
                    //listShot[j]= qMakePair(listShot.at(j).first, listShot.at(j).second + 1);
                    //__________________________________________________________________
                    break;
                }
            }
        }
    }
       qQ.prepare(QLatin1String("SELECT x,y,sign,imageId FROM Q WHERE x=:x AND y=:y AND sign=:sign "));
    for(int i=0;i<nQ;i++)
    {
        /*qQ.addBindValue(sign[2].points[i].X);
        qQ.addBindValue(sign[2].points[i].Y);
        qQ.addBindValue(sign[2].points[i].V);*/

        qY.bindValue(":x",sign[2].points[i].X);
        qY.bindValue(":y",sign[2].points[i].Y);
        qY.bindValue(":sign",sign[2].points[i].V);

        qQ.exec();

        while(qQ.next())
        {
            for(int j=0;j<list.size();j++)
            {
                if(list.at(j).first == qQ.value(3).toInt())
                {
                    int bin=(log(sign[2].points[i].X)/log(2) > log(sign[2].points[i].Y)/log(2))? floor(log(sign[2].points[i].X)/log(2)) : floor(log(sign[2].points[i].Y)/log(2));
                    bin=(bin > 5) ? 5 : bin;
                    list[j]= qMakePair(list.at(j).first, list.at(j).second - w[2][bin]);
                    //listShot[j]= qMakePair(listShot.at(j).first, listShot.at(j).second + 1);
                    //____________________________________________________________________
                    break;
                }
            }
        }
    }
    qDebug()<<time.elapsed();

    if(!list.isEmpty()){
        for(int j=0;j<24;j++)
        {
            double min=list.at(j).second;
            int mini=j;
            for(int i=j;i<list.size();i++)
            {
                if(list.at(i).second < min)
                {
                    min = list.at(i).second;
                    mini = i;
                }
            }
            list.swap(j,mini);
        }
    }
    ui->widget_2->timer->stop();

    //__________________________________________________________
    /*for(int j=0;j<24;j++)
    {
        double max=listShot.at(j).second;
        int maxi=j;
        for(int i=j;i<listShot.size();i++)
        {
            if(listShot.at(i).second > max)
            {
                max = listShot.at(i).second;
                maxi = i;
            }
        }
        listShot.swap(j,maxi);
    }*/
    //___________________________________________________________
    if(!list.isEmpty()) ui->widget->updateRes(list);
    int some;
}
Exemplo n.º 15
0
void MapWinCtrl::setupPatients()
{
    QSqlQuery query;
    QString HealthCardNum;
    QString firstName ;
    QString lastName;
    QDateTime dateAdmitted ;
    QDateTime datePlacedOnWaitingList;
    int reqCare;
    int occCare;

     query.exec("SELECT dateAdmitted,datePlacedOnWaitingList,firstName,healthCardNum, lastName ,occCare,reqCare FROM patient ");

     while (query.next()) {
         HealthCardNum =query.value(3).toString();
         firstName = query.value(2).toString();
         lastName = query.value(4).toString();
         datePlacedOnWaitingList = query.value(1).toDateTime();
         dateAdmitted = query.value(0).toDateTime();
         occCare = query.value(5).toInt();
         reqCare = query.value(6).toInt();

         Patient * aPatient = new Patient(HealthCardNum, firstName,lastName,dateAdmitted,datePlacedOnWaitingList,reqCare,occCare);


         if(occCare == 0)

         {
             if (listOfFacility.at(0)->NUsedBedAcute())
             {
                 listOfFacility.at(0)->addPatientAcute(aPatient);

             }
         }

         if (occCare == 1)

         {
             if (listOfFacility.at(0)->NUsedBedComplex())
             {
                 listOfFacility.at(0)->addPatientComplex(aPatient);
             }
         }

         if (occCare == 2)

         {
                 if (listOfFacility.at(0)->NUsedBedLTC())
                 {
                     listOfFacility.at(0)->addPatientLTC(aPatient);
                 }
         }



  //       listOfPatient.append(aPatient);
     }
     qDebug() <<listOfFacility.at(0)->getSizePatientAcute();
     qDebug() <<listOfFacility.at(0)->getSizePatientComplex();
     qDebug() <<listOfFacility.at(0)->getSizePatientLTC();
     query.clear();
}
void SensorsManagerWidget::editSetOfSensorsDialog()
{
                m_names        = new QComboBox();
    QLabel      *namesLabel    = new QLabel(tr("Sets: "));
    QHBoxLayout *layoutNames   = new QHBoxLayout;

    layoutNames->addWidget(namesLabel);
    layoutNames->addWidget(m_names);

                m_numberOfSensors      = new QSpinBox;
    QLabel      *numberOfSensorsLabel  = new QLabel(tr("Number of sensors: "));
    QHBoxLayout *layoutNumberOfSensors = new QHBoxLayout;

    layoutNumberOfSensors->addWidget(numberOfSensorsLabel);
    layoutNumberOfSensors->addWidget(m_numberOfSensors);

                m_sensors         = new QVector<SensorWidget*>;

    QLabel      *sensorName       = new QLabel(tr("Name"));
    QLabel      *sensorX          = new QLabel(tr("X (cm)"));
    QLabel      *sensorY          = new QLabel(tr("Y (cm)"));
    QLabel      *sensorZ          = new QLabel(tr("Z (cm)"));

    QHBoxLayout *layoutLabels     = new QHBoxLayout;

    layoutLabels->addWidget(sensorName);
    layoutLabels->addWidget(sensorX);
    layoutLabels->addWidget(sensorY);
    layoutLabels->addWidget(sensorZ);

                m_layoutSensors   = new QVBoxLayout;

    m_layoutSensors->addLayout(layoutLabels);

                m_comments        = new QTextEdit();
    QLabel      *commentsLabel    = new QLabel(tr("Comments: "));
    QHBoxLayout *layoutComments   = new QHBoxLayout;

    layoutComments->addWidget(commentsLabel);
    layoutComments->addWidget(m_comments);

                m_buttonDialogEdit = new QPushButton(tr("Edit"));
    QPushButton *buttonCancel      = new QPushButton(tr("Cancel"));
    QHBoxLayout *layoutButtons     = new QHBoxLayout;

    layoutButtons->addWidget(m_buttonDialogEdit);
    layoutButtons->addWidget(buttonCancel);
   
    QVBoxLayout *layoutDialog = new QVBoxLayout;
    layoutDialog->addLayout(layoutNames);
    layoutDialog->addLayout(layoutNumberOfSensors);
    layoutDialog->addLayout(m_layoutSensors);
    layoutDialog->addLayout(layoutComments);
    layoutDialog->addLayout(layoutButtons);

    dialogBox = new QDialog();
    dialogBox->setLayout(layoutDialog);

    connect(this, SIGNAL(closeDialog()), dialogBox, SLOT(accept()));
    connect(m_buttonDialogEdit, SIGNAL(clicked()), this, SLOT(editSetOfSensors()));
    connect(buttonCancel, SIGNAL(clicked()), dialogBox, SLOT(accept()));

    m_names->addItem(tr("Select a set..."));
    QSqlQuery query;
    if(query.exec(QString("SELECT %1 FROM %2").arg("name").arg("Sets_of_sensors")))
    {
        while(query.next())
        {
            m_names->addItem(query.value(0).toString());
        }
    }
    else
        QMessageBox::critical(dialogBox, tr("Error"), tr("Unsucessful SELECT query."));

    m_buttonDialogEdit->setEnabled(false);
    connect(m_names, SIGNAL(currentIndexChanged(int)), this, SLOT(enableButtonDialogEdit()));
    connect(m_names, SIGNAL(currentIndexChanged(QString)), this, SLOT(updateSetOfSensors(QString)));
    connect(m_numberOfSensors, SIGNAL(valueChanged(int)), this, SLOT(displaySensorWidgets(int)));

    m_activeWindow = 2;

    dialogBox->exec();

//    m_activeWindow = 0;
}
Exemplo n.º 17
0
    QString str;
    QDate begMonthDate(ui.dateEdit_tabelDate->date().year(), ui.dateEdit_tabelDate->date().month(),1), endMonthDate;
    endMonthDate.setDate(begMonthDate.year(), begMonthDate.month(), begMonthDate.daysInMonth());
    ui.dateEdit_dateFilter->setDate(begMonthDate);

    QString pidrozdilFilter = currentPidrozdil()?QString("Pidrozdil_id=")+sqlStr(currentPidrozdil()):
                              QString(" Pidrozdil_id not in (SELECT id FROM pidrozdily_salary) ");

    //Заповнення комбо пошуку працівника
    ui.comboBox_nprFilter->clear();
    ui.comboBox_nprFilter->addItem("",0);
    query.exec("SELECT id, Prizv, Imia, Pobatk FROM npr \
				WHERE "+pidrozdilFilter+" \
				ORDER BY Prizv, Imia, Pobatk");
    while (query.next())
        ui.comboBox_nprFilter->addItem("["+query.value(0).toString()+"] "+query.value(1).toString()+" "+
                                       query.value(2).toString()+" "+query.value(3).toString(), query.value(0));

    //створення переліку індексів святкових днів
    QSet<int> svIndex;
    query.exec("SELECT CDate FROM svyatkovidni \
				WHERE CDate BETWEEN date("+sqlStr(begMonthDate)+") \
					and date("+sqlStr(endMonthDate)+")");
    while (query.next())
        svIndex << begMonthDate.daysTo(query.value(0).toDate());

    // Заповнення вертикального заголовка
    query.exec("SELECT count(*) FROM npr WHERE "+pidrozdilFilter);
    query.next();
    int rowCount = query.value(0).toInt(), row;
    ui.tableWidget_tabel->setRowCount(rowCount);
bool PrintReport::paintAreaCodeReport(QPainter *p)
{
  QString str;
  QString sql;
  QSqlQuery *q;
  PegCounter areacodes;
  PegCounter numbers;
  bool ok;
  unsigned nullnumbers=0;

  p->fillRect(0,0,p->window().width(),p->window().height(),Qt::white);
  //
  // Display Header
  //
  p->setPen(Qt::black);
  p->setBrush(Qt::black);
  p->setFont(QFont("helvetica",16,QFont::Bold));
  p->drawText((p->window().width()-p->fontMetrics().width(print_header[0]))/2,
	      (int)(p->window().height()*.1263),print_header[0]);
  p->setFont(QFont("helvetica",14,QFont::Normal));
  p->drawText((p->window().width()-p->fontMetrics().width(print_header[1]))/2,
	      (int)(p->window().height()*.1515),print_header[1]);
  str=QString().sprintf("Calls from %s to %s",
			(const char *)start_datetime.toString("MM/dd/yyyy"),
			(const char *)end_datetime.toString("MM/dd/yyyy"));
  p->setFont(QFont("helvetica",12,QFont::Normal));
  p->drawText((p->window().width()-p->fontMetrics().width(str))/2,
	      (int)(p->window().height()*.1894),str);

  //
  // Generate the Peg Counts
  //
  sql=QString().sprintf("select NUMBER from DETAILS_%s\
                         where %s order by NUMBER",
			(const char *)print_showcode,
			(const char *)print_filter);
  q=new QSqlQuery(sql);
  while(q->next()) {
    str=q->value(0).toString();
    str.left(3).toInt(&ok);
    if(ok) {
      numbers.addItem(str);
      areacodes.addItem(str.left(3));
    }
    else {
      nullnumbers++;
    }
  }

  //
  // Print the Summary
  //
  p->drawText(p->window().width()/8,(int)(p->window().height()*.2305),
	      QString().sprintf("Total Calls"));
  str=QString().sprintf("%d",q->size());
  p->drawText(p->window().width()*7/8-p->fontMetrics().width(str),
	      (int)(p->window().height()*.2525),str);

  p->drawText(p->window().width()/8,(int)(p->window().height()*.2525),
	      QString().sprintf("Total Area Codes"));
  str=QString().sprintf("%d",areacodes.size());
  p->drawText(p->window().width()*7/8-p->fontMetrics().width(str),
	      (int)(p->window().height()*.2745),str);

  p->drawText(p->window().width()/8,(int)(p->window().height()*.2745),
	      QString().sprintf("Total Unique Numbers"));
  str=QString().sprintf("%d",numbers.size());
  p->drawText(p->window().width()*7/8-p->fontMetrics().width(str),
	      (int)(p->window().height()*.2965),str);

  p->drawText(p->window().width()/8,(int)(p->window().height()*.2965),
	      QString().sprintf("Total Blocked Number Calls"));
  str=QString().sprintf("%u",nullnumbers);
  p->drawText(p->window().width()*7/8-p->fontMetrics().width(str),
	      (int)(p->window().height()*.3185),str);

  p->drawText(p->window().width()/8,(int)(p->window().height()*.3295),
	      QString().sprintf("Area Codes:"));
  str=QString().sprintf("%u",nullnumbers);
  p->drawText(p->window().width()*7/8-p->fontMetrics().width(str),
	      (int)(p->window().height()*.3185),str);

  delete q;

  //
  // Print the Counts
  //
  p->setFont(QFont("helvetica",10,QFont::Normal));
  for(int i=0;i<areacodes.size();i+=4) {
    p->drawText(p->window().width()*3/16,
		(int)(p->window().height()*.3645)+i*p->window().height()/180,
		QString().sprintf("%s [%d]",
				  (const char *)areacodes.itemName(i),
				  areacodes.itemCount(i)));

    if((i+1)<areacodes.size()) {
      p->drawText(p->window().width()*6/16,
		  (int)(p->window().height()*.3645)+i*p->window().height()/180,
		  QString().sprintf("%s [%d]",
				    (const char *)areacodes.itemName(i+1),
				    areacodes.itemCount(i+1)));
    }

    if((i+2)<areacodes.size()) {
      p->drawText(p->window().width()*9/16,
		  (int)(p->window().height()*.3645)+i*p->window().height()/180,
		  QString().sprintf("%s [%d]",
				    (const char *)areacodes.itemName(i+2),
				    areacodes.itemCount(i+2)));
    }

    if((i+3)<areacodes.size()) {
      p->drawText(p->window().width()*12/16,
		  (int)(p->window().height()*.3645)+i*p->window().height()/180,
		  QString().sprintf("%s [%d]",
				    (const char *)areacodes.itemName(i+3),
				    areacodes.itemCount(i+3)));
    }
  }

  //
  // Print the Footer
  //
  p->setFont(QFont("helvetica",6,QFont::Light));
  p->drawText((int)(p->window().width()/8.5),(int)(p->window().height()*.9090),
	      "Generated by CallCommander");
  p->drawText(p->window().width()-p->fontMetrics().
	      width(WEB_URL)-(int)(p->window().width()/8.5),
	      (int)(p->window().height()*.9090),WEB_URL);

  return false;
}
Exemplo n.º 19
0
void MainWindow::on_pushButton_3_clicked()
{
    if(ui->B_NIO->text().isEmpty() || ui->S_NO->text().isEmpty()){
        QMessageBox::information(this,tr("提示"),tr("不能为空"),QMessageBox::Ok);
        ui->B_NIO->clear();
        ui->S_NO->clear();
        return;
    }
    QSqlQuery query;
    QString s_num="";
    QString b_num="";
    QString o_name="";
    QString o_author="";
    QString o_price ="";
    QString s_name="";
    query.prepare("select C_NUM from  COUNT where C_NO = :uid");
    query.bindValue(":uid",ui->S_NO->text());
    query.exec();
    if(query.next()){
        s_num = query.value(0).toString();
    }
    query.prepare("select * from  BOOKS where O_ISBN = :bid");
    query.bindValue(":bid",ui->B_NIO->text());
    query.exec();
    if(query.next()){
        o_name = query.value(1).toString();
        o_author = query.value(2).toString();
        o_price = query.value(4).toString();
        b_num = query.value(5).toString();
    }
    qDebug()<<s_num<<b_num;
    query.prepare("SELECT S_NAME FROM STUDENTS WHERE S_NO = ?");
    query.addBindValue(ui->S_NO->text());
    query.exec();
    if(query.next()){
        s_name = query.value(0).toString();
        qDebug()<<s_name;
    }
    if(s_num.isEmpty() || s_num.toInt() < 1){
        QMessageBox::information(this,tr("提示"),tr("输入学号错误"),QMessageBox::Ok);
        ui->B_NIO->clear();
        ui->S_NO->clear();
        return;
    }
    if(b_num.isEmpty() || b_num.toInt() < 1){
        QMessageBox::information(this,tr("提示"),tr("输入ISBN错误"),QMessageBox::Ok);
        ui->B_NIO->clear();
        ui->S_NO->clear();
        return;
    }
    int ss_num=s_num.toInt();
    int bb_num=b_num.toInt();
    --bb_num;
    --ss_num;
    QString temss = QString(tr("%1还能借%2本书")).arg(s_name).arg(ss_num);
    QMessageBox::information(this,tr("提示"),temss,QMessageBox::Ok);
    query.prepare("UPDATE BOOKS SET  O_STORAGE = ? WHERE O_ISBN = ?");
    query.addBindValue(QString::number(bb_num,10));
    query.addBindValue(ui->B_NIO->text());
    query.exec();
    query.prepare("UPDATE COUNT SET  C_NUM = ? WHERE C_NO = ?");
    query.addBindValue(QString::number(ss_num,10));
    query.addBindValue(ui->S_NO->text());
    query.exec();
    QDate date;
    date=date.fromString("2012.9.1","yyyy.M.d");
    //date=date.currentDate();
    QString newdate=date.toString("yyyy.M.d");
    qDebug()<<newdate;
    int countI = ui->tableWidget->rowCount();
    ui->tableWidget->insertRow(countI);
    ui->tableWidget->setItem(countI,0,new QTableWidgetItem(ui->S_NO->text()));
    ui->tableWidget->setItem(countI,1,new QTableWidgetItem(s_name));
    ui->tableWidget->setItem(countI,2,new QTableWidgetItem(ui->B_NIO->text()));
    ui->tableWidget->setItem(countI,3,new QTableWidgetItem(o_name));
    ui->tableWidget->setItem(countI,4,new QTableWidgetItem(o_author));
    ui->tableWidget->setItem(countI,5,new QTableWidgetItem(o_price));
    ui->tableWidget->setItem(countI,6,new QTableWidgetItem(QString(tr("借出"))));
    ui->tableWidget->setItem(countI,7,new QTableWidgetItem(newdate));
    query.prepare("INSERT INTO BORROW (B_NO,B_ISBN,B_TIME,B_ISRENT) VALUES(?,?,?,?)");
    query.addBindValue(ui->S_NO->text());
    query.addBindValue(ui->B_NIO->text());
    query.addBindValue(newdate);
    query.addBindValue(0);
    query.exec();
    query.clear();
}
Exemplo n.º 20
0
bool Note::fillFromQuery(QSqlQuery query) {
    id = query.value("id").toInt();
    name = query.value("name").toString();
    fileName = query.value("file_name").toString();
    noteText = query.value("note_text").toString();
    decryptedNoteText = query.value("decrypted_note_text").toString();
    cryptoKey = query.value("crypto_key").toLongLong();
    cryptoPassword = query.value("crypto_password").toString();
    hasDirtyData = query.value("has_dirty_data").toInt() == 1;
    fileCreated = query.value("file_created").toDateTime();
    fileLastModified = query.value("file_last_modified").toDateTime();
    created = query.value("created").toDateTime();
    modified = query.value("modified").toDateTime();

    return true;
}
Exemplo n.º 21
0
Database::Database() {
	QSqlDatabase db = QSqlDatabase::addDatabase(QLatin1String("QSQLITE"));
	QSettings qs;
	QStringList datapaths;
	int i;

	datapaths << g.qdBasePath.absolutePath();
	datapaths << QDesktopServices::storageLocation(QDesktopServices::DataLocation);
#if defined(Q_OS_UNIX) && ! defined(Q_OS_MAC)
	datapaths << QDir::homePath() + QLatin1String("/.config/Mumble");
#endif
	datapaths << QDir::homePath();
	datapaths << QDir::currentPath();
	datapaths << qApp->applicationDirPath();
	datapaths << qs.value(QLatin1String("InstPath")).toString();
	bool found = false;

	for (i = 0; (i < datapaths.size()) && ! found; i++) {
		if (!datapaths[i].isEmpty()) {
			QFile f(datapaths[i] + QLatin1String("/mumble.sqlite"));
			if (f.exists()) {
				db.setDatabaseName(f.fileName());
				found = db.open();
			}

			QFile f2(datapaths[i] + QLatin1String("/.mumble.sqlite"));
			if (f2.exists()) {
				db.setDatabaseName(f2.fileName());
				found = db.open();
			}
		}
	}

	if (! found) {
		for (i = 0; (i < datapaths.size()) && ! found; i++) {
			if (!datapaths[i].isEmpty()) {
				QDir::root().mkpath(datapaths[i]);
#ifdef Q_OS_WIN
				QFile f(datapaths[i] + QLatin1String("/mumble.sqlite"));
#else
				QFile f(datapaths[i] + QLatin1String("/.mumble.sqlite"));
#endif
				db.setDatabaseName(f.fileName());
				found = db.open();
			}
		}
	}

	if (! found) {
		QMessageBox::critical(NULL, QLatin1String("Mumble"), tr("Mumble failed to initialize a database in any\nof the possible locations."), QMessageBox::Ok | QMessageBox::Default, QMessageBox::NoButton);
		qFatal("Database: Failed initialization");
	}

	QFileInfo fi(db.databaseName());

	if (! fi.isWritable()) {
		QMessageBox::critical(NULL, QLatin1String("Mumble"), tr("The database '%1' is read-only. Mumble cannot store server settings (i.e. SSL certificates) until you fix this problem.").arg(fi.filePath()), QMessageBox::Ok | QMessageBox::Default, QMessageBox::NoButton);
		qWarning("Database: Database is read-only");
	}

	QSqlQuery query;

	query.exec(QLatin1String("CREATE TABLE IF NOT EXISTS `servers` (`id` INTEGER PRIMARY KEY AUTOINCREMENT, `name` TEXT, `hostname` TEXT, `port` INTEGER DEFAULT " MUMTEXT(DEFAULT_MUMBLE_PORT) ", `username` TEXT, `password` TEXT)"));
	query.exec(QLatin1String("ALTER TABLE `servers` ADD COLUMN `url` TEXT"));

	query.exec(QLatin1String("CREATE TABLE IF NOT EXISTS `comments` (`who` TEXT, `comment` BLOB, `seen` DATE)"));
	query.exec(QLatin1String("CREATE UNIQUE INDEX IF NOT EXISTS `comments_comment` ON `comments`(`who`, `comment`)"));
	query.exec(QLatin1String("CREATE INDEX IF NOT EXISTS `comments_seen` ON `comments`(`seen`)"));

	query.exec(QLatin1String("CREATE TABLE IF NOT EXISTS `blobs` (`hash` TEXT, `data` BLOB, `seen` DATE)"));
	query.exec(QLatin1String("CREATE UNIQUE INDEX IF NOT EXISTS `blobs_hash` ON `blobs`(`hash`)"));
	query.exec(QLatin1String("CREATE INDEX IF NOT EXISTS `blobs_seen` ON `blobs`(`seen`)"));

	query.exec(QLatin1String("CREATE TABLE IF NOT EXISTS `tokens` (`id` INTEGER PRIMARY KEY AUTOINCREMENT, `digest` BLOB, `token` TEXT)"));
	query.exec(QLatin1String("CREATE INDEX IF NOT EXISTS `tokens_host_port` ON `tokens`(`digest`)"));

	query.exec(QLatin1String("CREATE TABLE IF NOT EXISTS `shortcut` (`id` INTEGER PRIMARY KEY AUTOINCREMENT, `digest` BLOB, `shortcut` BLOB, `target` BLOB, `suppress` INTEGER)"));
	query.exec(QLatin1String("CREATE INDEX IF NOT EXISTS `shortcut_host_port` ON `shortcut`(`digest`)"));

	query.exec(QLatin1String("CREATE TABLE IF NOT EXISTS `udp` (`id` INTEGER PRIMARY KEY AUTOINCREMENT, `digest` BLOB)"));
	query.exec(QLatin1String("CREATE UNIQUE INDEX IF NOT EXISTS `udp_host_port` ON `udp`(`digest`)"));

	query.exec(QLatin1String("CREATE TABLE IF NOT EXISTS `cert` (`id` INTEGER PRIMARY KEY AUTOINCREMENT, `hostname` TEXT, `port` INTEGER, `digest` TEXT)"));
	query.exec(QLatin1String("CREATE UNIQUE INDEX IF NOT EXISTS `cert_host_port` ON `cert`(`hostname`,`port`)"));

	query.exec(QLatin1String("CREATE TABLE IF NOT EXISTS `friends` (`id` INTEGER PRIMARY KEY AUTOINCREMENT, `name` TEXT, `hash` TEXT)"));
	query.exec(QLatin1String("CREATE UNIQUE INDEX IF NOT EXISTS `friends_name` ON `friends`(`name`)"));
	query.exec(QLatin1String("CREATE UNIQUE INDEX IF NOT EXISTS `friends_hash` ON `friends`(`hash`)"));

	query.exec(QLatin1String("CREATE TABLE IF NOT EXISTS `muted` (`id` INTEGER PRIMARY KEY AUTOINCREMENT, `hash` TEXT)"));
	query.exec(QLatin1String("CREATE UNIQUE INDEX IF NOT EXISTS `muted_hash` ON `muted`(`hash`)"));

	query.exec(QLatin1String("CREATE TABLE IF NOT EXISTS `pingcache` (`id` INTEGER PRIMARY KEY AUTOINCREMENT, `hostname` TEXT, `port` INTEGER, `ping` INTEGER)"));
	query.exec(QLatin1String("CREATE UNIQUE INDEX IF NOT EXISTS `pingcache_host_port` ON `pingcache`(`hostname`,`port`)"));

	query.exec(QLatin1String("DELETE FROM `comments` WHERE `seen` < datetime('now', '-1 years')"));
	query.exec(QLatin1String("DELETE FROM `blobs` WHERE `seen` < datetime('now', '-1 months')"));

	query.exec(QLatin1String("VACUUM"));

	query.exec(QLatin1String("PRAGMA synchronous = OFF"));
	query.exec(QLatin1String("PRAGMA journal_mode = TRUNCATE"));

	query.exec(QLatin1String("SELECT sqlite_version()"));
	while (query.next())
		qWarning() << "Database SQLite:" << query.value(0).toString();
}
Exemplo n.º 22
0
void ZealDocsetsRegistry::_runQuery(const QString& rawQuery, int queryNum)
{
    if(queryNum != lastQuery) return; // some other queries pending - ignore this one

    QList<ZealSearchResult> results;
    ZealSearchQuery query(rawQuery);

    QString preparedQuery = query.getSanitizedQuery();
    bool hasDocsetFilter = query.hasDocsetFilter();

    for (const ZealDocsetsRegistry::docsetEntry docset : docsets()) {
        if(hasDocsetFilter && !query.docsetPrefixMatch(docset.prefix)) {
            // Filter out this docset as the names don't match the docset prefix
            continue;
        }

        QString qstr;
        QSqlQuery q;
        QList<QList<QVariant> > found;
        bool withSubStrings = false;
        // %.%1% for long Django docset values like django.utils.http
        // %::%1% for long C++ docset values like std::set
        // %/%1% for long Go docset values like archive/tar
        QString subNames = QString(" or %1 like '%.%2%' escape '\\'");
        subNames += QString(" or %1 like '%::%2%' escape '\\'");
        subNames += QString(" or %1 like '%/%2%' escape '\\'");
        while(found.size() < 100) {
            auto curQuery = preparedQuery;
            QString notQuery; // don't return the same result twice
            QString parentQuery;
            if(withSubStrings) {
                // if less than 100 found starting with query, search all substrings
                curQuery = "%"+preparedQuery;
                // don't return 'starting with' results twice
                if(docset.type == ZDASH) {
                    notQuery = QString(" and not (ztokenname like '%1%' escape '\\' %2) ").arg(preparedQuery, subNames.arg("ztokenname", preparedQuery));
                } else {
                    if(docset.type == ZEAL) {
                        notQuery = QString(" and not (t.name like '%1%' escape '\\') ").arg(preparedQuery);
                        parentQuery = QString(" or t2.name like '%1%' escape '\\' ").arg(preparedQuery);
                    } else { // DASH
                        notQuery = QString(" and not (t.name like '%1%' escape '\\' %2) ").arg(preparedQuery, subNames.arg("t.name", preparedQuery));
                    }
                }
            }
            int cols = 3;
            if(docset.type == ZEAL) {
                qstr = QString("select t.name, t2.name, t.path from things t left join things t2 on t2.id=t.parent where "
                               "(t.name like '%1%' escape '\\'  %3) %2 order by length(t.name), lower(t.name) asc, t.path asc limit 100").arg(curQuery, notQuery, parentQuery);

            } else if(docset.type == DASH) {
                qstr = QString("select t.name, null, t.path from searchIndex t where (t.name "
                               "like '%1%' escape '\\' %3)  %2 order by length(t.name), lower(t.name) asc, t.path asc limit 100").arg(curQuery, notQuery, subNames.arg("t.name", curQuery));
            } else if(docset.type == ZDASH) {
                cols = 4;
                qstr = QString("select ztokenname, null, zpath, zanchor from ztoken "
                                "join ztokenmetainformation on ztoken.zmetainformation = ztokenmetainformation.z_pk "
                                "join zfilepath on ztokenmetainformation.zfile = zfilepath.z_pk where (ztokenname "

                               "like '%1%' escape '\\' %3) %2 order by length(ztokenname), lower(ztokenname) asc, zpath asc, "
                               "zanchor asc limit 100").arg(curQuery, notQuery, subNames.arg("ztokenname", curQuery));
            }
            q = db(docset.name).exec(qstr);
            while(q.next()) {
                QList<QVariant> values;
                for(int i = 0; i < cols; ++i) {
                    values.append(q.value(i));
                }
                found.append(values);
            }

            if(withSubStrings) break;
            withSubStrings = true;  // try again searching for substrings
        }
        for(auto &row : found) {
            QString parentName;
            if(!row[1].isNull()) {
                parentName = row[1].toString();
            }
            auto path = row[2].toString();
            // FIXME: refactoring to use common code in ZealListModel and ZealDocsetsRegistry
            if(docset.type == ZDASH) {
                path += "#" + row[3].toString();
            }
            auto itemName = row[0].toString();
            normalizeName(itemName, parentName, row[1].toString());
            results.append(ZealSearchResult(itemName, parentName, path, docset.name, preparedQuery));
        }
    }
    qSort(results);
    if(queryNum != lastQuery) return; // some other queries pending - ignore this one

    queryResults = results;
    emit queryCompleted();
}
Exemplo n.º 23
0
  void OSArgumentRecord_Impl::setLastValues(const QSqlQuery& query,
                                            ProjectDatabase& projectDatabase)
  {
    OS_ASSERT(query.isValid());
    OS_ASSERT(query.isActive());
    OS_ASSERT(query.isSelect());

    ObjectRecord_Impl::setLastValues(query,projectDatabase);

    QVariant value;

    value = query.value(OSArgumentRecord::ColumnsType::rubyPerturbationRecordId);
    if (value.isValid() && !value.isNull()) {
      m_lastRubyMeasureRecordId = value.toInt();
    }
    else {
      m_lastRubyMeasureRecordId.reset();
    }

    value = query.value(OSArgumentRecord::ColumnsType::rubyContinuousVariableRecordId);
    if (value.isValid() && !value.isNull()) {
      m_lastRubyContinuousVariableRecordId = value.toInt();
    }
    else {
      m_lastRubyContinuousVariableRecordId.reset();
    }

    value = query.value(OSArgumentRecord::ColumnsType::argumentType);
    OS_ASSERT(value.isValid() && !value.isNull());
    m_lastArgumentType = ruleset::OSArgumentType(value.toInt());

    value = query.value(OSArgumentRecord::ColumnsType::required);
    OS_ASSERT(value.isValid() && !value.isNull());
    m_lastRequired = value.toBool();

    value = query.value(OSArgumentRecord::ColumnsType::argumentValue);
    if (value.isValid() && !value.isNull()) {
      m_lastArgumentValue = value.toString().toStdString();
    }
    else {
      m_lastArgumentValue.reset();
    }

    value = query.value(OSArgumentRecord::ColumnsType::defaultArgumentValue);
    if (value.isValid() && !value.isNull()) {
      m_lastDefaultArgumentValue = value.toString().toStdString();
    }
    else {
      m_lastDefaultArgumentValue.reset();
    }

    value = query.value(OSArgumentRecord::ColumnsType::domainType);
    OS_ASSERT(value.isValid() && !value.isNull());
    m_lastDomainType = ruleset::OSDomainType(value.toInt());

    value = query.value(OSArgumentRecord::ColumnsType::domainValues);
    if (value.isValid() && !value.isNull()) {
      m_lastDomain = value.toString().toStdString();
    }
    else {
      m_lastDomain.reset();
    }

    value = query.value(OSArgumentRecord::ColumnsType::choices);
    OS_ASSERT(value.isValid() && !value.isNull());
    m_lastChoices = value.toString().toStdString();

    value = query.value(OSArgumentRecord::ColumnsType::choiceDisplayNames);
    OS_ASSERT(value.isValid() && !value.isNull());
    m_lastChoiceDisplayNames = value.toString().toStdString();

    value = query.value(OSArgumentRecord::ColumnsType::isRead);
    OS_ASSERT(value.isValid() && !value.isNull());
    m_lastIsRead = value.toBool();

    value = query.value(OSArgumentRecord::ColumnsType::extension);
    OS_ASSERT(value.isValid() && !value.isNull());
    m_lastExtension = value.toString().toStdString();
  }
Exemplo n.º 24
0
Message::ptr_t Message::load(QObject &parent, int dbId)
{
    QSqlQuery query;

    enum Fields {
        direction, state,  conversation_id, conversation, message_id, composed_time, received_time, content, signature, sender, encoding
    };

    query.prepare("SELECT direction, state, conversation_id, conversation, message_id, composed_time, received_time, content, signature, sender, encoding FROM message where id=:id ");
    query.bindValue(":id", dbId);

    if(!query.exec()) {
        throw Error(QStringLiteral("Failed to fetch Message: %1").arg(
                        query.lastError().text()));
    }

    if (!query.next()) {
        throw NotFoundError(QStringLiteral("Message not found!"));
    }

    auto ptr = make_shared<Message>(parent);
    ptr->data_ = make_unique<MessageData>();

    ptr->id_ = dbId;
    ptr->direction_ = static_cast<Direction>(query.value(direction).toInt());
    ptr->state_ = static_cast<State>(query.value(state).toInt());
    ptr->conversationId_ = query.value(conversation_id).toInt();
    ptr->data_->conversation = query.value(conversation).toByteArray();
    ptr->data_->messageId = query.value(message_id).toByteArray();
    ptr->data_->composedTime = query.value(composed_time).toDateTime();
    ptr->sentReceivedTime_ = query.value(received_time).toDateTime();
    ptr->data_->content = query.value(content).toString();
    ptr->data_->signature = query.value(signature).toByteArray();
    ptr->data_->sender = query.value(sender).toByteArray();
    ptr->data_->encoding = static_cast<Encoding>(query.value(encoding).toInt());

    return ptr;
}
Exemplo n.º 25
0
// Return a note structure given the LID
bool NoteTable::get(Note &note, qint32 lid,bool loadResources, bool loadResourceRecognition) {

    QSqlQuery query;
    query.prepare("Select key, data from DataStore where lid=:lid");
    query.bindValue(":lid", lid);

    query.exec();
    while (query.next()) {
        qint32 key = query.value(0).toInt();
        switch (key) {
        case (NOTE_GUID):
            note.guid = query.value(1).toString().toStdString();
            note.__isset.guid = true;
            break;
        case (NOTE_UPDATE_SEQUENCE_NUMBER):
            note.updateSequenceNum = query.value(1).toInt();
            note.__isset.updateSequenceNum = true;
            break;
        case (NOTE_ACTIVE):
            note.active = query.value(1).toBool();
            note.__isset.active = true;
            break;
        case (NOTE_DELETED_DATE):
            note.active = query.value(1).toLongLong();
            note.__isset.deleted = true;
            break;
        case (NOTE_ATTRIBUTE_SOURCE_URL):
            note.attributes.sourceURL = query.value(1).toString().toStdString();
            note.__isset.attributes = true;
            note.attributes.__isset.sourceURL = true;
            break;
        case (NOTE_ATTRIBUTE_SOURCE_APPLICATION):
            note.attributes.sourceApplication = query.value(1).toString().toStdString();
            note.__isset.attributes = true;
            note.attributes.__isset.sourceApplication = true;
            break;
        case (NOTE_CONTENT_LENGTH):
            note.contentLength = query.value(1).toLongLong();
            note.__isset.contentLength = true;
            break;
        case (NOTE_ATTRIBUTE_LONGITUDE):
            note.attributes.longitude = query.value(1).toFloat();
            note.__isset.attributes = true;
            note.attributes.__isset.longitude = true;
            break;
        case (NOTE_TITLE):
            note.title = query.value(1).toString().toStdString();
            note.__isset.title = true;
            break;
        case (NOTE_ATTRIBUTE_SOURCE):
            note.attributes.source = query.value(1).toString().toStdString();
            note.__isset.attributes = true;
            note.attributes.__isset.source = true;
            break;
        case (NOTE_ATTRIBUTE_ALTITUDE):
            note.attributes.altitude = query.value(1).toFloat();
            note.__isset.attributes = true;
            note.attributes.__isset.altitude = true;
            break;
        case (NOTE_NOTEBOOK_LID): {
            qint32 notebookLid = query.value(1).toInt();
            NotebookTable ntable;
            QString notebookGuid;
            ntable.getGuid(notebookGuid, notebookLid);
            note.notebookGuid = notebookGuid.toStdString();
            note.__isset.notebookGuid = true;
            break;
        }
        case (NOTE_UPDATED_DATE):
            note.updated = query.value(1).toLongLong();
            note.__isset.updated = true;
            break;
        case (NOTE_CREATED_DATE):
            note.created = query.value(1).toLongLong();
            note.__isset.created = true;
            break;
        case (NOTE_ATTRIBUTE_SUBJECT_DATE):
            note.attributes.subjectDate = query.value(1).toLongLong();
            note.__isset.attributes = true;
            note.attributes.__isset.subjectDate = true;
            break;
        case (NOTE_ATTRIBUTE_LATITUDE):
            note.attributes.latitude = query.value(1).toFloat();
            note.__isset.attributes = true;
            note.attributes.__isset.latitude = true;
            break;
        case (NOTE_CONTENT):
            note.content = query.value(1).toByteArray().data();
            note.__isset.content = true;
            break;
        case (NOTE_CONTENT_HASH):
            note.contentHash = query.value(1).toString().toStdString();
            note.__isset.contentHash = true;
            break;
        case (NOTE_ATTRIBUTE_AUTHOR):
            note.attributes.author = query.value(1).toString().toStdString();
            note.__isset.attributes = true;
            note.attributes.__isset.author = true;
            break;
        case (NOTE_ISDIRTY):
            break;
        case (NOTE_ATTRIBUTE_SHARE_DATE) :
            note.attributes.shareDate = query.value(1).toLongLong();
            note.__isset.attributes = true;
            note.attributes.__isset.shareDate = true;
            break;
        case (NOTE_ATTRIBUTE_PLACE_NAME) :
            note.attributes.placeName = query.value(1).toString().toStdString();
            note.__isset.attributes = true;
            note.attributes.__isset.placeName = true;
            break;
        case (NOTE_ATTRIBUTE_CONTENT_CLASS) :
            note.attributes.contentClass = query.value(1).toString().toStdString();
            note.__isset.attributes = true;
            note.attributes.__isset.contentClass = true;
            break;
        case (NOTE_TAG_LID) :
            TagTable tagTable;
            qint32 tagLid = query.value(1).toInt();
            Tag tag;
            tagTable.get(tag, tagLid);
            note.__isset.tagGuids = true;
            note.__isset.tagNames = true;
            note.tagGuids.push_back(tag.guid);
            note.tagNames.push_back(tag.name);
            break;
        }
    }

    ResourceTable resTable;
    QList<qint32> resList;
    if (resTable.getResourceList(resList, lid)) {
        for (int i=0; i<resList.size(); i++) {
            Resource resource;
            if (loadResources) {
                resTable.get(resource, resList[i]);
            } else {
                QString resGuid = resTable.getGuid(resList[i]);
                resource.guid = resGuid.toStdString();
                resource.__isset.guid = true;
            }
            note.__isset.resources = true;
            note.resources.push_back(resource);
        }
    }

    /*
    TagScanner test;
    test.setData(QString::fromStdString(note.content));
    QList<TagScannerRecord> retval;
    int k = test.findAll(retval, QString("en-note"));
    */

    if (note.__isset.guid)
        return true;
    else
        return false;
}
Exemplo n.º 26
0
SeeStats::SeeStats(Session *session, QWidget *parent) :
    QWidget(parent),
    ui(new Ui::SeeStats)
{
    ui->setupUi(this);
    this->showMaximized();

    ostringstream s;
    s << "SELECT Student.id AS id, Student.name AS name, Student.directory AS path, COUNT(Face.id) AS caras, "
            "SessionStudent.'column' AS columna, SessionStudent.'row' AS fila\n"
            "FROM Student, Face, SessionStudent\n"
            "WHERE Student.id = Face.id_student and Face.id_session =" << session->getId() <<
            " and SessionStudent.id_session =" << session->getId() << " and SessionStudent.id_student = Student.id\n" <<
            "GROUP BY Student.id;";
    cout << s.str() << endl;

    QSqlQuery query = QSqlQuery(QString(s.str().c_str()));

    ui->tableWidget->setColumnCount(5);
    int i = 1;

    ui->tableWidget->setHorizontalHeaderItem(0, new QTableWidgetItem("Foto"));
    ui->tableWidget->setHorizontalHeaderItem(1, new QTableWidgetItem("Nombre"));
    ui->tableWidget->setHorizontalHeaderItem(2, new QTableWidgetItem("Número de caras en esta sesión"));
    ui->tableWidget->setHorizontalHeaderItem(3, new QTableWidgetItem("Fila"));
    ui->tableWidget->setHorizontalHeaderItem(4, new QTableWidgetItem("Columna"));
    ui->tableWidget->horizontalHeader()->setStretchLastSection(true);

    while(query.next()){
        cout << "ENTRA" << endl;
        string name = query.value("name").toString().toStdString();
        string path = query.value("path").toString().toStdString();
        QString pathImage = QString(path.c_str()) + "/0.jpg";
        QImage* image = new QImage();
        ui->tableWidget->setRowCount(i);
        if(!image->load(pathImage)) cout << "ERROR LOADING" << endl;
        else{
            QTableWidgetItem * itm = new QTableWidgetItem;
            *image = image->scaledToHeight(50);
            itm->setData(Qt::DecorationRole, QPixmap::fromImage(*image));
            itm->setFlags(itm->flags() ^ Qt::ItemIsEditable);
            ui->tableWidget->setItem(i - 1, 0, itm);
            QTableWidgetItem *itm2 = new QTableWidgetItem;
            itm2->setData(Qt::DisplayRole, name.c_str());
            ui->tableWidget->setItem(i - 1, 1, itm2);
            QTableWidgetItem* itm3 = new QTableWidgetItem;
            itm3->setData(Qt::DisplayRole, query.value("caras").toString());
            ui->tableWidget->setItem(i - 1, 2, itm3);
            QTableWidgetItem* itm4 = new QTableWidgetItem;
            itm4->setData(Qt::DisplayRole, query.value("fila").toString());
            ui->tableWidget->setItem(i - 1, 3, itm4);
            QTableWidgetItem* itm5 = new QTableWidgetItem;
            itm5->setData(Qt::DisplayRole, query.value("columna").toString());
            ui->tableWidget->setItem(i - 1, 4, itm5);
        }
        i++;
    }
    ui->tableWidget->resizeColumnsToContents();
    ui->tableWidget->resizeRowsToContents();

}
Exemplo n.º 27
0
Tag::Tag(QSqlQuery& query)
{
    Id = query.value(KEY_Tag_Id).toInt();
    Type = (TagType)query.value(KEY_Tag_Type).toInt();
    Name = query.value(KEY_Tag_Name).toString();
}
Exemplo n.º 28
0
void CopyGui::readData()
{
    QSqlQuery qry;
    qry.prepare( "SELECT * FROM collections WHERE id=:collection");
    qry.bindValue(":collection", selected_id);
    if( !qry.exec() )
        qDebug() << qry.lastError();
    else
    {
        qry.next();
        ui->lblHeader->setText("<html><head/><body><p align='center'><span style='font-size:14pt; color:#ff0000;'>Copies of "+qry.value("title").toString()+"</span></p></body></html>");
    }


    queryModel = new QSqlRelationalTableModel();
    QString collection = QString::number(selected_id);
    queryModel->setTable("copy");
    queryModel->setFilter("collection_id="+collection);
    queryModel->setRelation(6,QSqlRelation("collections","id","title"));
    queryModel->setRelation(7,QSqlRelation("borrowers","id","name"));
    queryModel->setEditStrategy(QSqlTableModel::OnManualSubmit);
    queryModel->setJoinMode(QSqlRelationalTableModel::LeftJoin);
    queryModel->select();

    queryModel->setHeaderData(0, Qt::Horizontal, QObject::tr("ID"));
    queryModel->setHeaderData(1, Qt::Horizontal, QObject::tr("Barcode"));
    queryModel->setHeaderData(2, Qt::Horizontal, QObject::tr("Borrowing Status"));
    queryModel->setHeaderData(3, Qt::Horizontal, QObject::tr("Times Borrowed"));
    queryModel->setHeaderData(4, Qt::Horizontal, QObject::tr("Borrowed Date"));
    queryModel->setHeaderData(5, Qt::Horizontal, QObject::tr("Days currently borrower"));
    queryModel->setHeaderData(6, Qt::Horizontal, QObject::tr("Collection ID"));
    queryModel->setHeaderData(7, Qt::Horizontal, QObject::tr("Borrowed by"));


    //select entire row
    ui->tableView->setSelectionBehavior(QAbstractItemView::SelectRows);
    ui->tableView->setSelectionMode(QAbstractItemView::SingleSelection);

    ui->tableView->setModel(queryModel);
    ui->tableView->setSortingEnabled(true);
    //connect(ui->tableView, SIGNAL(clicked(QModelIndex)),this, SLOT(onClick(QModelIndex)));
    ui->tableView->setEditTriggers(QAbstractItemView::NoEditTriggers);
    ui->tableView->show();
}
Exemplo n.º 29
0
void Login::on_pushButton_Login_clicked()
{

    QString username = ui->lineEdit_username->text();
    QString password = ui->lineEdit_password->text();
    QSqlQuery query;
    QString employID;
    QString isTempPass;
    QString islocked;
    roleSel *roleDash = new roleSel();
    query.bindValue(":username", username);
    query.bindValue(":password", password);
    bool debug = true;

    if (debug)
    {
        if ((username == "root") & (password == "root"))
        {
            accountCreate *ACDash = new accountCreate();
            this->close();
            ACDash->show();
            ACDash->activateWindow();
            ACDash->raise();
        }
    }
    setLoginCount(username);

                //checks login if correct
                query.prepare("SELECT * FROM Account WHERE accountID = '"+username+"' and password = '******'");
                if (query.exec())
                {
                    qDebug()<<"Code has entered login check";
                    int count=0;
                    while(query.next())
                    {
                        employeeID = query.value(1).toString();
                       // qDebug()<<"I have entered this";
                        isTempPass = query.value(6).toString();
                        islocked = query.value(7).toString();
                        count++;
                        qDebug()<<"The count is: "<<count;
                     }
                     if (count==1)
                     {
                        ui->label_status->setText("Login Successful");

                        //user needs to change password because current is temporary
                        if (isTempPass == "1")
                        {
                            changePass *passDash = new changePass();
                            QObject::connect(this, SIGNAL(sendData(QString)), &*passDash, SLOT(receiveData(QString)));
                            emit sendData(employeeID);
                            passDash->setModal(true);
                            passDash->show();
                            passDash->activateWindow();
                            passDash->raise();
                        }
                        else //information is correct
                        {
                            //check if account is locked
                            if (islocked == "1")
                            {
                                QMessageBox msgbox;
                                msgbox.setText("Your Account is locked, please see a system administrator");
                                msgbox.exec();
                            }
                            //account is not locked
                            else
                            {
                                QObject::connect(this, SIGNAL(sendData(QString)), &*roleDash, SLOT(receiveData(QString)));
                                qDebug()<<"Sending data: "<<employeeID;
                                qDebug()<<"Temporary pass is: "<<isTempPass;
                                emit sendData(employeeID);
                                query.prepare("UPDATE Account SET loginCountID = '0' FROM Account WHERE accountID = '"+username+"'");
                                if(query.exec())
                                {
                                     qDebug()<<"The loginCount being reset to is : "<<loginCount;
                                     ui->label_loginCount->setText("");
                                }
                                this->hide();
                                roleDash->show();
                                roleDash->activateWindow();
                                roleDash->raise();
                            }
                        }
                      }
                        //login information is incorrect
                        if (count<1)
                        {
                            qDebug()<<"Code has entered the fail to vertify section";
                            ui->label_status->setText("username or password is incorrect");
                            //check if loginCount has been maxed
                            //if loginCount is over 6 then lock the account
                            if (loginCount >6)
                            {
                                QMessageBox msgbox;
                                msgbox.setText("You have failed to login 6 times, your account is now locked. "
                                                 "Please see the system administrator for further assistance");
                                query.prepare("UPDATE Account SET islocked = '1' FROM Account WHERE accountID = '"+username+"'");
                                query.exec();
                                msgbox.exec();

                                //reset count and label
                                //loginCount = 1;
                                query.prepare("UPDATE Account SET loginCountID = '0' FROM Account WHERE accountID = '"+username+"'");
                                if(query.exec())
                                {
                                     qDebug()<<"The loginCount being reset to is : "<<loginCount;
                                     ui->label_loginCount->setText("");
                                }

                            }
                            //or just increase loginCount and display warning
                            else
                            {
                                //increase login count for failed login
                                loginCount++;
                                qDebug()<<(QString("Currently trying to insert: %1 into loginCountID").arg(loginCount));
                                qDebug()<<"The username's loginCountID being changed is: "<<username;
                                query.prepare("UPDATE Account SET loginCountID = :loginCountID FROM Account WHERE accountID = '"+username+"'");
                                query.bindValue(":loginCountID", loginCount);
                                query.exec();
                                qDebug()<<(loginCount)<<"times has been tried";
                                ui->label_loginCount->setText(QString("You have tried to login: %1 times").arg(loginCount));
                            }

                        }
                    }


}
Exemplo n.º 30
0
// ************************************************************
// doExport (20.11.08)
// logFile, pathDateiname,??
// ************************************************************
void wadif::doExport(QString log, QString fpath, int lpref)
{
 QString p, dfeld;
 int col, idx;
 QString Call, Name, Cept, val, v, id;
    state = 0;
    p = fpath+log+".adi";
    QFile file(p);
    if (!file.open(QIODevice::WriteOnly | QIODevice::Text)) {
         state = 2;
        return;
    }
    QTextStream out(&file);
    n = lpref;                                        // dummy
    QSqlQuery query;
    qy = "SELECT id,cept,"+tmp+etmp;                  // QUERY bauen SELECT + header_felder
    qy += " FROM "+log+"om LEFT JOIN ("+log+"qsl,"+log+") ON (omid=oid AND qsoid=id)";
    qy += " ORDER BY day";
    //qDebug() << qy;
    
    query.exec(qy);
    n = query.size();                                 // Tabellen_größe
    col = query.record().count();                     // Anzahl Tabellen_felder
    
    p = "** ADIF V2.0 file exportet by QtLog V1.5.07 ** LOG:"+log+" - logs:"+s.setNum(n)+"  date:";
    QDate d = QDate::currentDate();                   // erzeuge das Datum von heute
    p += s.setNum(d.year());
    p += "-";
    p += s.setNum(d.month());
    p += "-";
    p += s.setNum(d.day());
    p += "\n";
    p += "<PROGRAMID:5>QtLog";
    p += "\n";
    p += "<eoh>\n";
    out << p;
    count = 0;
    
    while(query.next() ) {                           // -- data_table_loop --
      idx = 0;
      p = "";
      while( idx != col ) {                          // -- data_header_loop --
       n = 0;                                        // ----------------------
       dfeld = query.record().fieldName(idx);        // dbfeld_name pos(col)
       val = query.value(idx).toString();            // Feld_Data_value(col)
       if(dfeld.compare("id") == 0) {                // ist ID
          id = val;
       }
       else 
        if(dfeld.compare("cept") == 0) { 
           Cept = val;                               // Cept
        }
       else
        if(dfeld.compare("rufz") == 0) {             // Call
          Call = val;
          if(Cept.count() != 0) {
              val = Cept+Call;                       // bilde cept/Call
              p += "<CALL:"+v.setNum(val.count())+">"+val;
           }
           else 
             p += "<CALL:"+v.setNum(Call.count())+">"+Call;
        }
       else 
        if(dfeld.compare("day") == 0) {              // QSO_datum
            val.remove(QChar('-'), Qt::CaseInsensitive);
            p += " <"+getAdifName(dfeld)+":"+v.setNum(val.count())+":d>"+val;
        }
       else 
        if((dfeld.compare("qslrd") == 0) || (dfeld.compare("qslsd") == 0)) {   // Datum QSL_erhalten ..
           val.remove(QChar('-'), Qt::CaseInsensitive);
           if(val.count() != 0) 
             p += " <"+getAdifName(dfeld)+":"+v.setNum(val.count())+":d>"+val;
        }
       else 
        if(dfeld.compare("btime") == 0) {             // QSO_Start
           val.remove(QChar(':'), Qt::CaseInsensitive);
           p += " <"+getAdifName(dfeld)+":"+v.setNum(val.count())+">"+val;
        }
       else
        if(dfeld.compare("etime") == 0) {             // QSO_Ende
           val.remove(QChar(':'), Qt::CaseInsensitive);
           p += " <"+getAdifName(dfeld)+":"+v.setNum(val.count())+">"+val;
        }
       else
        if(dfeld.compare("band") == 0) {
           val = getAdifBand(val);                   // Band getAdifBand(QString sysband)
           p += " <"+getAdifName(dfeld)+":"+v.setNum(val.count())+">"+val;
        }
        else
         if(dfeld.compare("ntext") == 0) {
           if(val.count() != 0) {
             val = val.simplified();                 // entferne '\n', '\v', '\f', '\r', and ' 
             p += " <"+getAdifName(dfeld)+":"+v.setNum(val.count())+">"+val; 
           }
        }
       else
         if(dfeld.compare("ktext") == 0) {
           if(val.count() != 0) {
             val = val.simplified();                 // entferne '\n', '\v', '\f', '\r', and ' '.
             p += " <"+getAdifName(dfeld)+":"+v.setNum(val.count())+">"+val; 
           }
        }
        else
         if(dfeld.compare("dxcc") == 0) {
            if(lpref) {                             // dxcc als Adif_Nr exporieren
               if(val.count() != 0) {               // nur wenn dxcc vorhanden
                 QSqlQuery query;
                 qy = "SELECT adif FROM tla WHERE ldxcc='"+val+"'";
                 query.exec(qy);
                 query.next(); 
                 val = query.value(0).toString(); 
               }
            }
            p += " <"+getAdifName(dfeld)+":"+v.setNum(val.count())+">"+val;
        }
       else
        if((dfeld.compare("lotqslrd") == 0) || (dfeld.compare("lotqslsd") == 0)) {
            val.remove(QChar('-'), Qt::CaseInsensitive);
            if(val.count() != 0)
              p += " <"+getAdifName(dfeld)+":"+v.setNum(val.count())+":d>"+val;
        }
       else {
         if(val.count() != 0) {                      // Leer_felder nicht übernehmen
           p += " <"+getAdifName(dfeld)+":"+v.setNum(val.count())+">"+val; 
         }
       }
       idx++;                                        // nächstes Feld
     }
//--
    
    qy = "SELECT awtype,awkenner FROM "+log+"awd WHERE qid="+id;
    QSqlQuery query(qy);
    n = query.size();
    while(query.next()) {
       n = 0;
       dfeld = query.value(n++).toString();         // zB DLD
       val = query.value(n++).toString();           // zB E33
       p += " <"+getAdifCustom(dfeld)+":"+v.setNum(val.count())+">"+val; 
    }                                               // while daten_satz_felder
    p += " <eor>\n";                                // Datensatz fertig 
    out << p;                                       // Datensatz in Datei übernehmen
    count++;
  }                                                 // while log_tabelle
  out << "<EOF>\n";
  file.close();
}