Example #1
0
//@function     testing function
void testor(void)
{

    qDebug() << LEFT(2);
    qDebug() << RIGHT(2);
    qDebug() << PARENT(5);
    qDebug() << PARENT(6);

    QList<QPoint> openlist;
    openlist.push_back(QPoint(1,0));
    openlist.push_back(QPoint(0,1));
    openlist.push_back(QPoint(2,1));
    openlist.push_back(QPoint(2,3));
    openlist.push_back(QPoint(1,1));

    for (int i =0; i< openlist.size(); i++)
        qDebug() << openlist.at(i);

    for (int i=0; i< openlist.size(); i++)
    {
        for(int j=i+1; j< openlist.size(); j++)
        {
            if (openlist.at(i).x()>openlist.at(j).x())
                openlist.swap(i,j);
            else if ((openlist.at(i).x()==openlist.at(j).x()) && openlist.at(i).y()>openlist.at(j).y())
                openlist.swap(i,j);

        }
    }
    qDebug() << "-----------------";
    for (int i =0; i< openlist.size(); i++)
        qDebug() << openlist.at(i);

}
Example #2
0
QList< VdpVideoSurface > MPEGDecoder::getOrderedFrames()
{
   QList< VdpVideoSurface > list;
   int j;
   for ( j=0; j<NUMSURFACES; ++j ) {
      MPEGFrame *frame = frames.at( j );

      frame->info.backward_reference = VDP_INVALID_HANDLE;
      frame->info.forward_reference = VDP_INVALID_HANDLE;
      if ( frame->info.picture_coding_type==P_FRAME )
         frame->info.forward_reference = backwardRef;
      else if ( frame->info.picture_coding_type==B_FRAME ) {
         frame->info.forward_reference = forwardRef;
         frame->info.backward_reference = backwardRef;
      }

      VdpBitstreamBuffer vbit;
      vbit.struct_version = VDP_BITSTREAM_BUFFER_VERSION;
      vbit.bitstream = frame->data;
      vbit.bitstream_bytes = frame->dataLength;
      VdpStatus st = vc->vdp_decoder_render( decoder, surfaces[j], (VdpPictureInfo*)&frame->info, 1, &vbit );
      if ( st != VDP_STATUS_OK )
         fprintf( stderr, "MPEGDecoder: decoding failed: %s!\n", vc->vdp_get_error_string( st ) );


      if ( frame->info.picture_coding_type!=B_FRAME ) {				
         forwardRef = backwardRef;
         backwardRef = surfaces[j];
      }
   }

   QList< int > framesType;
   for ( j=0; j<NUMSURFACES; ++j ) {
      framesType.append( frames.at(j)->info.picture_coding_type );
      list.append( surfaces[j] );
   }

   j = 1;
   while ( j<NUMSURFACES ) {
      if ( framesType.at(j)==B_FRAME ) {
         framesType.swap(j-1, j);
         list.swap(j-1, j);
      }
      else
         ++j;
   }

   vc->vdp_decoder_destroy( decoder );
   decoder = VDP_INVALID_HANDLE;

   return list;
}
void tst_QList::swap() const
{
    QList<QString> list;
    list << "foo" << "bar" << "baz";

    // swap
    list.swap(0, 2);
    QCOMPARE(list, QList<QString>() << "baz" << "bar" << "foo");

    // swap again
    list.swap(1, 2);
    QCOMPARE(list, QList<QString>() << "baz" << "foo" << "bar");
}
QList<Experience> SystemeMotivationnel::exp(const Resultat & r) const
{
    QList<Experience> rt;
    QList<Interaction> temp;
    foreach (const Interaction& it, m_systeme)
    {
        if(r == it.resultat())
        {
            temp<<it;
        }
    }

    for(int i = 0; i < temp.size(); i ++)
    {
        for(int j = i; j < temp.size(); j ++)
        {
            //qDebug()<<temp[i].toString()<<temp[i].motivation()<<temp[j].toString()<<temp[j].motivation();

            if(temp[i] < temp[j])
            {
                temp.swap(i,j);
            }
        }
    }

    foreach (const Interaction& it, temp)
    {
        rt<<it.experience();
    }

    return rt;
}
QList<Media*> Playlist::shufflePlaylist(QList<Media *> media)
{
    for (int i = media.size()-1; i >= 0; i--)
    {

          int j = (int) (((float)qrand()/RAND_MAX) * i);
          media.swap(j, i);
    }
    return media;
}
Example #6
0
void MReportDataAdapter::BubbleSort(QList<EventInfo *> &list)
{
    for (int i = 0; i < list.count(); i++)
    {
        for (int j = 0; j < list.count() - 1 - i; j++)
        {
            if (list.at(j)->magnitude < list.at(j+1)->magnitude)
            {
                list.swap(j, j+1);
            }
        }
    }
}
QList<QPolygonF> PathSorter::MyFakeTSP(const QList<QPolygonF> inpaths)
{
	QPolygonF zero = QPolygonF(QRectF(0.0,mediaHeight,0.0,0.0)); // able to change the start point

	QList<QPolygonF> outpaths = QList<QPolygonF>(inpaths);

	// find the shortest path
	for (int i = 0; i < (outpaths.size()-1); ++i)
	{
		if(i == 0) // find good start
		{
			qreal dist=10000.0;
			int bestindex=i;
			for (int j = (i+1); j < outpaths.size(); ++j)
			{
				if (getDistance(zero,outpaths[j]) < dist) 
				{
				dist = getDistance(zero,outpaths[j]);
				bestindex = j;
				}
				
			}
			if (dist != 0) outpaths.swap(0,bestindex);
		}
		qreal dist=10000.0;
		int bestindex=i;
		for (int j = (i+1); j < outpaths.size(); ++j)
		{
			if (getDistance(outpaths[i],outpaths[j]) < dist) 
			{
				dist = getDistance(outpaths[i],outpaths[j]);
				bestindex = j;
			}
		}
		if (dist != 0) outpaths.swap((i+1),bestindex);
	}
	return outpaths;
}
QList<QVariantList>
ImporterSqlConnection::query( const QString &query, const QVariantMap &bindValues,
                              bool* const ok )
{
    QMutexLocker lock( &m_apiMutex );

    QMetaObject::invokeMethod( this, "slotQuery", blockingConnectionType(),
                               Q_ARG( QString, query ), Q_ARG( QVariantMap, bindValues ),
                               Q_ARG( bool* const, ok ) );

    QList<QVariantList> result;
    result.swap( m_result );
    return result;
}
Example #9
0
QList<int>* Util::randomArray(int N)
{
    // http://en.wikipedia.org/wiki/Fisher%E2%80%93Yates_shuffle
    QList<int> *lst = new QList<int>();
    lst->reserve(N);

    for (int i=0; i<N; ++i)
        (*lst)[i] = i;

    for (int i=0; i<N; ++i) {
        int n = randInt(i, N-1);
        lst->swap(i, n);
    }

    return lst;
}
Example #10
0
/*!
    \internal
*/
bool QImageReaderPrivate::initHandler()
{
    // check some preconditions
    if (!device || (!deleteDevice && !device->isOpen() && !device->open(QIODevice::ReadOnly))) {
        imageReaderError = QImageReader::DeviceError;
        errorString = QLatin1String(QT_TRANSLATE_NOOP(QImageReader, "Invalid device"));
        return false;
    }

    // probe the file extension
    if (deleteDevice && !device->isOpen() && !device->open(QIODevice::ReadOnly) && autoDetectImageFormat) {
        QList<QByteArray> extensions = QImageReader::supportedImageFormats();
        if (!format.isEmpty()) {
            // Try the most probable extension first
            int currentFormatIndex = extensions.indexOf(format.toLower());
            if (currentFormatIndex > 0)
                extensions.swap(0, currentFormatIndex);
        }

        int currentExtension = 0;

        QFile *file = static_cast<QFile *>(device);
        QString fileName = file->fileName();

        do {
            file->setFileName(fileName + QLatin1Char('.')
                    + QString::fromLatin1(extensions.at(currentExtension++).constData()));
            file->open(QIODevice::ReadOnly);
        } while (!file->isOpen() && currentExtension < extensions.size());

        if (!device->isOpen()) {
            imageReaderError = QImageReader::FileNotFoundError;
            errorString = QLatin1String(QT_TRANSLATE_NOOP(QImageReader, "File not found"));
            file->setFileName(fileName); // restore the old file name
            return false;
        }
    }

    // assign a handler
    if (!handler && (handler = createReadHandlerHelper(device, format, autoDetectImageFormat, ignoresFormatAndExtension)) == 0) {
        imageReaderError = QImageReader::UnsupportedFormatError;
        errorString = QLatin1String(QT_TRANSLATE_NOOP(QImageReader, "Unsupported image format"));
        return false;
    }
    return true;
}
Example #11
0
int main(int argc, char *argv[])
{
    QCoreApplication a(argc, argv);

    QList<QString> list;
    list << "aa" << "bb" << "cc";
    if(list[1] == "bb")
    {
        list[1] = "ab";
    }
    list.replace(2,"bc");
    qDebug() << "the list is:";
    for(int i = 0;i<list.size();++i)
    {
        qDebug()<<list.at(i);
    }
    list.append("dd");
    list.prepend("mm");

    QString str = list.takeAt(2);
    qDebug()<<"at(2) item is:"<<str;
    qDebug()<<"the list is:";
    for(int i = 0;i<list.size();++i)
    {
        qDebug()<<list.at(i);
    }
    list.insert(2,"mm");
    list.swap(1,3);
    qDebug()<<"the list is:";
    for(int i = 0;i<list.size();++i)
    {
        qDebug()<<list.at(i);
    }
    qDebug()<<"contains 'mm'?"<<list.contains("mm");
    qDebug()<<"the 'mm' count:"<<list.count("mm");
    qDebug()<<"the first 'mm' index:"<<list.indexOf("mm");
    qDebug()<<"the second 'mm' index:"<<list.indexOf("mm",1);



    return a.exec();
}
QList<QPolygonF> PathSorter::BbSort (const QList<QPolygonF> inpaths)
{
	QList<QPolygonF> outpaths = QList<QPolygonF>(inpaths);
	for (int i = 0; i < (outpaths.size()-1); i++)
	{
		for (int j = (i+1); j < outpaths.size(); j++)
		{
		if (outpaths[i].boundingRect().intersects(outpaths[j].boundingRect()))
			{
				if (outpaths[i].boundingRect().width() > outpaths[j].boundingRect().width() || outpaths[i].boundingRect().height() > outpaths[j].boundingRect().height()) 
				{
					outpaths.swap(i,j);
					break;
				}
			}
		}
	}
	cout<<"BbSort outpaths: "<< getTotalDistance(outpaths) << endl;
	return outpaths;
}
void EncodingTree::fill(){

    QList<EncondingNode *> lista = DList;

    while(lista.size() > 1)
    {

        EncondingNode *tmp = new EncondingNode(lista.at(0)->getFrequency() + lista.at(1)->getFrequency());
        int z = 0;

        tmp->setLeft(lista.at(0));
        tmp->setRight(lista.at(1));
        tmp->setType(1);

        lista.removeAt(0);
        lista.removeAt(0);
        lista.insert(z, tmp);

        root = tmp;

        while(1)
        {
            if(z == lista.size() - 1)
            {
                break;
            }
            if(lista.at(z)->getFrequency() > lista.at(z + 1)->getFrequency())
            {
                lista.swap(z,z+1);
            }
            else
            {
                break;
            }
            z++;
        }
    }
}
Example #14
0
void LayerListModel::handleMoveLayer(int oldIdx, int newIdx)
{
	// Need at least two layers for this to make sense
	const int count = _items.count();
	if(count < 2)
		return;

	QList<uint16_t> layers;
	layers.reserve(count);
	foreach(const LayerListItem &li, _items)
		layers.append(li.id);

	if(newIdx>oldIdx)
		--newIdx;

	layers.move(oldIdx, newIdx);

	// Layers are shown topmost first in the list but
	// are sent bottom first in the protocol.
	for(int i=0;i<count/2;++i)
		layers.swap(i,count-(1+i));

	emit layerOrderChanged(layers);
}
Example #15
0
void VListCF::determineChildren()
{
	// Get the single items from the list of composite items.
	QList< Item* > items = extractSingleItems();

	// Inserts elements that are not yet visualized and adjusts the order to match that in 'nodes'.
	for (int i = 0; i < node()->size(); ++i)
	{
		if (i >= items.size() ) items.append( renderer()->render(this, node()->at<Node>(i)));	// This node is new
		else if ( items[i]->node() == node()->at<Node>(i) )	continue;	// This node is already there
		else
		{
			// This node might appear somewhere ahead, we should look for it
			bool found = false;
			for (int k = i + 1; k<items.size(); ++k)
			{
				if ( items[k]->node() == node()->at<Node>(i) )
				{
					// We found this node, swap the visualizations
					items.swap(i, k);
					found = true;
					break;
				}
			}

			// The node was not found, insert a visualization here
			if (!found ) items.insert(i, renderer()->render(this, node()->at<Node>(i)));
		}
	}

	// Remove excess items
	while (items.size() > node()->size()) items.removeLast();

	// Convert the single items list back to a list of composite items.
	buildCompositeItems(items);
}
Example #16
0
void System::layoutSystem(qreal xo1)
      {
      if (_staves.empty())                 // ignore vbox
            return;

      static const Spatium instrumentNameOffset(1.0);       // TODO: make style value

      int nstaves  = _staves.size();

      //---------------------------------------------------
      //  find x position of staves
      //    create brackets
      //---------------------------------------------------

      qreal xoff2 = 0.0;         // x offset for instrument name

      int bracketLevels = 0;
      for (int idx = 0; idx < nstaves; ++idx)
            bracketLevels = qMax(bracketLevels, score()->staff(idx)->bracketLevels());

      qreal bracketWidth[bracketLevels];
      for (int i = 0; i < bracketLevels; ++i)
            bracketWidth[i] = 0.0;

      QList<Bracket*> bl;
      bl.swap(_brackets);

      for (int staffIdx = 0; staffIdx < nstaves; ++staffIdx) {
            Staff* s = score()->staff(staffIdx);
            for (int i = 0; i < bracketLevels; ++i) {
                  if (s->bracket(i) == BracketType::NO_BRACKET)
                        continue;
                  int firstStaff = staffIdx;
                  int lastStaff  = staffIdx + s->bracketSpan(i) - 1;
                  if (lastStaff >= nstaves)
                        lastStaff = nstaves - 1;

                  for (; firstStaff <= lastStaff; ++firstStaff) {
                        if (score()->staff(firstStaff)->show())
                              break;
                        }
                  for (; lastStaff >= firstStaff; --lastStaff) {
                        if (score()->staff(lastStaff)->show())
                              break;
                        }
                  int span = lastStaff - firstStaff + 1;
                  //
                  // do not show bracket if it only spans one
                  // system due to some invisible staves
                  //
                  if ((span > 1) || (s->bracketSpan(i) == span)) {
                        //
                        // this bracket is visible
                        //
                        Bracket* b = 0;
                        int track = staffIdx * VOICES;
                        for (int k = 0; k < bl.size(); ++k) {
                              if (bl[k]->track() == track && bl[k]->level() == i) {
                                    b = bl.takeAt(k);
                                    break;
                                    }
                              }
                        if (b == 0) {
                              b = new Bracket(score());
                              b->setGenerated(true);
                              b->setTrack(track);
                              b->setLevel(i);
                              }
                        add(b);
                        b->setFirstStaff(firstStaff);
                        b->setLastStaff(lastStaff);
                        b->setBracketType(s->bracket(i));
                        b->setSpan(s->bracketSpan(i));
                        bracketWidth[i] = qMax(bracketWidth[i], b->width());
                        }
                  }
            if (!s->show())
                  continue;
            for (InstrumentName* t : _staves[staffIdx]->instrumentNames) {
                  t->layout();
                  qreal w = t->width() + point(instrumentNameOffset);
                  if (w > xoff2)
                        xoff2 = w;
                  }
            }

      for (Bracket* b : bl)
            delete b;

      //---------------------------------------------------
      //  layout  SysStaff and StaffLines
      //---------------------------------------------------

      _leftMargin = xoff2;


      qreal bd = score()->styleP(StyleIdx::bracketDistance);
      if ( _brackets.size() > 0) {
            for (int i = 0; i < bracketLevels; ++i)
                  _leftMargin += bracketWidth[i] + bd;
            }

      int nVisible = 0;
      for (int staffIdx = 0; staffIdx < nstaves; ++staffIdx) {
            SysStaff* s  = _staves[staffIdx];
            Staff* staff = score()->staff(staffIdx);
            if (!staff->show() || !s->show()) {
                  s->setbbox(QRectF());
                  continue;
                  }
            ++nVisible;
            qreal staffMag = staff->mag();
            qreal h;
            if (staff->lines() == 1)
                  h = 2;
            else
                  h = (staff->lines()-1) * staff->lineDistance();
            h = h * staffMag * spatium();
            s->bbox().setRect(_leftMargin + xo1, 0.0, 0.0, h);
            }

      //---------------------------------------------------
      //  layout brackets
      //---------------------------------------------------

      for (Bracket* b : _brackets) {
            qreal xo = -xo1;
            for (const Bracket* b2 : _brackets) {
                   if (b->level() > b2->level() &&
                      ((b->firstStaff() >= b2->firstStaff() && b->firstStaff() <= b2->lastStaff()) ||
                      (b->lastStaff() >= b2->firstStaff() && b->lastStaff() <= b2->lastStaff())))
                        xo += b2->width() + bd;
                   }
            b->rxpos() = _leftMargin - xo - b->width();
            }

      //---------------------------------------------------
      //  layout instrument names x position
      //---------------------------------------------------

      int idx = 0;
      for (const Part* p : score()->parts()) {
            SysStaff* s = staff(idx);
            if (s->show() && p->show()) {
                  for (InstrumentName* t : s->instrumentNames) {
                        switch (t->textStyle().align() & AlignmentFlags::HMASK) {
                              case int(AlignmentFlags::LEFT):
                                    t->rxpos() = 0;
                                    break;
                              case int(AlignmentFlags::HCENTER):
                                    t->rxpos() = (xoff2 - point(instrumentNameOffset) + xo1) * .5;
                                    break;
                              case int(AlignmentFlags::RIGHT):
                              default:
                                    t->rxpos() = xoff2 - point(instrumentNameOffset) + xo1;
                                    break;
                              }
                        t->rxpos() += t->textStyle().offset(t->spatium()).x();
                        }
                  }
            idx += p->nstaves();
            }
      }
Example #17
0
//! Methode zum Erstellen des Previews
void PrintWidget::createPreview()
{
  //! Überprüfen, ob der Zeiger ungleich NULL ist
  if(_CurrentArea == NULL)
  {
    return;
  }

  QString sHtml = "<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01//EN\">";
  sHtml += "<html><head><title>Aufbau einer Tabelle</title></head>";
  sHtml += "<body>";
  sHtml += "<table border=\"0\">";
  sHtml += "<tr><th align=\"left\" width=\"24%\">Gebietsbezeichnung: </th><th align=\"left\" width=\"41%\">";
  sHtml += _CurrentArea->areaName();
  sHtml += "</th><th align=\"left\" width=\"23%\">Gebietsnummer: </th><th align=\"left\" width=\"12%\">";
  sHtml += QString::number(_CurrentArea->areaNumber());
  sHtml += "</th>";
  sHtml += "</table><BR>";

  //! Liste mit allen Bearbeitungen für das aktuelle Gebiet
  QList<AreaHandling*>* lstAreaHandlingCurArea = _CurrentArea->lstHandling();

  sHtml += "<table border=\"1\" style=\"border-style:solid; border-color:black;\">";
  sHtml += "<tr><th width=\"35%\"></th><th align=\"center\" width=\"26%\">Name Prediger</th><th align=\"center\" width=\"13%\">Erhalten am</th><th align=\"center\" width=\"13%\">Bearbeitet am</th><th align=\"center\" width=\"13%\">Abgesucht am</th></tr>";

  if(lstAreaHandlingCurArea->isEmpty() == true)
  {
    sHtml += "<tr><td rowspan=\"8\" valign=\"middle\">Trage hier die Personen ein, die auf diesem Gebiet wohnen</td><td height=\"2%\"></td><td></td><td></td><td></td></tr>";
  }
  else
  {
      while( lstAreaHandlingCurArea->size() > 3 )
          lstAreaHandlingCurArea->takeFirst();
  }


  bool FirstRow = true;


  for(int i= lstAreaHandlingCurArea->size() > 3 ? lstAreaHandlingCurArea->size() - 3 : 0; i<lstAreaHandlingCurArea->size(); i++)
  {
    if(FirstRow == true)
    {
      sHtml += "<tr><td rowspan=\"8\" valign=\"middle\">Trage hier die Personen ein, die auf diesem Gebiet wohnen</td>";
      FirstRow = false;
    }
    else
    {
      sHtml += "<tr>";
    }

    sHtml += "<td height=\"2%\" align=\"center\">";

    sHtml += lstAreaHandlingCurArea->at(i)->prophet()->toString();
    sHtml += "</td><td align=\"center\">";
    sHtml += QDate(2000,1,1).addDays(lstAreaHandlingCurArea->at(i)->dateLend()).toString("MM.yyyy");
    sHtml += "</td><td align=\"center\">";

    if(lstAreaHandlingCurArea->at(i)->dateDone() != -1)
    {
      sHtml += QDate(2000,1,1).addDays(lstAreaHandlingCurArea->at(i)->dateDone()).toString("MM.yyyy");
    }

    sHtml += "</td>";
    sHtml += "<td align=\"center\">";

    if(lstAreaHandlingCurArea->at(i)->dateSearch() != -1)
    {
      sHtml += QDate(2000,1,1).addDays(lstAreaHandlingCurArea->at(i)->dateSearch()).toString("MM.yyyy");
    }

    sHtml += "</td>";

    sHtml += "</tr>";
  }


  for(int i=lstAreaHandlingCurArea->size() > 3 ? lstAreaHandlingCurArea->size() - 3 : lstAreaHandlingCurArea->size(); i<7; i++)
  {
    sHtml += "<tr><td height=\"2%\"></td><td></td><td></td><td></td></tr>";
  }

  sHtml += "</table><BR>";


  //! Alle dazugehörige Teilgebiet werden in einer Liste zusammengefasst
  QList<AreaPart*> lstAreaPartCurArea;

  //! Liste mit allen Teilgebieten holen
  QList<AreaPart*>* lstAreaPart = _DB->allAreaPart();

  //! Über alle Teilgebiete laufen und die entsprechenden in die Liste einfügen
  for(int i=0; i<lstAreaPart->size(); i++)
  {
    if(lstAreaPart->at(i)->area() == _CurrentArea)
    {
      lstAreaPartCurArea.append(lstAreaPart->at(i));
    }
  }


  //! Jetzt werden die Bewohner zusammengezählt, die zu dem Gebiet zugehören
  QList<Habitant*> lstHabitantCurArea;

  //! Liste mit allen Bewohnern holen
  QList<Habitant*>* lstHabitant = _DB->allHabitant();

  //! Über alle Bewohner laufen und entsprechende in die Liste einfügen
  for(int i=0; i<lstHabitant->size(); i++)
  {
    if(lstHabitant->at(i)->address()->street()->areaPart()->area() == _CurrentArea)
    {
      lstHabitantCurArea.append(lstHabitant->at(i));
    }
  }

  // Die Liste mit allen Bewohnern ist nicht nach Strasse -> Hausnummer sortiert
  // Die Liste zuerst nach Strassen sortieren.

  bool swapped = false;

    do
    {
        swapped = false;

        for( int i=0; i < lstHabitantCurArea.size() - 1; i++ )
        {
            if( lstHabitantCurArea.at( i )->address()->street()->streetName() > lstHabitantCurArea.at( i + 1 )->address()->street()->streetName() )
            {
                lstHabitantCurArea.swap( i, i+1 );
                swapped = true;
            }
        }
    } while( swapped );

    do
    {
        swapped = false;

      for( int i=0; i < lstHabitantCurArea.size() - 1; i++ )
      {
          if( ( lstHabitantCurArea.at( i )->address()->street() == lstHabitantCurArea.at( i + 1 )->address()->street() ) && ( lstHabitantCurArea.at( i )->address()->houseNumberAsInt() > lstHabitantCurArea.at( i + 1 )->address()->houseNumberAsInt() ) )
          {
              lstHabitantCurArea.swap( i, i+1 );
              swapped = true;
          }
      }
    } while( swapped );

    // Die Bewohner werden noch alphabetisch sortiert.
    do
    {
        swapped = false;

        for( int i=0; i < lstHabitantCurArea.size() - 1; ++i )
        {
            if( ( lstHabitantCurArea.at( i )->address() == lstHabitantCurArea.at( i + 1 )->address() ) && ( lstHabitantCurArea.at( i )->lastName() > lstHabitantCurArea.at( i + 1 )->lastName() ) )
            {
                lstHabitantCurArea.swap( i, i+1 );
                swapped = true;
            }
        }
  } while( swapped );


  //! So, die Informationen passen also auf eine Seite...

  sHtml += "<table border=\"1\" style=\"border-style:solid; border-color:black;\">";
  sHtml += "<tr><th align=\"center\" width=\"31%\">Strasse</th><th align=\"center\" width=\"8%\">Nr.</th><th align=\"center\" width=\"61%\">Name</th></tr>";

  Street* LastStreet = NULL;
  int PrintRows = 0;

  for(int i=0; i<lstAreaPartCurArea.size(); i++)
  {


    //! Wenn es sich nur um ein Teilgebiet handelt, wird diese nicht ausgegeben
    if(lstAreaPartCurArea.size() > 1)
    {
      sHtml += "<tr><td align=\"center\"><b>";
      sHtml += lstAreaPartCurArea.at(i)->toString();
      sHtml += "</b></td><td></td><td></td></tr>";
      PrintRows++;
    }



    for(int j=0; j<lstHabitantCurArea.size(); j++)
    {
      if(lstHabitantCurArea.at(j)->address()->street()->areaPart() == lstAreaPartCurArea.at(i))
      {
        sHtml += "<tr><td width=\"31%\">";

        if(LastStreet != lstHabitantCurArea.at(j)->address()->street())
        {
          LastStreet = lstHabitantCurArea.at(j)->address()->street();
          sHtml += "&nbsp;";
          sHtml += lstHabitantCurArea.at(j)->address()->street()->toString();
        }

        sHtml += "</td><td align=\"center\" width=\"8%\">";
        sHtml += lstHabitantCurArea.at(j)->address()->toString();
        sHtml += "</td><td width=\"61%\">";
        sHtml += "&nbsp;";

        //! Überprüfen, ob die Ausgabe des Bewohners in eine Zeile passt
        //! Die Ausgabe ist auf 50 Zeichen begrenzt
        if(lstHabitantCurArea.at(j)->toStringShort(true).length() > 50)
        {
          //! Meldung ausgeben
          QMessageBox::warning(this, tr("Hinweis..."), tr("Die Ausgabeinformation für den Bewohner \"") + lstHabitantCurArea.at(j)->toString() + tr(" ist länger als 50 Zeichen"));
        }

        sHtml += lstHabitantCurArea.at(j)->toStringShort(true);


        sHtml += "</td></tr>";
        PrintRows++;
      }
    }

    //sHtml += "<tr><td></td><td align=\"center\"></td><td></td></tr>";
    //PrintRows++;
  }


  int RowsMaxCount = 0;

  //! Auf der ersten Seite sind es 37 Zeilen
  if(PrintRows < 38)
  {
    RowsMaxCount = 37 - PrintRows;
  }
  else
  {
    //! Auf der folgenden Seiten passen 51 Zeilen
    RowsMaxCount = (52 - ((PrintRows - 37) % 52));
  }

  for(int i = 1; i<RowsMaxCount; i++)
  {
    sHtml += "<tr><td></td><td align=\"center\"></td><td></td></tr>";
  }

  sHtml += "</table>";
  sHtml += "</body></html>";

  ui->textEdit->setHtml(sHtml);
}
void GAppHelper::ReverseOriginal(QList<T>& list)
{
    for(int i = 0; i < (list.size() / 2); i++)
        list.swap(i, list.size() - (1 + i));
}
Example #19
0
void shuffle(QList<T> &list) {
	int size = list.size();
	for (int i = 1; i < size; i++) {
		list.swap(i, qrand() % size);
	}
}
Example #20
0
void Worker::run() {
	while (1) {
		res->requestSemaphore.acquire(1);
		if (die) {
			break;
		}

		// get next page to render
		res->requestMutex.lock();
		int page, width, index;
		map<int,pair<int,int> >::iterator less = res->requests.lower_bound(res->center_page);
		map<int,pair<int,int> >::iterator greater = less--;

		if (greater != res->requests.end()) {
			if (greater != res->requests.begin()) {
				// favour nearby page, go down first
				if (greater->first + less->first <= res->center_page * 2) {
					page = greater->first;
					index = greater->second.first;
					width = greater->second.second;
					res->requests.erase(greater);
				} else {
					page = less->first;
					index = less->second.first;
					width = less->second.second;
					res->requests.erase(less);
				}
			} else {
				page = greater->first;
				index = greater->second.first;
				width = greater->second.second;
				res->requests.erase(greater);
			}
		} else {
			page = less->first;
			index = less->second.first;
			width = less->second.second;
			res->requests.erase(less);
		}
		res->requestMutex.unlock();

		// check for duplicate requests
		res->k_page[page].mutex.lock();
		if (res->k_page[page].status[index] == width &&
				res->k_page[page].rotation[index] == res->rotation) {
			res->k_page[page].mutex.unlock();
			continue;
		}
		int rotation = res->rotation;
		res->k_page[page].mutex.unlock();

		// open page
#ifdef DEBUG
		cerr << "    rendering page " << page << " for index " << index << endl;
#endif
		Poppler::Page *p = res->doc->page(page);
		if (p == NULL) {
			cerr << "failed to load page " << page << endl;
			continue;
		}

		// render page
		float dpi = 72.0 * width / res->get_page_width(page);
		QImage img = p->renderToImage(dpi, dpi, -1, -1, -1, -1,
				static_cast<Poppler::Page::Rotation>(rotation));

		if (img.isNull()) {
			cerr << "failed to render page " << page << endl;
			continue;
		}

		// invert to current color setting
		if (res->inverted_colors) {
			img.invertPixels();
		}

		// put page
		res->k_page[page].mutex.lock();
		if (!res->k_page[page].img[index].isNull()) {
			res->k_page[page].img[index] = QImage(); // assign null image
		}

		// adjust all available images to current color setting
		if (res->k_page[page].inverted_colors != res->inverted_colors) {
			res->k_page[page].inverted_colors = res->inverted_colors;
			for (int i = 0; i < 3; i++) {
				res->k_page[page].img[i].invertPixels();
			}
			res->k_page[page].thumbnail.invertPixels();
		}
		res->k_page[page].img[index] = img;
		res->k_page[page].status[index] = width;
		res->k_page[page].rotation[index] = rotation;
		res->k_page[page].mutex.unlock();

		res->garbageMutex.lock();
		res->garbage.insert(page); // TODO add index information?
		res->garbageMutex.unlock();

		emit page_rendered(page);

		// collect goto links
		res->link_mutex.lock();
		if (res->k_page[page].links == NULL) {
			res->link_mutex.unlock();

			QList<Poppler::Link *> *links = new QList<Poppler::Link *>;
			QList<Poppler::Link *> l = p->links();
			links->swap(l);

			res->link_mutex.lock();
			res->k_page[page].links = links;
		}
		if (res->k_page[page].text == NULL) {
			res->link_mutex.unlock();

			QList<Poppler::TextBox *> text = p->textList();
			// assign boxes to lines
			// make single parts from chained boxes
			set<Poppler::TextBox *> used;
			QList<SelectionPart *> selection_parts;
			Q_FOREACH(Poppler::TextBox *box, text) {
				if (used.find(box) != used.end()) {
					continue;
				}
				used.insert(box);

				SelectionPart *p = new SelectionPart(box);
				selection_parts.push_back(p);
				Poppler::TextBox *next = box->nextWord();
				while (next != NULL) {
					used.insert(next);
					p->add_word(next);
					next = next->nextWord();
				}
			}

			// sort by y coordinate
			qStableSort(selection_parts.begin(), selection_parts.end(), selection_less_y);

			QRectF line_box;
			QList<SelectionLine *> *lines = new QList<SelectionLine *>();
			Q_FOREACH(SelectionPart *part, selection_parts) {
				QRectF box = part->get_bbox();
				// box fits into line_box's line
				if (!lines->empty() && box.y() <= line_box.center().y() && box.bottom() > line_box.center().y()) {
					float ratio_w = box.width() / line_box.width();
					float ratio_h = box.height() / line_box.height();
					if (ratio_w < 1.0f) {
						ratio_w = 1.0f / ratio_w;
					}
					if (ratio_h < 1.0f) {
						ratio_h = 1.0f / ratio_h;
					}
					if (ratio_w > 1.3f && ratio_h > 1.3f) {
						lines->back()->sort();
						lines->push_back(new SelectionLine(part));
						line_box = part->get_bbox();
					} else {
						lines->back()->add_part(part);
					}
				// it doesn't fit, create new line
				} else {
					if (!lines->empty()) {
						lines->back()->sort();
					}
					lines->push_back(new SelectionLine(part));
					line_box = part->get_bbox();
				}
			}
			if (!lines->empty()) {
				lines->back()->sort();
			}

			res->link_mutex.lock();
			res->k_page[page].text = lines;
		}
Example #21
0
// Triangulate a no convex polygon
void glc::triangulatePolygon(QList<GLuint>* pIndexList, const QList<float>& bulkList)
{
	int size= pIndexList->size();
	if (polygonIsConvex(pIndexList, bulkList))
	{
		QList<GLuint> indexList(*pIndexList);
		pIndexList->clear();
		for (int i= 0; i < size - 2; ++i)
		{
			pIndexList->append(indexList.at(0));
			pIndexList->append(indexList.at(i + 1));
			pIndexList->append(indexList.at(i + 2));
		}
	}
	else
	{
		// Get the polygon vertice
		QList<GLC_Point3d> originPoints;
		QHash<int, int> indexMap;

		QList<int> face;
		GLC_Point3d currentPoint;
		int delta= 0;
		for (int i= 0; i < size; ++i)
		{
			const int currentIndex= pIndexList->at(i);
			currentPoint= GLC_Point3d(bulkList.at(currentIndex * 3), bulkList.at(currentIndex * 3 + 1), bulkList.at(currentIndex * 3 + 2));
			if (!originPoints.contains(currentPoint))
			{
				originPoints.append(GLC_Point3d(bulkList.at(currentIndex * 3), bulkList.at(currentIndex * 3 + 1), bulkList.at(currentIndex * 3 + 2)));
				indexMap.insert(i - delta, currentIndex);
				face.append(i - delta);
			}
			else
			{
				qDebug() << "Multi points";
				++delta;
			}
		}
		// Values of PindexList must be reset
		pIndexList->clear();

		// Update size
		size= size - delta;

		// Check new size
		if (size < 3) return;

		//-------------- Change frame to mach polygon plane
			// Compute face normal
			const GLC_Point3d point1(originPoints[0]);
			const GLC_Point3d point2(originPoints[1]);
			const GLC_Point3d point3(originPoints[2]);

			const GLC_Vector3d edge1(point2 - point1);
			const GLC_Vector3d edge2(point3 - point2);

			GLC_Vector3d polygonPlaneNormal(edge1 ^ edge2);
			polygonPlaneNormal.normalize();

			// Create the transformation matrix
			GLC_Matrix4x4 transformation;

			GLC_Vector3d rotationAxis(polygonPlaneNormal ^ Z_AXIS);
			if (!rotationAxis.isNull())
			{
				const double angle= acos(polygonPlaneNormal * Z_AXIS);
				transformation.setMatRot(rotationAxis, angle);
			}

			QList<GLC_Point2d> polygon;
			// Transform polygon vertexs
			for (int i=0; i < size; ++i)
			{
				originPoints[i]= transformation * originPoints[i];
				// Create 2d vector
				polygon << originPoints[i].toVector2d(Z_AXIS);
			}
			// Create the index
			QList<int> index= face;

			const bool faceIsCounterclockwise= isCounterclockwiseOrdered(polygon);

			if(!faceIsCounterclockwise)
			{
				//qDebug() << "face Is Not Counterclockwise";
				const int max= size / 2;
				for (int i= 0; i < max; ++i)
				{
					polygon.swap(i, size - 1 -i);
					int temp= face[i];
					face[i]= face[size - 1 - i];
					face[size - 1 - i]= temp;
				}
			}

            QList<int> tList;
			triangulate(polygon, index, tList);
			size= tList.size();
			for (int i= 0; i < size; i+= 3)
			{
				// Avoid normal problem
				if (faceIsCounterclockwise)
				{
					pIndexList->append(indexMap.value(face[tList[i]]));
					pIndexList->append(indexMap.value(face[tList[i + 1]]));
					pIndexList->append(indexMap.value(face[tList[i + 2]]));
				}
				else
				{
					pIndexList->append(indexMap.value(face[tList[i + 2]]));
					pIndexList->append(indexMap.value(face[tList[i + 1]]));
					pIndexList->append(indexMap.value(face[tList[i]]));
				}
			}
			Q_ASSERT(size == pIndexList->size());
	}

}
Example #22
0
QList<Number> Gauss::findSolution(QList<QList<Number> > coefficients)
{
	int variablesCount = coefficients.size();
	int columnsCount = variablesCount + 1;
	int rowsCount = variablesCount;

	// Save initial order of variables.
	QList<int> orderOfVariables;
	for (int i = 0; i < variablesCount; ++i) {
		orderOfVariables << i;
	}


	// Direct pass

	for (int i = 0; i < rowsCount; ++i) {

		int mainElementIndex = i;
		Number mainElement = coefficients[i][i];

		// Find main element of the current row
		for (int j = i + 1; j < columnsCount - 1; ++j) {
			if (qAbs(mainElement) < qAbs(coefficients[i][j])) {
				mainElementIndex = j;
				mainElement = coefficients[i][j];
			}
		}

		if (MathUtils::isNull(mainElement)) {
			THROW(ENoSolution());
		}

		// Swap columns
		if (mainElementIndex != i) {
			swapColumns(coefficients, i, mainElementIndex);
			orderOfVariables.swap(i, mainElementIndex);
		}

		// Divide the row by the main element
		coefficients[i] = MathUtils::divideVectorByNumber(coefficients[i], mainElement);

		// Subtract current row (multiplied before) from rows below.
		for (int j = i + 1; j < rowsCount; ++j) {
			QList<Number> multipliedRow = MathUtils::multiplyVectorByNumber(coefficients[i], coefficients[j][i]);
			coefficients[j] = MathUtils::subtractVectorFromVector(coefficients[j], multipliedRow);
		}
	}


	// Reverse pass

	for (int i = rowsCount - 1; i >= 0; --i) {
		for (int j = i - 1; j >= 0; --j) {
			// subtract current row (multiplied before) from rows above.
			QList<Number> multipliedRow = MathUtils::multiplyVectorByNumber(coefficients[i], coefficients[j][i]);
			coefficients[j] = MathUtils::subtractVectorFromVector(coefficients[j], multipliedRow);
		}
	}


	// Form result

	QList<Number> result = sizedVector(variablesCount);
	for (int i = 0; i < rowsCount; ++i) {
		result[orderOfVariables[i]] = coefficients[i][columnsCount - 1];
	}
	return result;
}
Example #23
0
void SearchWorker::run() {
	while (1) {
		bar->search_mutex.lock();
		stop = false;
		if (die) {
			break;
		}
		// always clear results -> empty search == stop search
		emit clear_hits();

		// get search string
		bar->term_mutex.lock();
		if (bar->term.isEmpty()) {
			bar->term_mutex.unlock();
			emit update_label_text("done.");
			continue;
		}
		int start = bar->start_page;
		QString search_term = bar->term;
		forward = bar->forward;
		bar->term_mutex.unlock();

		// check if term contains upper case letters; if so, do case sensitive search (smartcase)
		bool has_upper_case = false;
		for (QString::const_iterator it = search_term.begin(); it != search_term.end(); ++it) {
			if (it->isUpper()) {
				has_upper_case = true;
				break;
			}
		}

#ifdef DEBUG
		cerr << "'" << search_term.toUtf8().constData() << "'" << endl;
#endif
		emit update_label_text(QString("[%1] 0\% searched, 0 hits")
			.arg(has_upper_case ? "Case" : "no case"));

		// search all pages
		int hit_count = 0;
		int page = start;
		do {
			Poppler::Page *p = bar->doc->page(page);
			if (p == NULL) {
				cerr << "failed to load page " << page << endl;
				continue;
			}

			// collect all occurrences
			QList<QRectF> *hits = new QList<QRectF>;
#if POPPLER_VERSION < POPPLER_VERSION_CHECK(0, 22, 0)
			// old search interface, slow for many hits per page
			double x = 0, y = 0, x2 = 0, y2 = 0;
			while (!stop && !die &&
					p->search(search_term, x, y, x2, y2, Poppler::Page::NextResult,
						has_upper_case ? Poppler::Page::CaseSensitive : Poppler::Page::CaseInsensitive)) {
				hits->push_back(QRectF(x, y, x2 - x, y2 - y));
			}
#elif POPPLER_VERSION < POPPLER_VERSION_CHECK(0, 31, 0)
			// new search interface
			QList<QRectF> tmp = p->search(search_term,
					has_upper_case ? Poppler::Page::CaseSensitive : Poppler::Page::CaseInsensitive);
			hits->swap(tmp);
#else
			// even newer interface
			QList<QRectF> tmp = p->search(search_term,
					has_upper_case ? (Poppler::Page::SearchFlags) 0 : Poppler::Page::IgnoreCase);
			// TODO support Poppler::Page::WholeWords
			hits->swap(tmp);
#endif
#ifdef DEBUG
			if (hits->size() > 0) {
				cerr << hits->size() << " hits on page " << page << endl;
			}
#endif
			delete p;

			// clean up when interrupted
			if (stop || die) {
				delete hits;
				break;
			}

			if (hits->size() > 0) {
				hit_count += hits->size();
				emit search_done(page, hits);
			} else {
				delete hits;
			}

			// update progress label next to the search bar
			int percent;
			if (forward) {
				percent = page + bar->doc->numPages() - start;
			} else {
				percent = start + bar->doc->numPages() - page;
			}
			percent = (percent % bar->doc->numPages()) * 100 / bar->doc->numPages();
			QString progress = QString("[%1] %2\% searched, %3 hits")
				.arg(has_upper_case ? "Case" : "no case")
				.arg(percent)
				.arg(hit_count);
			emit update_label_text(progress);

			if (forward) {
				if (++page == bar->doc->numPages()) {
					page = 0;
				}
			} else {
				if (--page == -1) {
					page = bar->doc->numPages() - 1;
				}
			}
		} while (page != start);
#ifdef DEBUG
		cerr << "done!" << endl;
#endif
		emit update_label_text(QString("[%1] done, %2 hits")
				.arg(has_upper_case ? "Case" : "no case")
				.arg(hit_count));
	}
}
Example #24
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;
}
void InsertLinkTableDialog::on_addButton_clicked()
{
    QList<QTableWidgetItem *> aItems=ui->sourceTableWidget->selectedItems();
    QList<int> rows;

    for (int i=0; i<aItems.length(); i++)
    {
        if (!rows.contains(aItems.at(i)->row()))
        {
            rows.append(aItems.at(i)->row());
        }
    }

    for (int e=0; e<rows.length()-1; e++)
    {
        int min=rows.at(e);
        int minIndex=e;

        for (int i=e+1; i<rows.length(); i++)
        {
            if (rows.at(i)<min)
            {
                min=rows.at(i);
                minIndex=i;
            }
        }

        rows.swap(e, minIndex);
    }

    for (int i=0; i<rows.length(); i++)
    {
        int aSourceRow=rows.at(i);
        int aDestRow=-1;

        if (ui->beginRadioButton->isChecked())
        {
            aDestRow=mBeginPos;
            mBeginPos++;
        }
        else
        if (ui->beforeRadioButton->isChecked())
        {
            aDestRow=mDestTable->ui->dataTableWidget->currentRow();
            mBeginPos=0;
        }
        else
        if (ui->afterRadioButton->isChecked())
        {
            aDestRow=mDestTable->ui->dataTableWidget->currentRow()+1;
            mBeginPos=0;
        }
        else
        if (ui->endRadioButton->isChecked())
        {
            aDestRow=mDestTable->ui->dataTableWidget->rowCount();
            mBeginPos=0;
        }

        if (ui->sourceTableWidget->itemDelegateForRow(aSourceRow))
        {
            mDestTable->insertMiddleRow(aDestRow);

            mDestTable->ui->dataTableWidget->item(aDestRow, 0)->setText(ui->sourceTableWidget->item(aSourceRow, 0)->text());
        }
        else
        {
            mDestTable->insertRow(aDestRow);

            for (int j=0; j<ui->sourceTableWidget->columnCount() && j<mDestTable->ui->dataTableWidget->columnCount(); j++)
            {
                EColumnType aDestColumnType=mDestTable->typeColumns.at(j).column->type();
                EColumnType aSourceColumnType=mSourceTable->typeColumns.at(j).column->type();

                if (aDestColumnType==ctInteger)
                {
                    if (!((IntegerColumn*)mDestTable->typeColumns.at(j).column)->mIsAutoInc)
                    {
                        if (aSourceColumnType==ctInteger)
                        {
                            QString aText=ui->sourceTableWidget->item(aSourceRow, j)->text();

                            int removeBefore=0;
                            int removeAfter=0;

                            if (!((IntegerColumn*)mSourceTable->typeColumns.at(j).column)->mSplitRows)
                            {
                                removeBefore=((IntegerColumn*)mSourceTable->typeColumns.at(j).column)->mPrefix.length();
                                removeAfter=((IntegerColumn*)mSourceTable->typeColumns.at(j).column)->mPostfix.length();
                            }

                            aText.remove(aText.length()-removeAfter, removeAfter);
                            aText.remove(0, removeBefore);

                            double aValue=aText.toDouble();

                            if (((IntegerColumn*)mDestTable->typeColumns.at(j).column)->mSplitRows)
                            {
                                mDestTable->ui->dataTableWidget->item(aDestRow, j)->setText(QString::number(aValue, 'f', ((IntegerColumn*)mDestTable->typeColumns.at(j).column)->mDecimals));
                            }
                            else
                            {
                                mDestTable->ui->dataTableWidget->item(aDestRow, j)->setText(
                                                                                            ((IntegerColumn*)mDestTable->typeColumns.at(j).column)->mPrefix+
                                                                                            QString::number(aValue, 'f', ((IntegerColumn*)mDestTable->typeColumns.at(j).column)->mDecimals)+
                                                                                            ((IntegerColumn*)mDestTable->typeColumns.at(j).column)->mPostfix);
                            }
                        }
                        else
                        {
                            bool ok=true;
                            double aValue;

                            if (aSourceColumnType==ctBool)
                            {
                                if (ui->sourceTableWidget->item(aSourceRow, j)->checkState()==Qt::Checked)
                                {
                                    aValue=1;
                                }
                                else
                                {
                                    aValue=0;
                                }
                            }
                            else
                            {
                                aValue=ui->sourceTableWidget->item(aSourceRow, j)->text().toDouble(&ok);
                            }

                            if (ok)
                            {
                                if (((IntegerColumn*)mDestTable->typeColumns.at(j).column)->mSplitRows)
                                {
                                    mDestTable->ui->dataTableWidget->item(aDestRow, j)->setText(QString::number(aValue, 'f', ((IntegerColumn*)mDestTable->typeColumns.at(j).column)->mDecimals));
                                }
                                else
                                {
                                    mDestTable->ui->dataTableWidget->item(aDestRow, j)->setText(
                                                                                                ((IntegerColumn*)mDestTable->typeColumns.at(j).column)->mPrefix+
                                                                                                QString::number(aValue, 'f', ((IntegerColumn*)mDestTable->typeColumns.at(j).column)->mDecimals)+
                                                                                                ((IntegerColumn*)mDestTable->typeColumns.at(j).column)->mPostfix);
                                }
                            }
                        }
                    }
                }
                else
                if (aDestColumnType==ctString || aDestColumnType==ctList || aDestColumnType==ctExtendedList)
                {
                    if (aSourceColumnType==ctBool)
                    {
                        if (ui->sourceTableWidget->item(aSourceRow, j)->checkState()==Qt::Checked)
                        {
                            mDestTable->ui->dataTableWidget->item(aDestRow, j)->setText("1");
                        }
                        else
                        {
                            mDestTable->ui->dataTableWidget->item(aDestRow, j)->setText("0");
                        }
                    }
                    else
                    {
                        mDestTable->ui->dataTableWidget->item(aDestRow, j)->setText(ui->sourceTableWidget->item(aSourceRow, j)->text());
                    }
                }
                else
                if (aDestColumnType==ctBool)
                {
                    if (aSourceColumnType==ctBool)
                    {
                        mDestTable->ui->dataTableWidget->item(aDestRow, j)->setCheckState(ui->sourceTableWidget->item(aSourceRow, j)->checkState());
                    }
                    else
                    {
                        if (ui->sourceTableWidget->item(aSourceRow, j)->text()=="1")
                        {
                            mDestTable->ui->dataTableWidget->item(aDestRow, j)->setCheckState(Qt::Checked);
                        }
                        else
                        if (ui->sourceTableWidget->item(aSourceRow, j)->text()=="0")
                        {
                            mDestTable->ui->dataTableWidget->item(aDestRow, j)->setCheckState(Qt::Unchecked);
                        }
                    }
                }
                else
                if (aDestColumnType==ctDate)
                {
                    QDate aDate=QDate::fromString(ui->sourceTableWidget->item(aSourceRow, j)->text(), "dd.MM.yyyy");

                    if (aDate.isValid())
                    {
                        mDestTable->ui->dataTableWidget->item(aDestRow, j)->setText(ui->sourceTableWidget->item(aSourceRow, j)->text());
                    }
                }
                else
                if (aDestColumnType==ctTime)
                {
                    QTime aTime=QTime::fromString(ui->sourceTableWidget->item(aSourceRow, j)->text(), "h:mm:ss");

                    if (aTime.isValid())
                    {
                        mDestTable->ui->dataTableWidget->item(aDestRow, j)->setText(ui->sourceTableWidget->item(aSourceRow, j)->text());
                    }
                }
            }
        }
    }
}
Example #26
0
void
BiasSolver::geneticOptimize( SolverList *list,
                             int iterationLimit,
                             bool updateStatus )
{
    Q_UNUSED( list );
    Q_UNUSED( iterationLimit );
    Q_UNUSED( updateStatus );

    /**
     * Here we attempt to produce an optimal playlist using a genetic algorithm.
     * The basic steps:
     *
     *   1. Generate a population of playlists using generateInitialPlaylist.
     *
     * REPEAT:
     *   2. Choose a portion of that population to reproduce. The better the
     *      playlist (the lower the energy) the more likely it is to reproduce.
     *   3. The mating population playlists are mixed with each other producing
     *      offspring playlists.
     *   4. The worst playlists in the population are thrown out and replaced
     *      with the new offspring.
     */
#if 0

    // 1.  Generate initial population
    QList<SolverList> population;
    SolverList playlist;
    while( population.size() < GA_POPULATION_SIZE )
    {
        // TODO: OPTIMIZATION: most of the time spend solving now is spent
        // getting Meta::Tracks, since we request so many with this. Experiment
        // with lowering the population size, or finding a faster way to get a
        // bunch of random tracks.
        playlist = generateInitialPlaylist();

        playlist.removeAll( Meta::TrackPtr() );

        // test for the empty collection case
        if( playlist.empty() )
        {
            warning() << "Empty collection, aborting.";
            return Meta::TrackList();
        }

        double plEnergy = playlist->energy();

        if( plEnergy < epsilon() ) // no need to continue if we already found an optimal playlist
            return playlist;

        population.append( playlist );
    }

    qSort( population ); // sort the population by energy.


    double prevMin = 0.0;
    int giveUpCount = 0;
    int i = iterationLimit;
    QList<int> matingPopulation;
    while( i-- && population.first().energy >= epsilon() && !m_abortRequested )
    {
        // Sometime the optimal playlist can't have an energy of 0.0, or the
        // algorithm just gets stuck. So if the energy hasn't changed after
        // GIVE_UP_LIMIT iterations, we assume we bail out.
        if( population.first().energy == prevMin )
            giveUpCount++;
        else
        {
            prevMin = population.first().energy;
            giveUpCount = 0;
        }

        if( giveUpCount >= GA_GIVE_UP_LIMIT )
            break;


        // status updates
        if( updateStatus && i % 5 == 0 )
        {
            int progress = (int)(100.0 * (1.0 - population.first().energy));
            emit statusUpdate( progress >= 0 ? progress : 0 );
        }

        debug() << "GA: min E = " << population.first().energy;
        debug() << "GA: max E = " << population.last().energy;



        // 2. Choose the portion of the population to reproduce.
        matingPopulation = generateMatingPopulation( population );

        // randomize the order of the mating population so we don't get the same
        // playlists mating over and over
        int m = matingPopulation.size();
        while( m > 1 )
        {
            int k = KRandom::random() % m;
            --m;
            matingPopulation.swap( m, k );
        }

        QList<Meta::TrackList> offspring;



        // (I'm hanging on to code for now, until I do more testing.)
        // reproduce using single point crossover
#if 0
        for( int j = 0; j < matingPopulation.size(); ++j )
        {
            int parent1 = matingPopulation[j];
            int parent2 = j == 0 ? matingPopulation.last() : matingPopulation[j-1];

            Meta::TrackList child1, child2;
            int locus = KRandom::random() % m_n;

            child1 += population[parent1].trackList.mid( 0, locus );
            child1 += population[parent2].trackList.mid( locus );

            child2 += population[parent2].trackList.mid( 0, locus );
            child2 += population[parent1].trackList.mid( locus );

            offspring += child1;
            offspring += child2;
        }
#endif
        
        // 3. Reproduce (using uniform crossover).
        for( int j = 0; j < matingPopulation.size(); ++j )
        {
            int parent1 = matingPopulation[j];
            int parent2 = j == 0 ? matingPopulation.last() : matingPopulation[j-1];

            Meta::TrackList child1, child2;

            for( int k = 0; k < m_n; ++k )
            {
                if( KRandom::random() < RAND_MAX/2 )
                {
                    child1.append( population[parent1].trackList[k] );
                    child2.append( population[parent2].trackList[k] );
                }
                else
                {
                    child1.append( population[parent2].trackList[k] );
                    child2.append( population[parent1].trackList[k] );
                }
            }

            offspring += child1;
            offspring += child2;
        }


        // 4. Replace the worst in the population with the offspring.
        int j = population.size() - 1;
        foreach( const Meta::TrackList &p, offspring )
        {
            // TODO: try introducing mutations to the offspring here.

            population[j--] = SolverList( p, energy(p) );
        }

        qSort( population ); // sort playlists by energy
    }
Example #27
0
// функция распределения процессов на заданное количество процессоров
QList<QPair<QString,QString> > Graph::dealingProcess(QList<QPair<QString,QString> > procList, int prCount)
{
    // нахождение среднего времени выполнения всех процессов
    double t0 = 0;
    for (int i = 0; i < procList.count() ; i++)
        t0 += procList[i].second.toInt();
    t0 /= prCount;

    // сортировка процессов в порядке увеличения времени выпонения
    for (int i = 0 ; i < procList.count()-1 ; i++)
    {
        if (procList[i].second.toInt() > procList[i+1].second.toInt())
        {
            procList.swap(i,i+1);
            i=-1;
        }
    }

    double ds = 0;
    int index;    
    // нахождение позиции для начала поиска процессов
    for (int i = 0; i < procList.count() ; i++)
    {
        ds += procList[i].second.toInt();
        if (ds > t0)
        {
            index = i;
            break;
        }
    }  
    // создание двоичной строки
    QStringList mLine;
    for (int i = 0; i < procList.count() ; i++)
    {
        if (i == index)
            mLine << "1";
        else
            mLine << "0";
    }
    double min = t0+1;
    QStringList minMLine;
    bool cont = true;
    // выполнять увеличение строки пока не будет найдено время ближайшее к минимальному
    while(cont)
    {       
        // нахождение разницы среднего и текущего времени выполения процессов
        double sd=0;
        for (int i = 0; i < mLine.count() ; i++)
        {
            if (mLine[i] == "1")
                sd += procList[i].second.toInt();
        }
        sd -= t0;

        // если минимальное значение больше модуля разности
        if (min >= fabs(sd))
        {
            // присвоить минимальному значению новое значение
            min = fabs(sd);
            // установить новую минимаьлную двоичную строку
            minMLine = mLine;
        }        
        // если разница равна нулю значит было найдено наилучшее распределение процессов
        if (sd == 0)
        {
            cont = false;
            break;
        }
        // если разница больше нуля
        if (sd > 0)
        {
            // если в двоичной строке одна единица значит распределить этот процесс
            if (mLine.count("1") == 1)
            {
                cont = false;
                break;
            }
            // иначе если более одной единицы
            else if (mLine.count("1") > 1)
            {               
                // если последниий символ двоичной строки единица то поиск продолжать бессмысленно
                if (mLine.last() == "1")
                {
                    cont = false;
                    break;
                }
                // иначе произвести преобразование двоичной строки
                else
                {
                    // найти индекс второй единицы
                    int firInd = mLine.indexOf("1");
                    int secInd = mLine.indexOf("1",firInd+1);
                    int thInd = mLine.indexOf("0",secInd+1);
                    secInd = thInd-1;
                    // все значения строки до индекса занулить, а следующее установить равным единице
                    for (int i = 0 ; i <= secInd ; i++)
                    {
                        if (mLine[i] == "1")
                            mLine[i] = "0";
                    }
                    mLine[secInd+1] = "1";                    
                    continue;
                }
            }
        }        
        // произвести увеличение двоичной строки на единицу
        for (int i = 0 ; i < mLine.count() ; i++)
        {
            if( mLine[i] == "1")
            {
                mLine[i] = "0";
            }
            else
            {
                mLine[i] = "1";
                break;
            }
        }
        // если двоичная строка не содержит единицу прекратить поиск
        if (!mLine.contains("1"))
            cont = false;
    }

    // проанализировать минимальное значение и минимальную строку
    QList<QPair<QString,QString> > result;
    for (int i = 0 ; i < minMLine.count() ; i++)
    {
        // добавить к списку результатов процессы соответствующие единице в строке
        if (minMLine[i] == "1")
            result << procList[i];
    }
    // возвратить распределение
    return result;
}