Example #1
0
PhoneReg::PhoneReg(const QString& userAgent,
                   const QString& cc, const QString& number, const QString& method,
                   const QString& smscode, const QString& password,
                   const QString &mcc, const QString &mnc, QObject *parent) :
    QObject(parent)
{
    this->cc = cc;
    this->number = number;
    this->method = method;
    this->smscode = smscode;
    this->smscode = this->smscode.replace("-", "");
    this->mcc = mcc.rightJustified(3, '0');
    this->mnc = mnc.rightJustified(3, '0');
    this->userAgent = userAgent;

    // Generate a new id

    QtMD5Digest digest;
    digest.reset();

    if (password.isEmpty()) {
        digest.update(QUuid::createUuid().toByteArray());
    }
    else {
        digest.update(QString(number + "mitakuuluu" + password).toUtf8());
    }

    QByteArray bytes = digest.digest();

    this->id = QString::fromLatin1(bytes.toHex().constData()).left(20);
}
Example #2
0
PhoneReg::PhoneReg(const QString& cc, const QString& number, const QString& method,
                   const QString& smscode, const QString& password,
                   const QString &mcc, const QString &mnc, QObject *parent) :
    QObject(parent)
{
    this->cc = cc;
    this->number = number;
    this->method = method;
    this->smscode = smscode;
    this->smscode = this->smscode.replace("-", "");
    this->mcc = mcc.rightJustified(3, '0');
    this->mnc = mnc.rightJustified(3, '0');

    // Generate a new id

    QtMD5Digest digest;
    digest.reset();

    if (password.isEmpty()) {
        digest.update(QUuid::createUuid().toByteArray());
    }
    else {
        digest.update(QString(number + "mitakuuluu" + password).toUtf8());
    }

    QByteArray bytes = digest.digest();

    this->id = QString::fromLatin1(bytes.toHex().constData()).left(20);

    QString locale = QLocale::system().name();
    lg = locale.split("_").first();
    lc = locale.split("_").length() > 1 ? locale.split("_").last().toLower() : "zz";
}
Example #3
0
void Widget::rightJustifiedFunction()
{
    //! [49]
    QString s = "apple";
    QString t = s.rightJustified(8, '.');    // t == "...apple"
    //! [49]

    //! [50]
    QString str = "Pineapple";
    str = str.rightJustified(5, '.', true);    // str == "Pinea"
    //! [50]
}
Example #4
0
int Sequence::compareValues(QString value1, QString value2)
{
	if(value1==value2)
		return(0);
	else
	{
		char ops[2]={'\0','\0'};
		unsigned i, idx, count;
		QString *vet_values[2]={&value1, &value2}, aux_value;

		if(value1.size() < value2.size())
			value1=value1.rightJustified(value1.size() + (value2.size()-value1.size()),'0');
		else if(value1.size() > value2.size())
			value2=value2.rightJustified(value2.size() + (value1.size()-value2.size()),'0');

		for(i=0; i < 2; i++)
		{
			//Gets the value signal
			ops[i]=vet_values[i]->at(0).toLatin1();

			//Case the value doesn't has a + it will be append
			if(ops[i]!='-' && ops[i]!='+') ops[i]='+';

			idx=0;
			count=vet_values[i]->size();
			while(idx < count)
			{
				if(vet_values[i]->at(idx)!='+' &&
					 vet_values[i]->at(idx)!='-')
					aux_value+=vet_values[i]->at(idx);
				else
					aux_value+='0';

				idx++;
			}
			(*vet_values[i])=aux_value;
			aux_value=QString();
		}

		if(ops[0]==ops[1] && value1==value2)
			return(0);
		else if((ops[0]=='-' && ops[1]=='-' && value1 > value2) ||
						(ops[0]=='+' && ops[1]=='+' && value1 < value2) ||
						(ops[0]=='-' && ops[1]=='+'))
			return(-1);
		else
			return(1);
	}
}
Example #5
0
QString formatWord(mem_word word, int base)
{
    int width = 0;
    switch (base)
    {
    case 10: width = WORD_WIDTH_10; break;
    case 16: width = WORD_WIDTH_16; break;
    default: width = WORD_WIDTH_DEFAULT; break;
    }
    QString str = QString::number(word, base);
    str.remove(0, str.length() - width); // Negative hex number proceeded by 0xffffffff

    if (str[0] == '-')                   // decimal starting with a negative sign
        return str.rightJustified(width, ' ').replace(QRegExp(" "), "&nbsp;"); // Don't zero pad
    else
        return str.rightJustified(width, '0');
}
Example #6
0
/***************************************************************************
 * writeXPMpalette
 ***************************************************************************/
void CNDSbgr555::writeXPMpalette(bgr555 * palette, QStringList *xpm)
{
	int	i;
	QString	s;
	QString	l;

	for (i=0; i<16; i++)
	{
		l = QString('a' + i) + " c #";
		s.setNum(palette[i].R, 16);
		l += s.rightJustified(2, '0');
		s.setNum(palette[i].G, 16);
		l += s.rightJustified(2, '0');
		s.setNum(palette[i].B, 16);
		l += s.rightJustified(2, '0');
		xpm->append(l);
	}
	
}
Example #7
0
/***************************************************************************
 * writeXPMpalette
 ***************************************************************************/
void CNDSbgr555::writeXPMpalette(bgr555 * palette, QString *xpm)
{
	int	i;
	QString	s;

	for (i=0; i<16; i++)
	{
		
		*xpm += "\"" + QString('a' + i) + " c #";
		s.setNum(palette[i].R, 16);
		*xpm += s.rightJustified(2, '0');
		s.setNum(palette[i].G, 16);
		*xpm += s.rightJustified(2, '0');
		s.setNum(palette[i].B, 16);
		*xpm += s.rightJustified(2, '0');
		*xpm += "\",\n";
	}
	*xpm += "/* pixels */\n\"";
}
Example #8
0
QString SxVersionedFile::makeVersionName( QDir *history, uint version ) const
{
	QString revName;
	if( version == 0 )
		revName = "head.rev";
	else
	{
		revName = QString::number( version ) + ".rev";
		revName = revName.rightJustified(8,'0');
	}
	return history->absolutePath() + "/" + revName;
}
Example #9
0
	void PatternConverter::format(QString &rFormat, const LoggingEvent &rLoggingEvent) const
	{
		const QLatin1Char space(' ');
		QString s = convert(rLoggingEvent);
		
		if (s.length() > mFormattingInfo.mMaxLength)
			rFormat += s.left(mFormattingInfo.mMaxLength);
		else if (mFormattingInfo.mLeftAligned)
			rFormat += s.leftJustified(mFormattingInfo.mMinLength, space, false);
		else
			rFormat += s.rightJustified(mFormattingInfo.mMinLength, space, false);
	}
Example #10
0
void MultiMolDialog::createMoleculeList(chemkit::MoleculeFile *file)
{
    ui->molList->clear();
    ui->selectAllBox->setCheckState(Qt::Unchecked);

    for (int i = 0; i < int(file->moleculeCount()); i++)
    {
        QString name = QString::number(i + 1);
        QListWidgetItem *molItem = new QListWidgetItem(name.rightJustified(4, ' '), ui->molList);
        molItem->setFlags(Qt::ItemIsEnabled | Qt::ItemIsSelectable);
        ui->molList->addItem(molItem);
    }
}
Example #11
0
void NYView::guiDrawSetLineNumber(int y, int n, int h)
{
    fakeLine = n <= 0;
    QString num;

    if(!fakeLine && h == 0) {
        num = QString::number(n);
    }

    num = num.rightJustified(marginLeft - 1, ' ') + ' ';
    wattron(editor, attribYellow);
    mvwaddstr(editor, y, 0, num.toLocal8Bit().constData());
    wattroff(editor, attribYellow);
}
Example #12
0
QString Q19Writer::import ( BlFixed f, int longitud )
{

	f.setPrecision ( 2 );
	QString res = QString::number ( f.value );
	if ( f.value < 0 )
	{
		throw _ ( "Datos incorrectos" ) +"\n" + _ ( "Importe negativo (%1) ! " ).arg ( f.toQString() );
	}
	if ( res.length() >longitud )
	{
		throw _ ( "Datos incorrectos" ) +"\n" + _ ( "Importe excesivo (%1) !. El limite son %2 digitos, incluyendo los 2 decimales " ).arg ( f.toQString() ).arg ( abs ( longitud ) );
	}
	return res.rightJustified ( longitud,'0',true );
}
Example #13
0
void IRPrinter::addJustifiedNr(int pos)
{
    if (positionSize == Stmt::InvalidId) {
        *out << pos << ": ";
    } else {
        QString posStr;
        if (pos != Stmt::InvalidId)
            posStr = QString::number(pos);
        *out << posStr.rightJustified(positionSize);
        if (pos == Stmt::InvalidId)
            *out << "  ";
        else
            *out << ": ";
    }
}
//--------------------------------------------------------------------------------------------------
///
//--------------------------------------------------------------------------------------------------
QString RifEclipseDataTableFormatter::formatColumn(const QString str, size_t columnIndex) const
{
    const RifEclipseOutputTableColumn& column = m_columns[columnIndex];
    
    if (column.alignment == LEFT)
    {
        int colSpacing = (columnIndex == m_columns.size() - 1) ? 0 : m_colSpacing;
        return str.leftJustified(column.width + colSpacing, ' ');
    }
    else
    {
        int colSpacing = (columnIndex == 0) ? 0 : m_colSpacing;
        return str.rightJustified(column.width + colSpacing, ' ');
    }
}
Example #15
0
bool rigControl::getRadioList(QComboBox *cb)
{
    int i;
    if(capsList.count()==0) return false;
    QStringList sl;
    for (i=0;i<capsList.count();i++)
    {
        QString t;
        t= QString::number(capsList.at(i)->rig_model);
        t=t.rightJustified(5,' ')+" ";
        t+= capsList.at(i)->mfg_name;
        t+=",";
        t+=capsList.at(i)->model_name;
        sl << t;
    }
    cb->addItems(sl);
    return true;
}
Example #16
0
/**
\param out
\param idcobro
\return
**/
void Q19Writer::cabeceraOrdenante ( QTextStream &out, QString sufijo , BlDbRecordSet *curbanco, QDate fechaCargo )
{
	BL_FUNC_DEBUG

	/// GENERAMOS LA CABECERA ORDENANTE
	/// REGISTRO DEL ORDENANTE
	/// Registro en Euros. Longitud: 2
	out << ( "53" )  // pag. 18 diu 53 , pag. 25 diu 03
	/// Registro de codigo de dato: 80. Longitud: 2
	<< ( "80" )

	/// Codigo de ordenante (NIF + Sufijo alineado a la derecha y rellenado con ceros) Longitud: 12
	<< comprova ( nifOrdenante(),9, _("El CIF del ordenante") ,'0' )
	<< sufijo.rightJustified ( 3,'0',true )

	/// Fecha de emision del archivo
	<< ( QDate::currentDate().toString ( "ddMMyy" ) )
	/// Fecha de cargo
	<< ( fechaCargo.toString ( "ddMMyy" ) )
	/// Nombre del cliente Ordenante Longitud: 40
	<< nombreOrdenante().leftJustified ( 40,' ',true )
	/// Entidad Receptora del fichero Longitud: 4
	<< comprova ( curbanco->value( "codentidadbanco" ),-4,_ ( "Su entidad bancaria" ),'0' )
	/// Oficina Receptora del fichero Longitud: 4
	<< comprova ( curbanco->value( "codagenciabanco" ),-4,_ ( "Su oficina bancaria" ),'0' )
	/// DC Receptora del fichero Longitud: 2
	<< comprova ( curbanco->value( "dcbanco" ) ,-2,
	              _ ( "Los digitos de control de su cuenta bancaria" ),'0' )
	/// Oficina Receptora del fichero Longitud: 10
	<< comprova ( curbanco->value( "numcuentabanco" ), -10,
	              _ ( "Su numero de cuenta bancaria" ) ,'0' )
	/// Espacio libre Longitud: 8
	<<  QString ( 8, ' ' )
	/// Procedimiento de realizacion del adeudo (01 o 02) Longitud: 2
	<< "01"
	/// Espacio libre Longitud: 10
	<< QString ( 10, ' ' )
	/// Espacio libre Longitud: 40
	<< QString ( 40, ' ' )
	/// Espacio libre Longitud: 14
	<< QString ( 14, ' ' )
	<< "\x0a";
}
Example #17
0
void MainWindow::on_pushButton_6_clicked()
{

    if (cacheSize > 0 && cacheLine > 0)
    {
        if (existCache != true)
        {
            QStringList list;
            this->ui->tableWidget->setColumnCount(2 + cacheLine);
            if (cacheLine == 2)
            {
                list << "Tag" << "00" << "01" << "DirtyBit";
            }
            else if (cacheLine == 4)
            {
                list << "Tag" << "00" << "01" << "10" << "11" << "DirtyBit";
            }
            else if (cacheLine == 8)
            {
                list << "Tag";
                QString num;
                for (int i =0; i < 8; i ++)
                {
                    num = QString::number(i, 2);
                    num = num.rightJustified(3,'0');
                    list << (num);
                }
                list << "DirtyBit";
            }
            this->ui->tableWidget->setHorizontalHeaderLabels(list);
            this->ui->tableWidget->resizeColumnsToContents();
            this->ui->tableWidget->setRowCount(cacheSize/cacheLine );
        }
        existCache = true;
        emit cacheInit(cacheSize, cacheLine);
    }
    else
    {
        msgRcv("Error: Cache Size/Line not specified");
    }
}
Example #18
0
void Q19Writer::totalPresentador ( QTextStream &out,  QString sufijo , BlDbRecordSet *curbanco,
                                   BlFixed importes, int rebuts, int registros , int ordenants )
{
	BL_FUNC_DEBUG
	/// CABECERA TOTAL ORDENANTE
	/// Registro en Euros. Longitud: 2
	out << "59" //pag. 24 diu 59,pag. 29 diu 09
	/// Registro de codigo de dato: 80. Longitud: 2
	<<"80"
	/// Codigo de presentador (NIF + Sufijo alineado a la derecha y rellenado con ceros) Longitud: 12
	<< comprova ( nifPresentador(),9,_ ( "El CIF del presentador (propiedades de Empresa)" ),'0' )
	<< sufijo.rightJustified ( 3,'0',true )

	/// Espacio libre Longitud: 12
	/// Espacio libre Longitud: 40

	<< QString ( 12+40, ' ' )
	/// Num ordenants
	<< QString::number ( ordenants ).rightJustified ( 4,'0',true )
	/// Espacio libre Longitud: 16
	<< QString ( 16, ' ' )

	/// Suma de Importes del Ordenante Longitud: 10
	<< import ( importes,10 )

	/// Espacio libre Longitud: 6
	<< QString ( 6, ' ' )

	/// Numero de domiciliaciones del ordenante : 10
	<< QString::number ( rebuts ).rightJustified ( 10, '0',true )

	/// Numero total registros del ordenante : 10
	<< QString::number ( registros ).rightJustified ( 10, '0',true )

	/// Espacio libre Longitud: 20
	/// Espacio libre Longitud: 18
	<< QString ( 20+18, ' ' )
	<<"\x0a";
	

}
void AditionalFileDialog::set_permissions(const QString & permission)
{
    QString perm = permission.rightJustified(4, '0');
    if(perm.count() > 4)
        perm = perm.right(4);
    qint8 special = perm.at(0).toLatin1();
    qint8 user = perm.at(1).toLatin1();
    qint8 group = perm.at(2).toLatin1();
    qint8 others = perm.at(3).toLatin1();
    ui->c_uid->setChecked(special & 0x04);
    ui->c_gid->setChecked(special & 0x02);
    ui->c_sticky->setChecked(special & 0x01);
    ui->c_u_r->setChecked(user & 0x04);
    ui->c_u_w->setChecked(user & 0x02);
    ui->c_u_x->setChecked(user & 0x01);
    ui->c_g_r->setChecked(group & 0x04);
    ui->c_g_w->setChecked(group & 0x02);
    ui->c_g_x->setChecked(group & 0x01);
    ui->c_o_r->setChecked(others & 0x04);
    ui->c_o_w->setChecked(others & 0x02);
    ui->c_o_x->setChecked(others & 0x01);
}
Example #20
0
void MasternodeManager::updateNodeList()
{
    TRY_LOCK(cs_masternodes, lockMasternodes);
    if(!lockMasternodes)
        return;

    ui->countLabel->setText("Updating...");
    ui->tableWidget->clearContents();
    ui->tableWidget->setRowCount(0);
    std::vector<CMasternode> vMasternodes = mnodeman.GetFullMasternodeVector();
    BOOST_FOREACH(CMasternode& mn, vMasternodes)
    {
        int mnRow = 0;
        ui->tableWidget->insertRow(0);

        // populate list
        // Address, Rank, Active, Active Seconds, Last Seen, Pub Key
        QTableWidgetItem *activeItem = new QTableWidgetItem(QString::number(mn.IsEnabled()));
        QTableWidgetItem *addressItem = new QTableWidgetItem(QString::fromStdString(mn.addr.ToString()));
        QString Rank = QString::number(mnodeman.GetMasternodeRank(mn.vin, pindexBest->nHeight));
        QTableWidgetItem *rankItem = new QTableWidgetItem(Rank.rightJustified(2, '0', false));
        QTableWidgetItem *activeSecondsItem = new QTableWidgetItem(seconds_to_DHMS((qint64)(mn.lastTimeSeen - mn.sigTime)));
        QTableWidgetItem *lastSeenItem = new QTableWidgetItem(QString::fromStdString(DateTimeStrFormat(mn.lastTimeSeen)));

        CScript pubkey;
        pubkey =GetScriptForDestination(mn.pubkey.GetID());
        CTxDestination address1;
        ExtractDestination(pubkey, address1);
        CTransfercoinAddress address2(address1);
        QTableWidgetItem *pubkeyItem = new QTableWidgetItem(QString::fromStdString(address2.ToString()));

        ui->tableWidget->setItem(mnRow, 0, addressItem);
        ui->tableWidget->setItem(mnRow, 1, rankItem);
        ui->tableWidget->setItem(mnRow, 2, activeItem);
        ui->tableWidget->setItem(mnRow, 3, activeSecondsItem);
        ui->tableWidget->setItem(mnRow, 4, lastSeenItem);
        ui->tableWidget->setItem(mnRow, 5, pubkeyItem);
    }
Example #21
0
void KSnapshotObject::autoincFilename()
{
    // Extract the filename from the path
    QFileInfo info(file_path_);

    QString name= info.fileName();

    // If the name contains a number then increment it
    QRegExp numSearch( "(^|[^\\d])(\\d+)" ); // we want to match as far left as possible, and when the number is at the start of the name

    // Does it have a number?
    int start = numSearch.lastIndexIn( name );
    if (start != -1) {
        // It has a number, increment it
        start = numSearch.pos( 2 ); // we are only interested in the second group
        QString numAsStr = numSearch.capturedTexts()[ 2 ];
        QString number = QString::number( numAsStr.toInt() + 1 );
        number = number.rightJustified( numAsStr.length(), '0' );
        name.replace( start, numAsStr.length(), number );
    }
    else {
        // no number
        start = name.lastIndexOf('.');
        if (start != -1) {
            // has a . somewhere, e.g. it has an extension
            name.insert(start, '1');
        }
        else {
            // no extension, just tack it on to the end
            name += '1';
        }
    }

    //Rebuild the path
    QString newUrl = info.absolutePath() + '/' + name;
    changeUrl( newUrl );
}
Example #22
0
/**
\param out stream de sortida, que ja ha de saber traduir la codificacio a q19
\param sufijo:   la norma 19 el descriu aixi
   CLIENTE ORDENANTE:
se identifica por un codigo de dos partes: Numero de Identificacion Fiscal (
N.I.F.) y Sufijo (Numero de tres cifras que identifica los diferentes tipos de
facturacion del cliente y/o los diferentes centros emisores de soportes o
ficheros de facturacion).
El NIF debera ser el mismo y el Sufijo distinto cuando la facturacion sea
repartida entre varias Entidades Receptoras, asignando un Sufijo distinto a
cada Entidad.
\param curbanco cursor sobre el registre de banc que rebra els ingressos.
\return
**/
void Q19Writer::cabeceraPresentador ( QTextStream &out, QString sufijo , BlDbRecordSet *curbanco )
{
	BL_FUNC_DEBUG

	/// CABECERA PRESENTADOR
	/// Generamos la cabecera presentador


	/// Registro en Euros. Longitud: 2
	out << ( "51" )  // pag. 25 diu 01, pag. 17 diu 51
	/// Registro de codigo de dato: 80. Longitud: 2
	<< ( "80" )
	/// Codigo de presentador (NIF + Sufijo alineado a la derecha y rellenado con ceros) Longitud: 12
	<< comprova ( nifPresentador(),9,_ ( "El CIF del presentador (propiedades de Empresa)" ),'0' )
	<< sufijo.rightJustified ( 3,'0',true )
	/// Fecha de emision del archivo
	<< ( QDate::currentDate().toString ( "ddMMyy" ) )
	/// Espacio libre Longitud: 6
	<< QString ( 6,' ' )
	/// Nombre del cliente Presentador Longitud: 40
	<< nombrePresentador().leftJustified ( 40,' ',true )
	/// Espacio libre Longitud: 20
	<< QString ( 20,' ' )
	/// Entidad Receptora del fichero Longitud: 4
	<< comprova ( curbanco->value( "codentidadbanco" ),-4,_ ( "Su entidad bancaria" ),'0' )
	/// Oficina Receptora del fichero Longitud: 4
	<< comprova ( curbanco->value( "codagenciabanco" ),-4,_ ( "Su oficina bancaria" ),'0' )
	/// Espacio libre Longitud: 12
	<<  QString ( 12, ' ' )
	/// Espacio libre Longitud: 40
	<< QString ( 40, ' ' )
	/// Espacio libre Longitud: 14
	<< QString ( 14, ' ' )
	/// Hi ha d'haver salts de linia o no?. Un fitxer d'exemple que tinc en porta.
	<< "\x0a";
	
}
Example #23
0
QString CurrencyAdapter::formatAmount(quint64 _amount) const {
  QString result = QString::number(_amount);
  if (result.length() < getNumberOfDecimalPlaces() + 1) {
    result = result.rightJustified(getNumberOfDecimalPlaces() + 1, '0');
  }

  quint32 dot_pos = result.length() - getNumberOfDecimalPlaces();
  for (quint32 pos = result.length() - 1; pos > dot_pos + 1; --pos) {
    if (result[pos] == '0') {
      result.remove(pos, 1);
    } else {
      break;
    }
  }

  result.insert(dot_pos, ".");
  for (qint32 pos = dot_pos - 3; pos > 0; pos -= 3) {
    if (result[pos - 1].isDigit()) {
      result.insert(pos, ',');
    }
  }

  return result;
}
Example #24
0
void loop::changeLabel(QPoint *cP) {
    QString a = "X:";
    a = a.rightJustified(5, ' ');
    QString b;
    b.setNum(cP->x());
    b = b.rightJustified(6, ' ');
    a += b;
    b = "Y:";
    b = b.rightJustified(10, ' ');
    a += b;
    b.setNum(cP->y());
    b = b.rightJustified(6, ' ');
    a += b;
    b = "Zoom:";
    b = b.rightJustified(13, ' ');
    a += b;
    b = "x";
    b = b.rightJustified(6, ' ');
    a += b;
    b.setNum(curSc);
    a += b;
    pointCoordLab->setText(a);
    pointCoordLab->show();
}
QString JasonQt_QML::Tool::stringRightJustified(const QString &string, const int &width, const QString &fill)
{
    return string.rightJustified(width, fill.at(0));
}
Example #26
0
QString AgendaView::renderHTML()
{
    bool CO2_equivalent = settings->toolBarStack()->isCO2EquivalentChecked();

    QString html; MTTextStream out(&html);

    if (settings->mainWindowSettings().serviceCompanyInformationVisible()) {
        HTMLTable *service_company = writeServiceCompany();
        out << service_company->html();
        delete service_company;
        out << "<br>";
    }

    QMultiMap<QString, QList<QVariant> > next_inspections_map;

    MultiMapOfVariantMaps customers(Customer("").mapAll("id", "company"));

    MTRecord circuits_record("circuits", "id", "", MTDictionary("disused", "0"));
    if (!settings->toolBarStack()->isFilterEmpty()) {
        circuits_record.addFilter(settings->toolBarStack()->filterColumn(), settings->toolBarStack()->filterKeyword());
    }
    circuits_record.addJoin("LEFT JOIN (SELECT customer, circuit, MAX(date) AS date FROM inspections"
                            " WHERE outside_interval = 0 GROUP BY customer, circuit) AS ins"
                            " ON ins.customer = circuits.parent AND ins.circuit = circuits.id");
    circuits_record.addJoin("LEFT JOIN (SELECT i.customer, i.circuit, i.date, i.nominal, i.refr_add_am FROM inspections AS i"
                            " LEFT JOIN inspections AS j ON i.customer = j.customer AND i.circuit = j.circuit"
                            " AND i.date < j.date WHERE j.date IS NULL) AS all_ins"
                            " ON all_ins.customer = circuits.parent AND all_ins.circuit = circuits.id");
    MTSqlQuery circuits = circuits_record.select("circuits.parent, circuits.id, circuits.name, circuits.operation, circuits.refrigerant, "
                                                 + circuitRefrigerantAmountQuery()
                                                 + ", circuits.hermetic, circuits.leak_detector, circuits.inspection_interval,"
                                                 " COALESCE(ins.date, circuits.commissioning) AS last_regular_inspection,"
                                                 " COALESCE(all_ins.date, circuits.commissioning) AS last_inspection,"
                                                 " all_ins.nominal, all_ins.refr_add_am");
    circuits.setForwardOnly(true);
    circuits.exec();
    while (circuits.next()) {
        QString refrigerant = circuits.stringValue("refrigerant");
        double refrigerant_amount = circuits.doubleValue("refrigerant_amount");
        int inspection_interval = Warnings::circuitInspectionInterval(refrigerant, refrigerant_amount, CO2_equivalent,
                                                                      circuits.intValue("hermetic"),
                                                                      circuits.intValue("leak_detector"),
                                                                      circuits.intValue("inspection_interval"));
        if (inspection_interval) {
            QString last_regular_inspection_date = circuits.stringValue("last_regular_inspection");
            if (last_regular_inspection_date.isEmpty())
                continue;
            QString next_regular_inspection_date = QDate::fromString(last_regular_inspection_date.split("-").first(), DATE_FORMAT)
                    .addDays(inspection_interval).toString(DATE_FORMAT);
            QString last_inspection_date = circuits.stringValue("last_inspection");
            if (!last_inspection_date.isEmpty()) {
                QString next_inspection_date = QDate::fromString(last_inspection_date.split("-").first(), DATE_FORMAT)
                        .addDays(30).toString(DATE_FORMAT);
                if (next_inspection_date < next_regular_inspection_date &&
                        circuits.intValue("nominal") == 0 && circuits.doubleValue("refr_add_am") > 0.0)
                    next_inspections_map.insert(next_inspection_date,
                                                QList<QVariant>()
                                                    << circuits.stringValue("parent")
                                                    << circuits.stringValue("id")
                                                    << circuits.stringValue("name")
                                                    << circuits.stringValue("operation")
                                                    << refrigerant
                                                    << refrigerant_amount
                                                    << last_inspection_date
                                                    << true);
            }
            next_inspections_map.insert(next_regular_inspection_date,
                                        QList<QVariant>()
                                            << circuits.stringValue("parent")
                                            << circuits.stringValue("id")
                                            << circuits.stringValue("name")
                                            << circuits.stringValue("operation")
                                            << refrigerant
                                            << refrigerant_amount
                                            << last_regular_inspection_date
                                            << false);
        }
    }

    out << "<table cellspacing=\"0\" cellpadding=\"4\" style=\"width:100%;\"><tr>";
    out << "<th colspan=\"7\" style=\"font-size: medium;\">" << tr("Agenda") << "</th></tr>";
    out << "<tr><th>" << tr("Next inspection") << "</th><th>" << tr("Customer") << "</th>";
    out << "<th>" << tr("Circuit") << "</th><th>" << QApplication::translate("Circuit", "Place of operation") << "</th>";
    out << "<th>" << QApplication::translate("Circuit", "Refrigerant") << "</th>";
    out << "<th>" << replaceUnsupportedCharacters(QApplication::translate("MainWindow", "CO\342\202\202 equivalent")) << "</th>";
    out << "<th>" << tr("Last inspection") << "</th></tr>";

    QMapIterator<QString, QList<QVariant> > i(next_inspections_map);
    while (i.hasNext()) { i.next();
        QString customer = i.value().value(0).toString();
        QString circuit = i.value().value(1).toString();
        QString circuit_name = i.value().value(2).toString();
        QString operation = i.value().value(3).toString();
        QString refrigerant = i.value().value(4).toString();
        double refrigerant_amount = i.value().value(5).toDouble();
        QString last_inspection_date = i.value().value(6).toString();
        bool reinspection = i.value().value(7).toBool();
        int days_to = QDate::currentDate().daysTo(QDate::fromString(i.key(), DATE_FORMAT));
        QString next_inspection;
        switch (days_to) {
            case -1: next_inspection = tr("Yesterday"); break;
            case 0: next_inspection = tr("Today"); break;
            case 1: next_inspection = tr("Tomorrow"); break;
            default: next_inspection = settings->mainWindowSettings().formatDate(i.key()); break;
        }
        QString colour;
        if (days_to < 0) colour = "tomato";
        else if (days_to < 31) colour = "yellow";
        out << "<tr><td class=\"" << colour << "\">";
        if (reinspection)
            out << "<i>";
        out << next_inspection;
        if (reinspection)
            out << "*</i>";
        out << "</td><td class=\"" << colour << "\"><a href=\"customer:" << customer << "\">";
        out << formatCompanyID(customer) << " (" << escapeString(customers.value(customer).value("company").toString()) << ")</a></td>";
        out << "<td class=\"" << colour << "\"><a href=\"customer:" << customer << "/circuit:" << circuit << "\">";
        out << circuit.rightJustified(5, '0');
        if (!circuit_name.isEmpty()) { out << " (" << escapeString(circuit_name) << ")"; }
        out << "</a></td>";
        out << "<td class=\"" << colour << "\">" << escapeString(operation) << "</td>";
        out << "<td class=\"" << colour << "\">" << refrigerant_amount << "&nbsp;" << QApplication::translate("Units", "kg")
            << " " << escapeString(refrigerant) << "</td>";
        out << "<td class=\"" << colour << "\">" << CO2Equivalent(refrigerant, refrigerant_amount)
            << "&nbsp;" << QApplication::translate("Units", "t") << "</td>";
        out << "<td class=\"" << colour << "\">";
        if (last_inspection_date.contains("-"))
            out << "<a href=\"customer:" << customer << "/circuit:" << circuit << "/inspection:"
                << last_inspection_date << "\">" << settings->mainWindowSettings().formatDateTime(last_inspection_date) << "</a>";
        else
            out << settings->mainWindowSettings().formatDate(last_inspection_date);
        out << "</td></tr>";
    }
    out << "</table>";

    return viewTemplate("agenda")
            .arg(settings->isPrinterFriendlyVersionChecked() ? "/*" : "")
            .arg(settings->isPrinterFriendlyVersionChecked() ? "*/" : "")
            .arg(html);
}
Example #27
0
bool RemSection::fixOptionForQChem(QString& name, QString& value) {
   //qDebug() << "Fixing option for QChem" << name << "=" << value;
   bool shouldPrint(true);
   bool isInt;
   Option opt;
   OptionDatabase& db = OptionDatabase::instance();
   bool inDatabase(db.get(name, opt));

   // Skip internal QUI options
   if (name.startsWith("qui_",Qt::CaseInsensitive)) shouldPrint = false;

   // Perform some ad hoc conversions.  These are all triggered in the database
   // by having an entry of the form a|b where a is replaced by b in the input
   // file.  These are set in the InputDialog::initializeControl member function
   QString key = name + "::" + value;
   if (m_adHoc.count(key)) value = m_adHoc[key];

   //fix logicals
   if (inDatabase && opt.getType() == Option::Type_Logical) {
      if (name == "GUI") {
         value = value.toInt() == 0 ? QString::number(0) : QString::number(2);
      }else if (value.toInt() == Qt::Checked) {
         value = QString::number(1);
      }
   }



   //fix reals
   if (name == "CC_DIIS_MAXIMUM_OVERLAP" || 
       name == "CC_DOV_THRESH" ||
       name == "CC_DTHRESHOLD" ||
       name == "CC_HESSIAN_THRESH" ||
       name == "CC_THETA_STEPSIZE") {

       bool ok(true);
       double val = value.toDouble(&ok);

       int exp = floor(log10(val));
       int man = 100 * val * pow(10,-exp);
       //qDebug() << "2) " << man << "x10e" << exp+2;

       value = QString::number(man) + QString("%1").arg(exp+2,2,10,QChar('0'));

   }else if (inDatabase && opt.getType() == Option::Type_Real) {
      value = QString::number(value.toDouble() / opt.doubleStep());
   }


   if (name == "SCF_GUESS_MIX") {
      value = QString::number(value.toInt()/10);
   }

   if (name == "QUI_FROZEN_CORE" && value.toInt() != 0) {
      name = "N_FROZEN_CORE";
      value = "FC";
      shouldPrint = true;
   }

   if (name == "XC_GRID") {
      int ang(value.toInt(&isInt));

      if (isInt) {
         value = QString("%1").arg(ang);
         value = m_options["QUI_RADIAL_GRID"] + value.rightJustified(6,'0');
      }

   }

  
   if (name == "QUI_XOPT1" && value.toInt() > 0) {
      name = "XOPT_STATE_1";
      shouldPrint = true;

      // This is crappy
      key = "QUI_XOPT_SPIN1::";      
      key += m_options["QUI_XOPT_SPIN1"];
      if (m_adHoc.count(key)) m_options["QUI_XOPT_SPIN1"] = m_adHoc[key];

      value = "[" + m_options["QUI_XOPT_SPIN1"]  + ", "
                  + m_options["QUI_XOPT_IRREP1"] + ", "
                  + m_options["QUI_XOPT_STATE1"] + "]";

   }

   if (name == "QUI_XOPT2" && value.toInt() > 0)  {
      name = "XOPT_STATE_2";
      shouldPrint = true;

      key = "QUI_XOPT_SPIN2::";      
      key += m_options["QUI_XOPT_SPIN2"];
      if (m_adHoc.count(key)) m_options["QUI_XOPT_SPIN2"] = m_adHoc[key];

      value = "[" + m_options["QUI_XOPT_SPIN2"]  + ", "
                  + m_options["QUI_XOPT_IRREP2"] + ", "
                  + m_options["QUI_XOPT_STATE2"] + "]";
   }
 

   //qDebug() << "Fixing option for QChem" << name << "=" << value << "print = " << shouldPrint;
   return shouldPrint;
}
Example #28
0
int main(int argc, char *argv[])
{
    FillData fill_data;
    int fromfile_id = 1;
    int fromfile_offset = 0;
    QString fromfile_name;
    bool from_file = false;
    bool mark_repeats = true;

    bool usingDataDirect = false;

    bool from_dd_file = false;
    int sourceid = -1;
    QString fromddfile_lineupid;

    MythFillDatabaseCommandLineParser cmdline;
    if (!cmdline.Parse(argc, argv))
    {
        cmdline.PrintHelp();
        return GENERIC_EXIT_INVALID_CMDLINE;
    }

    if (cmdline.toBool("showhelp"))
    {
        cmdline.PrintHelp();
        return GENERIC_EXIT_OK;
    }

    if (cmdline.toBool("showversion"))
    {
        cmdline.PrintVersion();
        return GENERIC_EXIT_OK;
    }

    QCoreApplication a(argc, argv);
    QCoreApplication::setApplicationName(MYTH_APPNAME_MYTHFILLDATABASE);

    myth_nice(19);

    int retval;
    if ((retval = cmdline.ConfigureLogging()) != GENERIC_EXIT_OK)
        return retval;

    if (cmdline.toBool("manual"))
    {
        cout << "###\n";
        cout << "### Running in manual channel configuration mode.\n";
        cout << "### This will ask you questions about every channel.\n";
        cout << "###\n";
        fill_data.chan_data.m_interactive = true;
    }

    if (cmdline.toBool("onlyguide") || cmdline.toBool("update"))
    {
        LOG(VB_GENERAL, LOG_NOTICE,
            "Only updating guide data, channel and icon updates will be ignored");
        fill_data.chan_data.m_guideDataOnly = true;
    }

    if (cmdline.toBool("preset"))
    {
        cout << "###\n";
        cout << "### Running in preset channel configuration mode.\n";
        cout << "### This will assign channel ";
        cout << "preset numbers to every channel.\n";
        cout << "###\n";
        fill_data.chan_data.m_channelPreset = true;
    }

    if (cmdline.toBool("file"))
    {
        // manual file mode
        if (!cmdline.toBool("sourceid") ||
            !cmdline.toBool("xmlfile"))
        {
            cerr << "The --file option must be used in combination" << endl
                 << "with both --sourceid and --xmlfile." << endl;
            return GENERIC_EXIT_INVALID_CMDLINE;
        }

        fromfile_id = cmdline.toInt("sourceid");
        fromfile_name = cmdline.toString("xmlfile");

        LOG(VB_GENERAL, LOG_INFO,
            "Bypassing grabbers, reading directly from file");
        from_file = true;
    }

    if (cmdline.toBool("ddfile"))
    {
        // datadirect file mode
        if (!cmdline.toBool("sourceid") || 
            !cmdline.toBool("offset") ||
            !cmdline.toBool("lineupid") ||
            !cmdline.toBool("xmlfile"))
        {
            cerr << "The --dd-file option must be used in combination" << endl
                 << "with each of --sourceid, --offset, --lineupid," << endl
                 << "and --xmlfile." << endl;
            return GENERIC_EXIT_INVALID_CMDLINE;
        }

        fromfile_id         = cmdline.toInt("sourceid");
        fromfile_offset     = cmdline.toInt("offset");
        fromddfile_lineupid = cmdline.toString("lineupid");
        fromfile_name       = cmdline.toString("xmlfile");

        LOG(VB_GENERAL, LOG_INFO,
            "Bypassing grabbers, reading directly from file");
        from_dd_file = true;
    }

    if (cmdline.toBool("dochannelupdates"))
        fill_data.chan_data.m_channelUpdates = true;
    if (cmdline.toBool("removechannels"))
        fill_data.chan_data.m_removeNewChannels = true;
    if (cmdline.toBool("nofilterchannels"))
        fill_data.chan_data.m_filterNewChannels = false;
    if (!cmdline.GetPassthrough().isEmpty())
        fill_data.graboptions = " " + cmdline.GetPassthrough();
    if (cmdline.toBool("sourceid"))
        sourceid = cmdline.toInt("sourceid");
    if (cmdline.toBool("cardtype"))
    {
        if (!cmdline.toBool("sourceid"))
        {
            cerr << "The --cardtype option must be used in combination" << endl
                 << "with a --sourceid option." << endl;
            return GENERIC_EXIT_INVALID_CMDLINE;
        }

        fill_data.chan_data.m_cardType = cmdline.toString("cardtype")
                                                .trimmed().toUpper();
    }
    if (cmdline.toBool("maxdays") && cmdline.toInt("maxdays") > 0)
    {
        fill_data.maxDays = cmdline.toInt("maxdays");
        if (fill_data.maxDays == 1)
            fill_data.SetRefresh(0, true);
    }

    if (cmdline.toBool("refreshtoday"))
        cmdline.SetValue("refresh",
                cmdline.toStringList("refresh") << "today");
    if (cmdline.toBool("dontrefreshtomorrow"))
        cmdline.SetValue("refresh", 
                cmdline.toStringList("refresh") << "nottomorrow");
    if (cmdline.toBool("refreshsecond"))
        cmdline.SetValue("refresh", 
                cmdline.toStringList("refresh") << "second");
    if (cmdline.toBool("refreshall"))
        cmdline.SetValue("refresh", 
                cmdline.toStringList("refresh") << "all");
    if (cmdline.toBool("refreshday"))
        cmdline.SetValue("refresh",
                cmdline.toStringList("refresh") << 
                                        cmdline.toStringList("refreshday"));

    QStringList sl = cmdline.toStringList("refresh");
    if (!sl.isEmpty())
    {
        QStringList::const_iterator i = sl.constBegin();
        for (; i != sl.constEnd(); ++i)
        {
            QString warn = QString("Invalid entry in --refresh list: %1")
                                .arg(*i);

            bool enable = (*i).contains("not") ? false : true;

            if ((*i).contains("today"))
                fill_data.SetRefresh(0, enable);
            else if ((*i).contains("tomorrow"))
                fill_data.SetRefresh(1, enable);
            else if ((*i).contains("second"))
                fill_data.SetRefresh(2, enable);
            else if ((*i).contains("all"))
                fill_data.SetRefresh(FillData::kRefreshAll, enable);
            else if ((*i).contains("-"))
            {
                bool ok;
                QStringList r = (*i).split("-");

                uint lower = r[0].toUInt(&ok);
                if (!ok)
                {
                    cerr << warn.toLocal8Bit().constData() << endl;
                    return false;
                }

                uint upper = r[1].toUInt(&ok);
                if (!ok)
                {
                    cerr << warn.toLocal8Bit().constData() << endl;
                    return false;
                }

                if (lower > upper)
                {
                    cerr << warn.toLocal8Bit().constData() << endl;
                    return false;
                }

                for (uint j = lower; j <= upper; ++j)
                    fill_data.SetRefresh(j, true);
            }
            else
            {
                bool ok;
                uint day = (*i).toUInt(&ok);
                if (!ok)
                {
                    cerr << warn.toLocal8Bit().constData() << endl;
                    return false;
                }

                fill_data.SetRefresh(day, true);
            }
        }
    }

    if (cmdline.toBool("dontrefreshtba"))
        fill_data.refresh_tba = false;
    if (cmdline.toBool("ddgraball"))
    {
        fill_data.SetRefresh(FillData::kRefreshClear, false);
        fill_data.dd_grab_all = true;
    }
    if (cmdline.toBool("onlychannels"))
        fill_data.only_update_channels = true;

    mark_repeats = cmdline.toBool("markrepeats");

    CleanupGuard callCleanup(cleanup);

#ifndef _WIN32
    QList<int> signallist;
    signallist << SIGINT << SIGTERM << SIGSEGV << SIGABRT << SIGBUS << SIGFPE
               << SIGILL;
#if ! CONFIG_DARWIN
    signallist << SIGRTMIN;
#endif
    SignalHandler::Init(signallist);
    signal(SIGHUP, SIG_IGN);
#endif

    gContext = new MythContext(MYTH_BINARY_VERSION);
    if (!gContext->Init(false))
    {
        LOG(VB_GENERAL, LOG_ERR, "Failed to init MythContext, exiting.");
        return GENERIC_EXIT_NO_MYTHCONTEXT;
    }

    setHttpProxy();

    MythTranslation::load("mythfrontend");

    if (!UpgradeTVDatabaseSchema(false))
    {
        LOG(VB_GENERAL, LOG_ERR, "Incorrect database schema");
        return GENERIC_EXIT_DB_OUTOFDATE;
    }

    if (gCoreContext->SafeConnectToMasterServer(true, false))
        LOG(VB_GENERAL, LOG_INFO,
            "Opening blocking connection to master backend");
    else
        LOG(VB_GENERAL, LOG_WARNING,
            "Failed to connect to master backend. MythFillDatabase will "
            "continue running but will be unable to prevent backend from "
            "shutting down, or triggering a reschedule when complete.");

    if (from_file)
    {
        QString status = QObject::tr("currently running.");
        QDateTime GuideDataBefore, GuideDataAfter;

        updateLastRunStart();
        updateLastRunStatus(status);

        MSqlQuery query(MSqlQuery::InitCon());
        query.prepare("SELECT MAX(endtime) FROM program p LEFT JOIN channel c "
                      "ON p.chanid=c.chanid WHERE c.sourceid= :SRCID "
                      "AND manualid = 0 AND c.xmltvid != '';");
        query.bindValue(":SRCID", fromfile_id);

        if (query.exec() && query.next())
        {
            if (!query.isNull(0))
                GuideDataBefore =
                    MythDate::fromString(query.value(0).toString());
        }

        if (!fill_data.GrabDataFromFile(fromfile_id, fromfile_name))
        {
            return GENERIC_EXIT_NOT_OK;
        }

        updateLastRunEnd();

        query.prepare("SELECT MAX(endtime) FROM program p LEFT JOIN channel c "
                      "ON p.chanid=c.chanid WHERE c.sourceid= :SRCID "
                      "AND manualid = 0 AND c.xmltvid != '';");
        query.bindValue(":SRCID", fromfile_id);

        if (query.exec() && query.next())
        {
            if (!query.isNull(0))
                GuideDataAfter =
                    MythDate::fromString(query.value(0).toString());
        }

        if (GuideDataAfter == GuideDataBefore)
            status = QObject::tr("mythfilldatabase ran, but did not insert "
                    "any new data into the Guide.  This can indicate a "
                    "potential problem with the XML file used for the update.");
        else
            status = QObject::tr("Successful.");

        updateLastRunStatus(status);
    }
    else if (from_dd_file)
    {
        fill_data.GrabDataFromDDFile(
            fromfile_id, fromfile_offset, fromfile_name, fromddfile_lineupid);
    }
    else
    {
        SourceList sourcelist;

        MSqlQuery sourcequery(MSqlQuery::InitCon());
        QString where;

        if (sourceid != -1)
        {
            LOG(VB_GENERAL, LOG_INFO,
                QString("Running for sourceid %1 ONLY because --sourceid "
                        "was given on command-line").arg(sourceid));
            where = QString("WHERE sourceid = %1").arg(sourceid);
        }

        QString querystr = QString("SELECT sourceid,name,xmltvgrabber,userid,"
                                   "password,lineupid "
                                   "FROM videosource ") + where +
                                   QString(" ORDER BY sourceid;");

        if (sourcequery.exec(querystr))
        {
             if (sourcequery.size() > 0)
             {
                  while (sourcequery.next())
                  {
                       Source newsource;

                       newsource.id = sourcequery.value(0).toInt();
                       newsource.name = sourcequery.value(1).toString();
                       newsource.xmltvgrabber = sourcequery.value(2).toString();
                       newsource.userid = sourcequery.value(3).toString();
                       newsource.password = sourcequery.value(4).toString();
                       newsource.lineupid = sourcequery.value(5).toString();

                       newsource.xmltvgrabber_baseline = false;
                       newsource.xmltvgrabber_manualconfig = false;
                       newsource.xmltvgrabber_cache = false;
                       newsource.xmltvgrabber_prefmethod = "";

                       sourcelist.push_back(newsource);
                       usingDataDirect |=
                           is_grabber_datadirect(newsource.xmltvgrabber);
                  }
             }
             else
             {
                  LOG(VB_GENERAL, LOG_ERR,
                      "There are no channel sources defined, did you run "
                      "the setup program?");
                  return GENERIC_EXIT_SETUP_ERROR;
             }
        }
        else
        {
             MythDB::DBError("loading channel sources", sourcequery);
             return GENERIC_EXIT_DB_ERROR;
        }

        if (!fill_data.Run(sourcelist))
            LOG(VB_GENERAL, LOG_ERR, "Failed to fetch some program info");
        else
            LOG(VB_GENERAL, LOG_NOTICE, "Data fetching complete.");
    }

    if (fill_data.only_update_channels && !fill_data.need_post_grab_proc)
    {
        return GENERIC_EXIT_OK;
    }

    LOG(VB_GENERAL, LOG_INFO, "Adjusting program database end times.");
    int update_count = ProgramData::fix_end_times();
    if (update_count == -1)
        LOG(VB_GENERAL, LOG_ERR, "fix_end_times failed!");
    else
        LOG(VB_GENERAL, LOG_INFO,
            QString("    %1 replacements made").arg(update_count));

    LOG(VB_GENERAL, LOG_INFO, "Marking generic episodes.");

    MSqlQuery query(MSqlQuery::InitCon());
    query.prepare("UPDATE program SET generic = 1 WHERE "
        "((programid = '' AND subtitle = '' AND description = '') OR "
        " (programid <> '' AND category_type = 'series' AND "
        "  program.programid LIKE '%0000'));");

    if (!query.exec())
        MythDB::DBError("mark generic", query);
    else
        LOG(VB_GENERAL, LOG_INFO,
            QString("    Found %1").arg(query.numRowsAffected()));

    LOG(VB_GENERAL, LOG_INFO, "Extending non-unique programids "
                                "with multiple parts.");

    int found = 0;
    MSqlQuery sel(MSqlQuery::InitCon());
    sel.prepare("SELECT DISTINCT programid, partnumber, parttotal "
                "FROM program WHERE partnumber > 0 AND parttotal > 0 AND "
                "programid LIKE '%0000'");
    if (sel.exec())
    {
        MSqlQuery repl(MSqlQuery::InitCon());
        repl.prepare("UPDATE program SET programid = :NEWID "
                        "WHERE programid = :OLDID AND "
                        "partnumber = :PARTNUM AND "
                        "parttotal = :PARTTOTAL");

        while (sel.next())
        {
            QString orig_programid = sel.value(0).toString();
            QString new_programid = orig_programid.left(10);
            int     partnum, parttotal;
            QString part;

            partnum   = sel.value(1).toInt();
            parttotal = sel.value(2).toInt();

            part.setNum(parttotal);
            new_programid.append(part.rightJustified(2, '0'));
            part.setNum(partnum);
            new_programid.append(part.rightJustified(2, '0'));

            LOG(VB_GENERAL, LOG_INFO,
                QString("    %1 -> %2 (part %3 of %4)")
                    .arg(orig_programid).arg(new_programid)
                    .arg(partnum).arg(parttotal));

            repl.bindValue(":NEWID", new_programid);
            repl.bindValue(":OLDID", orig_programid);
            repl.bindValue(":PARTNUM",   partnum);
            repl.bindValue(":PARTTOTAL", parttotal);
            if (!repl.exec())
            {
                LOG(VB_GENERAL, LOG_INFO,
                    QString("Fudging programid from '%1' to '%2'")
                        .arg(orig_programid)
                        .arg(new_programid));
            }
            else
                found += repl.numRowsAffected();
        }
    }

    LOG(VB_GENERAL, LOG_INFO, QString("    Found %1").arg(found));

    LOG(VB_GENERAL, LOG_INFO, "Fixing missing original airdates.");
    query.prepare("UPDATE program p "
                    "JOIN ( "
                    "  SELECT programid, MAX(originalairdate) maxoad "
                    "  FROM program "
                    "  WHERE programid <> '' AND "
                    "        originalairdate IS NOT NULL "
                    "  GROUP BY programid ) oad "
                    "  ON p.programid = oad.programid "
                    "SET p.originalairdate = oad.maxoad "
                    "WHERE p.originalairdate IS NULL");

    if (query.exec())
        LOG(VB_GENERAL, LOG_INFO,
            QString("    Found %1 with programids")
            .arg(query.numRowsAffected()));

    query.prepare("UPDATE program p "
                    "JOIN ( "
                    "  SELECT title, subtitle, description, "
                    "         MAX(originalairdate) maxoad "
                    "  FROM program "
                    "  WHERE programid = '' AND "
                    "        originalairdate IS NOT NULL "
                    "  GROUP BY title, subtitle, description ) oad "
                    "  ON p.programid = '' AND "
                    "     p.title = oad.title AND "
                    "     p.subtitle = oad.subtitle AND "
                    "     p.description = oad.description "
                    "SET p.originalairdate = oad.maxoad "
                    "WHERE p.originalairdate IS NULL");

    if (query.exec())
        LOG(VB_GENERAL, LOG_INFO,
            QString("    Found %1 without programids")
            .arg(query.numRowsAffected()));

    if (mark_repeats)
    {
        LOG(VB_GENERAL, LOG_INFO, "Marking repeats.");

        int newEpiWindow = gCoreContext->GetNumSetting( "NewEpisodeWindow", 14);

        MSqlQuery query(MSqlQuery::InitCon());
        query.prepare("UPDATE program SET previouslyshown = 1 "
                      "WHERE previouslyshown = 0 "
                      "AND originalairdate is not null "
                      "AND (to_days(starttime) - to_days(originalairdate)) "
                      "    > :NEWWINDOW;");
        query.bindValue(":NEWWINDOW", newEpiWindow);

        if (query.exec())
            LOG(VB_GENERAL, LOG_INFO,
                QString("    Found %1").arg(query.numRowsAffected()));

        LOG(VB_GENERAL, LOG_INFO, "Unmarking new episode rebroadcast repeats.");
        query.prepare("UPDATE program SET previouslyshown = 0 "
                      "WHERE previouslyshown = 1 "
                      "AND originalairdate is not null "
                      "AND (to_days(starttime) - to_days(originalairdate)) "
                      "    <= :NEWWINDOW;");
        query.bindValue(":NEWWINDOW", newEpiWindow);

        if (query.exec())
            LOG(VB_GENERAL, LOG_INFO,
                QString("    Found %1").arg(query.numRowsAffected()));
    }

    // Mark first and last showings
    MSqlQuery updt(MSqlQuery::InitCon());
    updt.prepare("UPDATE program SET first = 0, last = 0;");
    if (!updt.exec())
        MythDB::DBError("Clearing first and last showings", updt);

    LOG(VB_GENERAL, LOG_INFO, "Marking episode first showings.");
    updt.prepare("UPDATE program "
                    "JOIN (SELECT MIN(p.starttime) AS starttime, p.programid "
                    "      FROM program p, channel c "
                    "      WHERE p.programid <> '' "
                    "            AND p.chanid = c.chanid "
                    "            AND c.visible = 1 "
                    "      GROUP BY p.programid "
                    "     ) AS firsts "
                    "ON program.programid = firsts.programid "
                    "  AND program.starttime = firsts.starttime "
                    "SET program.first=1;");
    if (!updt.exec())
        MythDB::DBError("Marking first showings by id", updt);
    found = updt.numRowsAffected();

    updt.prepare("UPDATE program "
                    "JOIN (SELECT MIN(p.starttime) AS starttime, p.title, p.subtitle, "
                    "           LEFT(p.description, 1024) AS partdesc "
                    "      FROM program p, channel c "
                    "      WHERE p.programid = '' "
                    "            AND p.chanid = c.chanid "
                    "            AND c.visible = 1 "
                    "      GROUP BY p.title, p.subtitle, partdesc "
                    "     ) AS firsts "
                    "ON program.starttime = firsts.starttime "
                    "  AND program.title = firsts.title "
                    "  AND program.subtitle = firsts.subtitle "
                    "  AND LEFT(program.description, 1024) = firsts.partdesc "
                    "SET program.first = 1 "
                    "WHERE program.programid = '';");
    if (!updt.exec())
        MythDB::DBError("Marking first showings", updt);
    found += updt.numRowsAffected();
    LOG(VB_GENERAL, LOG_INFO, QString("    Found %1").arg(found));

    LOG(VB_GENERAL, LOG_INFO, "Marking episode last showings.");
    updt.prepare("UPDATE program "
                    "JOIN (SELECT MAX(p.starttime) AS starttime, p.programid "
                    "      FROM program p, channel c "
                    "      WHERE p.programid <> '' "
                    "            AND p.chanid = c.chanid "
                    "            AND c.visible = 1 "
                    "      GROUP BY p.programid "
                    "     ) AS lasts "
                    "ON program.programid = lasts.programid "
                    "  AND program.starttime = lasts.starttime "
                    "SET program.last=1;");
    if (!updt.exec())
        MythDB::DBError("Marking last showings by id", updt);
    found = updt.numRowsAffected();

    updt.prepare("UPDATE program "
                    "JOIN (SELECT MAX(p.starttime) AS starttime, p.title, p.subtitle, "
                    "           LEFT(p.description, 1024) AS partdesc "
                    "      FROM program p, channel c "
                    "      WHERE p.programid = '' "
                    "            AND p.chanid = c.chanid "
                    "            AND c.visible = 1 "
                    "      GROUP BY p.title, p.subtitle, partdesc "
                    "     ) AS lasts "
                    "ON program.starttime = lasts.starttime "
                    "  AND program.title = lasts.title "
                    "  AND program.subtitle = lasts.subtitle "
                    "  AND LEFT(program.description, 1024) = lasts.partdesc "
                    "SET program.last = 1 "
                    "WHERE program.programid = '';");
    if (!updt.exec())
        MythDB::DBError("Marking last showings", updt);
    found += updt.numRowsAffected();
    LOG(VB_GENERAL, LOG_INFO, QString("    Found %1").arg(found));

    if (1) // limit MSqlQuery's lifetime
    {
        MSqlQuery query(MSqlQuery::InitCon());
        query.prepare("SELECT count(previouslyshown) "
                      "FROM program WHERE previouslyshown = 1;");
        if (query.exec() && query.next())
        {
            if (query.value(0).toInt() != 0)
                gCoreContext->SaveSettingOnHost("HaveRepeats", "1", NULL);
            else
                gCoreContext->SaveSettingOnHost("HaveRepeats", "0", NULL);
        }
    }

    if ((usingDataDirect) &&
        (gCoreContext->GetNumSetting("MythFillGrabberSuggestsTime", 1)))
    {
        fill_data.ddprocessor.GrabNextSuggestedTime();
    }

    LOG(VB_GENERAL, LOG_INFO, "\n"
            "===============================================================\n"
            "| Attempting to contact the master backend for rescheduling.  |\n"
            "| If the master is not running, rescheduling will happen when |\n"
            "| the master backend is restarted.                            |\n"
            "===============================================================");

    if (mark_repeats)
        ScheduledRecording::RescheduleMatch(0, 0, 0, QDateTime(),
                                            "MythFillDatabase");

    gCoreContext->SendMessage("CLEAR_SETTINGS_CACHE");

    gCoreContext->SendSystemEvent("MYTHFILLDATABASE_RAN");

    LOG(VB_GENERAL, LOG_NOTICE, "mythfilldatabase run complete.");

    return GENERIC_EXIT_OK;
}
Example #29
0
/***************************************************************************
 * ListToTable
 ***************************************************************************/
void CNDSromScanner::ListToTable(QList<CNDSromData> * lst, QTableWidget * tbl)
{
	int			i;
	CNDSromData		rd;
	QString			s;
	QTableWidgetItem *	itm;
	int			rsize;

	i = 0;
	s = "";
	itm = NULL;
	rsize = 0;

	if (lst == NULL)
		return;
	if (tbl == NULL)
		return;

	// Clear Table
	tbl->setRowCount(0);

	// Fill Table
	for (i = 0; i < lst->size(); ++i) 
	{
		rd = lst->at(i);

		tbl->setRowCount(i + 1);

		// ID
		s.setNum(rd.ROMid);
		itm = new QTableWidgetItem(s.rightJustified(8, '0'));
		itm->setFlags(Qt::ItemIsSelectable | Qt::ItemIsDragEnabled | Qt::ItemIsEnabled);
		tbl->setItem(i, 0, itm);
		// Icon
		switch(rd.ROMstate)
		{
		case STATE_NONE: break;
		case STATE_NO_ROM: break;
		case STATE_DIRECTORY: break;
		case STATE_CRC32:
		case STATE_ON_DEVICE:
		case STATE_FILE_STORED:
		case STATE_ONLY_DATA: 
			{
				itm = new QTableWidgetItem(rd.getROMicon(), "");
				itm->setFlags(Qt::ItemIsSelectable | Qt::ItemIsDragEnabled | Qt::ItemIsEnabled);
				tbl->setItem(i, 1, itm);
				break;
			}
		}
		// Status
		s = "";
		switch(rd.ROMstate)
		{
		case STATE_NONE: s = rd.ROMpath; break;
		case STATE_CRC32: s = "CRC32 vorhanden"; break;
		case STATE_NO_ROM: s = "kein NDS ROM"; break;
		case STATE_ON_DEVICE: s = "auf DEVICE"; break;
		case STATE_FILE_STORED: s = "im Archiv"; break;
		case STATE_ONLY_DATA: s = "Metadaten"; break;
		case STATE_DIRECTORY: s = "Ordner"; break;
		}
		itm = new QTableWidgetItem(s);
		itm->setFlags(Qt::ItemIsSelectable | Qt::ItemIsDragEnabled | Qt::ItemIsEnabled);
		tbl->setItem(i, 2, itm);
		// Name
		itm = new QTableWidgetItem(rd.ROMlanguage[this->NameLanguage].Name + " " + rd.ROMlanguage[this->NameLanguage].SubName);
		itm->setFlags(Qt::ItemIsSelectable | Qt::ItemIsDragEnabled | Qt::ItemIsEnabled);
		tbl->setItem(i, 3, itm);
		// ROMname
		itm = new QTableWidgetItem(rd.ROMname);
		itm->setFlags(Qt::ItemIsSelectable | Qt::ItemIsDragEnabled | Qt::ItemIsEnabled);
		tbl->setItem(i, 4, itm);
		// ROMserial
		itm = new QTableWidgetItem(rd.ROMserial);
		itm->setFlags(Qt::ItemIsSelectable | Qt::ItemIsDragEnabled | Qt::ItemIsEnabled);
		tbl->setItem(i, 5, itm);
		// CRC32
		s.setNum(rd.ROMcrc32, 16);
		itm = new QTableWidgetItem(s.toUpper().rightJustified(8, '0'));
		itm->setTextAlignment(Qt::AlignVCenter | Qt::AlignCenter);
		itm->setFlags(Qt::ItemIsSelectable | Qt::ItemIsDragEnabled | Qt::ItemIsEnabled);
		tbl->setItem(i, 6, itm);
		// ROMsize
		rsize = rd.ROMfilesize/(float)MB;
		if (rsize < 1)
			rsize = 0;
		itm = new QTableWidgetItem(s.setNum(rsize) + " MB");
		itm->setTextAlignment(Qt::AlignVCenter | Qt::AlignRight);
		itm->setFlags(Qt::ItemIsSelectable | Qt::ItemIsDragEnabled | Qt::ItemIsEnabled);
		tbl->setItem(i, 7, itm);
		// Verleger
		itm = new QTableWidgetItem(rd.ROMlanguage[this->NameLanguage].Publisher);
		itm->setFlags(Qt::ItemIsSelectable | Qt::ItemIsDragEnabled | Qt::ItemIsEnabled);
		tbl->setItem(i, 8, itm);
		
	}
}
Example #30
0
void Debugger::updateData( const dsp_core_t* pCore )
{
	int regs = sizeof( pCore->registers ) / sizeof( pCore->registers[0] );

	for( int i = 0; i < regs; ++i )
	{
		QString str = QString::number( pCore->registers[i], 16 );

		int justify;
		if( i == DSP_REG_X0 || i == DSP_REG_X1 || i == DSP_REG_Y0 || i == DSP_REG_Y1
		    || i == DSP_REG_A0 || i == DSP_REG_B0 || i == DSP_REG_A1 || i == DSP_REG_B1 )
		{
			justify = 6;
		}
		else if( i == DSP_REG_A2 || i == DSP_REG_B2 )
		{
			justify = 2;
		}
		else
		{
			justify = 4;
		}
		str = str.rightJustified( justify, '0' ).toUpper();

		switch( i )
		{
		case DSP_REG_X0:
			ui->lineEditX0->setText( str );
			break;
		case DSP_REG_X1:
			ui->lineEditX1->setText( str );
			break;
		case DSP_REG_Y0:
			ui->lineEditY0->setText( str );
			break;
		case DSP_REG_Y1:
			ui->lineEditY1->setText( str );
			break;
		case DSP_REG_A0:
			ui->lineEditA0->setText( str );
			break;
		case DSP_REG_B0:
			ui->lineEditB0->setText( str );
			break;
		case DSP_REG_A2:
			ui->lineEditA2->setText( str );
			break;
		case DSP_REG_B2:
			ui->lineEditB2->setText( str );
			break;
		case DSP_REG_A1:
			ui->lineEditA1->setText( str );
			break;
		case DSP_REG_B1:
			ui->lineEditB1->setText( str );
			break;

		case DSP_REG_R0:
			ui->lineEditR0->setText( str );
			break;
		case DSP_REG_R1:
			ui->lineEditR1->setText( str );
			break;
		case DSP_REG_R2:
			ui->lineEditR2->setText( str );
			break;
		case DSP_REG_R3:
			ui->lineEditR3->setText( str );
			break;
		case DSP_REG_R4:
			ui->lineEditR4->setText( str );
			break;
		case DSP_REG_R5:
			ui->lineEditR5->setText( str );
			break;
		case DSP_REG_R6:
			ui->lineEditR6->setText( str );
			break;
		case DSP_REG_R7:
			ui->lineEditR7->setText( str );
			break;

		case DSP_REG_N0:
			ui->lineEditN0->setText( str );
			break;
		case DSP_REG_N1:
			ui->lineEditN1->setText( str );
			break;
		case DSP_REG_N2:
			ui->lineEditN2->setText( str );
			break;
		case DSP_REG_N3:
			ui->lineEditN3->setText( str );
			break;
		case DSP_REG_N4:
			ui->lineEditN4->setText( str );
			break;
		case DSP_REG_N5:
			ui->lineEditN5->setText( str );
			break;
		case DSP_REG_N6:
			ui->lineEditN6->setText( str );
			break;
		case DSP_REG_N7:
			ui->lineEditN7->setText( str );
			break;

		case DSP_REG_M0:
			ui->lineEditM0->setText( str );
			break;
		case DSP_REG_M1:
			ui->lineEditM1->setText( str );
			break;
		case DSP_REG_M2:
			ui->lineEditM2->setText( str );
			break;
		case DSP_REG_M3:
			ui->lineEditM3->setText( str );
			break;
		case DSP_REG_M4:
			ui->lineEditM4->setText( str );
			break;
		case DSP_REG_M5:
			ui->lineEditM5->setText( str );
			break;
		case DSP_REG_M6:
			ui->lineEditM6->setText( str );
			break;
		case DSP_REG_M7:
			ui->lineEditM7->setText( str );
			break;

		case DSP_REG_SR:
			ui->lineEditSR->setText( str );
			break;
		case DSP_REG_LC:
			ui->lineEditLC->setText( str );
			break;
		}
	}

	QString str = QString::number( pCore->pc, 16 );
	str = str.rightJustified( 4, '0' ).toUpper();
	ui->lineEditPC->setText( str );

	scrollToPc();

	if( ui->radioButtonP->isChecked() )
	{
		updateP();
	}
	else if( ui->radioButtonX->isChecked() )
	{
		updateX();
	}
	else if( ui->radioButtonY->isChecked() )
	{
		updateY();
	}
	else if( ui->radioButtonL->isChecked() )
	{
		updateL();
	}

	// if waiting for another breakpoint
	if( m_autoStepping )
	{
		if( !m_breakpoints.contains( m_pCurrentDspCore->pc ) )
		{
			emit stepInto();
		}
		else
		{
			m_autoStepping = false;
		}
	}
}