void ConnectedComponentsLabeling::Run(){
    //Avoid possible problems (avoid more pixels than there can be sub_objects)
    if ((m_image_ptr->width()*m_image_ptr->height()) > UINT_MAX){
        return;
    }

    m_image = QImage(m_image_ptr->width(), m_image_ptr->height(),
            QImage::Format_RGB888);

    //Used to store subobjects to witch a pixel can belong
    struct subobject{
        unsigned int pixels;
        unsigned int parent_subobject;
    };

    //Init subobjects list
    QList<subobject> subobjects;
    subobject dummy;
    subobjects.append(dummy); //dummy to avoid 0

    //List that tells to witch sub object a pixel belongs
    QList<unsigned int> pixel_subobject_nr;

    QColor current, left, top, left_top, right_top;

    //Caching
    for (int y=0; y <m_image_ptr->height() ; y++){
        for (int x=0; x < m_image_ptr->width(); x++){
            bool l=true, t=true, lt=true, rt=true;

            //shift old values + boundry check
            if (x > 0){
                left = current;

                if (y > 0){
                    left_top = top;
                } else {
                    //no pixel set false
                    lt = false;
                }
            } else {
                //no pixel so set false
                l = false;
                lt = false;
            }

            if(y > 0){
                if (x > 0){
                    top = right_top;
                } else {
                    top = QColor(m_image_ptr->pixel(x,y-1));
                }

                if(x < m_image_ptr->width()-1){
                    right_top = QColor(m_image_ptr->pixel(x+1,y-1));
                } else {
                    //no pixel so set false
                    rt = false;
                }
            } else {
                //no pixel so set false
                t = false;
                rt = false;
            }

            //get new current value
            current = QColor(m_image_ptr->pixel(x,y));

            //evaluate values
            if (l) l = evaluate(left, current);
            if (t) t = evaluate(top, current);
            if (m_diagonalValue){
                if (lt) lt = evaluate(left_top, current);
                if (rt) rt = evaluate(right_top, current);
            } else {
                lt = false;
                rt = false;
            }

            //perform actions based on evaluation
            if (l && !t && !lt && !rt){
                //Current pixel belongs to subobject of pixel on the left
                subobjects.last().pixels++;
            } else {
                //Generate new sub object
                subobject new_subobject;
                new_subobject.pixels = 1;
                new_subobject.parent_subobject = 0;
                subobjects.append(new_subobject);

                QList<unsigned int> connected_subobjects;

                if (lt){
                    unsigned int lt_index = (x-1) +
                        ((y-1)*m_image_ptr->width());
                    unsigned int lt_subobject_index =
                        pixel_subobject_nr[lt_index];
                    while(subobjects[lt_subobject_index].parent_subobject != 0){
                        lt_subobject_index =
                            subobjects[lt_subobject_index].parent_subobject;
                    }
                    connected_subobjects.append(lt_subobject_index);
                }

                if (t){
                    unsigned int t_index = x + ((y-1)*m_image_ptr->width());
                    unsigned int t_subobject_index =
                        pixel_subobject_nr[t_index];
                    while(subobjects[t_subobject_index].parent_subobject != 0){
                        t_subobject_index =
                            subobjects[t_subobject_index].parent_subobject;
                    }
                    connected_subobjects.append(t_subobject_index);
                }

                if (rt){
                    unsigned int rt_index = (x+1) +
                        ((y-1)*m_image_ptr->width());
                    unsigned int rt_subobject_index =
                        pixel_subobject_nr[rt_index];
                    while(subobjects[rt_subobject_index].parent_subobject != 0){
                        rt_subobject_index =
                            subobjects[rt_subobject_index].parent_subobject;
                    }
                    connected_subobjects.append(rt_subobject_index);
                }

                if (l){
                    unsigned int l_index = (x-1) + (y*m_image_ptr->width());
                    unsigned int l_subobject_index =
                        pixel_subobject_nr[l_index];
                    while(subobjects[l_subobject_index].parent_subobject != 0){
                        l_subobject_index =
                            subobjects[l_subobject_index].parent_subobject;
                    }
                    connected_subobjects.append(l_subobject_index);
                }

                //If there are linked subobjects make connection
                if (!connected_subobjects.isEmpty()){

                    //find subobject whit lowest index
                    qSort(connected_subobjects);

                    //add this subobject to bigger object
                    subobjects.last().parent_subobject =
                        connected_subobjects.first();
                    subobjects.last().pixels = 0;
                    subobjects[connected_subobjects.first()].pixels++;

                    //add other connected sub_objects to bigger object
                    for (int i=1; i<connected_subobjects.size(); i++){
                        //prevent adding subobjects to itself
                        if (connected_subobjects[i] !=
                                connected_subobjects.first()){

                            //Add subobject
                            subobjects[connected_subobjects[i]].parent_subobject
                                = connected_subobjects.first();
                            subobjects[connected_subobjects.first()].pixels +=
                                subobjects[connected_subobjects[i]].pixels;
                            subobjects[connected_subobjects[i]].pixels = 0;
                        }
                    }
                }
            }
            pixel_subobject_nr.append(subobjects.size()-1);
        }
    }

    //Init color lookup table
    QList<QRgb> color_table;

    //Add black for objects with to few pixels
    color_table.append(0);

    //Fill the color lookup table
    for (int i=1; i<subobjects.size(); i++){

        //generate new color
        if (subobjects[i].parent_subobject == 0){

            //check object size
            if (subobjects[i].pixels > m_minWeightValue){
                int r = qrand()%255;
                int g = qrand()%255;
                int b = qrand()%255;
                QColor new_color(r,g,b);
                color_table.append(new_color.rgb());
            } else {
                color_table.append(0);
            }
        } else {
            color_table.append(color_table[subobjects[i].parent_subobject]);
        }
    }

    //Make new image
    for (int y=0; y < m_image_ptr->height(); y++){
        for (int x=0; x < m_image_ptr->width(); x++){
            m_image.setPixel(x,y, color_table[pixel_subobject_nr[x +
                    y*m_image_ptr->width()]]);
        }
    }
}
void MusicUserRecordWidget::changeVerificationCodeT()
{
    ui->verificationCode->setText(QString::number(qrand()).leftJustified(5, '0'));
}
Exemple #3
0
Post::Post(QObject *parent) : QObject(parent), d_ptr(new PostPrivate(this))
{
	Q_D(Post);
	ins = this;
	setObjectName("Post");

	auto avProcess = [this](QNetworkReply *reply){
		Q_D(Post);
		Task &task = d->queue.head();
		switch (task.state){
		case None:{
			QString api("http://interface.%1/dmpost");
			api = api.arg(Utils::customUrl(Utils::Bilibili));
			task.request.setUrl(api);
			task.request.setHeader(QNetworkRequest::ContentTypeHeader, "application/x-www-form-urlencoded");
			const Comment &c = task.comment;
			QUrlQuery params;
			params.addQueryItem("cid", QFileInfo(task.target->source).baseName());
			params.addQueryItem("date", QDateTime::currentDateTime().toString("yyyy-MM-dd hh:mm:ss"));
			params.addQueryItem("pool", "0");
			params.addQueryItem("playTime", QString::number(c.time / 1000.0, 'f', 4));
			params.addQueryItem("color", QString::number(c.color));
			params.addQueryItem("fontsize", QString::number(c.font));
			params.addQueryItem("message", c.string);
			params.addQueryItem("rnd", QString::number(qrand()));
			params.addQueryItem("mode", QString::number(c.mode));
			task.data = QUrl::toPercentEncoding(params.query(QUrl::FullyEncoded), "%=&", "-.~_");
			task.state = Code;
			forward();
			break;
		}
		case Code:{
			int code = QString(reply->readAll()).toInt();
			emit stateChanged(task.state = code > 0 ? None : code);
			dequeue();
			break;
		}
		}
	};
	auto avRegular = [](QString code){
		static QRegularExpression r("a(v(\\d+([#_])?(\\d+)?)?)?");
		r.setPatternOptions(QRegularExpression::CaseInsensitiveOption);
		return r.match(code).capturedLength() == code.length();
	};
	d->pool.append({ avRegular, 0, avProcess });

	connect(this, &Post::stateChanged, [this](int code){
		switch (code){
		case None:
		case Code:
			break;
		default:
		{
			Q_D(Post);
			if (!d->tryNext()){
				emit errorOccured(code);
			}
			break;
		}
		}
	});
}
// TODO: This looks like should be ported to C code. or a big part of it.
bool DivelogsDeWebServices::prepare_dives_for_divelogs(const QString &tempfile, const bool selected)
{
	static const char errPrefix[] = "divelog.de-upload:";
	if (!amount_selected) {
		report_error(tr("no dives were selected").toUtf8());
		return false;
	}

	xsltStylesheetPtr xslt = NULL;
	struct zip *zip;

	xslt = get_stylesheet("divelogs-export.xslt");
	if (!xslt) {
		qDebug() << errPrefix << "missing stylesheet";
		return false;
	}


	int error_code;
	zip = zip_open(QFile::encodeName(QDir::toNativeSeparators(tempfile)), ZIP_CREATE, &error_code);
	if (!zip) {
		char buffer[1024];
		zip_error_to_str(buffer, sizeof buffer, error_code, errno);
		report_error(tr("failed to create zip file for upload: %s").toUtf8(), buffer);
		return false;
	}

	/* walk the dive list in chronological order */
	int i;
	struct dive *dive;
	for_each_dive (i, dive) {
		FILE *f;
		char filename[PATH_MAX];
		int streamsize;
		char *membuf;
		xmlDoc *transformed;
		struct zip_source *s;

		/*
		 * Get the i'th dive in XML format so we can process it.
		 * We need to save to a file before we can reload it back into memory...
		 */
		if (selected && !dive->selected)
			continue;
		QString innerTmpFile = tempfile;
		QString tmpSuffix = QString::number(qrand() % 9999) + ".tmp";
		innerTmpFile.replace(".dld", tmpSuffix);
		f = subsurface_fopen(QFile::encodeName(QDir::toNativeSeparators(innerTmpFile)), "w+");
		if (!f) {
			report_error(tr("cannot create temporary file: %s").toUtf8(), qt_error_string().toUtf8().data());
			goto error_close_zip;
		}
		save_dive(f, dive);
		fseek(f, 0, SEEK_END);
		streamsize = ftell(f);
		rewind(f);

		membuf = (char *)malloc(streamsize + 1);
		if (!membuf || (streamsize = fread(membuf, 1, streamsize, f)) == 0) {
			report_error(tr("internal error: %s").toUtf8(), qt_error_string().toUtf8().data());
			fclose(f);
			free((void *)membuf);
			goto error_close_zip;
		}
		membuf[streamsize] = 0;
		fclose(f);
		unlink(QFile::encodeName(QDir::toNativeSeparators(innerTmpFile)));
		/*
		 * Parse the memory buffer into XML document and
		 * transform it to divelogs.de format, finally dumping
		 * the XML into a character buffer.
		 */
		xmlDoc *doc = xmlReadMemory(membuf, streamsize, "divelog", NULL, 0);
		if (!doc) {
			qWarning() << errPrefix << "could not parse back into memory the XML file we've just created!";
			report_error(tr("internal error").toUtf8());
			free((void *)membuf);
			goto error_close_zip;
		}
		free((void *)membuf);

		transformed = xsltApplyStylesheet(xslt, doc, NULL);
		xmlDocDumpMemory(transformed, (xmlChar **)&membuf, &streamsize);
		xmlFreeDoc(doc);
		xmlFreeDoc(transformed);

		/*
		 * Save the XML document into a zip file.
		 */
		snprintf(filename, PATH_MAX, "%d.xml", i + 1);
		s = zip_source_buffer(zip, membuf, streamsize, 1);
		if (s) {
			int64_t ret = zip_add(zip, filename, s);
			if (ret == -1)
				qDebug() << errPrefix << "failed to include dive:" << i;
		}
	}
/**
 * @brief GameMaster::losujWroga Metoda losująca przeciwnika z zadanej grupy.
 * @param grupa		indeks grupy, z której ma być losowany przeciwnik.
 * @return		Wskaźnik na wylosowanego przeciwnika.
 */
Enemy * GameMaster::generateEnemy(int enemyGroup)
{
	int idx = qrand() % enemyGroups_[enemyGroup]->size();
	return enemies_[enemyGroups_[enemyGroup]->at(idx)];
}
Exemple #6
0
bool DkUtils::compRandom(const QFileInfo&, const QFileInfo&) {

	return qrand() % 2 != 0;
}
Exemple #7
0
QVariant PayloadProtocol::fieldData(int index, FieldAttrib attrib,
        int streamIndex) const
{
    switch (index)
    {
        case payload_dataPattern:
            switch(attrib)
            {
                case FieldName:            
                    return QString("Data");
                case FieldValue:
                    return data.pattern();
                case FieldTextValue:
                    return QString(fieldData(index, FieldFrameValue, 
                            streamIndex).toByteArray().toHex());
                case FieldFrameValue:
                {
                    QByteArray fv;
                    int dataLen;

                    dataLen = protocolFrameSize(streamIndex);

                    // FIXME: Hack! Bad! Bad! Very Bad!!!
                    if (dataLen <= 0)
                        dataLen = 1;

                    fv.resize(dataLen+4);
                    switch(data.pattern_mode())
                    {
                        case OstProto::Payload::e_dp_fixed_word:
                            for (int i = 0; i < (dataLen/4)+1; i++)
                                qToBigEndian((quint32) data.pattern(), 
                                    (uchar*)(fv.data()+(i*4)) );
                            break;
                        case OstProto::Payload::e_dp_inc_byte:
                            for (int i = 0; i < dataLen; i++)
                                fv[i] = i % (0xFF + 1);
                            break;
                        case OstProto::Payload::e_dp_dec_byte:
                            for (int i = 0; i < dataLen; i++)
                                fv[i] = 0xFF - (i % (0xFF + 1));
                            break;
                        case OstProto::Payload::e_dp_random:
                            //! \todo (HIGH) cksum is incorrect for random pattern
                            for (int i = 0; i < dataLen; i++)
                                fv[i] =  qrand() % (0xFF + 1);
                            break;
                        default:
                            qWarning("Unhandled data pattern %d", 
                                data.pattern_mode());
                    }
                    fv.resize(dataLen);
                    return fv;
                }
                default:
                    break;
            }
            break;

        // Meta fields

        case payload_dataPatternMode:
            switch(attrib)
            {
                case FieldValue: return data.pattern_mode();
                default: break;
            }
            break;
        default:
            break;
    }

    return AbstractProtocol::fieldData(index, attrib, streamIndex);
}
QString TrustAI::askForChoice(const QString &, const QString &choice, const QVariant &) {
    QStringList choices = choice.split("+");
    return choices.at(qrand() % choices.length());
}
ServerPlayer *TrustAI::askForPlayerChosen(const QList<ServerPlayer *> &targets, const QString &reason) {
    Q_UNUSED(reason);

    int r = qrand() % targets.length();
    return targets.at(r);
}
Exemple #10
0
/**
 * @brief Icon::Icon
 *  Ikona o losowym kolorze i rozmiarze 10x10
 */
Icon::Icon()
{
    this->color = QColor((float)qrand()/RAND_MAX*255, (float)qrand()/RAND_MAX*255, (float)qrand()/RAND_MAX*255);
    this->geometry = Geometry(0, 0, 10, 10);
}
Card::Suit TrustAI::askForSuit(const QString &) {
    return Card::AllSuits[qrand() % 4];
}
bool DesktopWindow::pickWallpaper() {
    if(slideShowInterval_ <= 0
       || !QFileInfo(wallpaperDir_).isDir()) {
        return false;
    }

    QList<QByteArray> formats = QImageReader::supportedImageFormats();
    QStringList formatsFilters;
    for (const QByteArray& format: formats)
        formatsFilters << QString("*.") + format;
    QDir folder(wallpaperDir_);
    QStringList files = folder.entryList(formatsFilters,
                                         QDir::Files | QDir::NoDotAndDotDot,
                                         QDir::Name);
    if(!files.isEmpty()) {
       QString dir = wallpaperDir_ + QLatin1Char('/');
       if(!wallpaperRandomize_) {
           if(!lastSlide_.startsWith(dir)) { // not in the directory
               wallpaperFile_ = dir + files.first();
           }
           else {
               QString ls = lastSlide_.remove(0, dir.size());
               if(ls.isEmpty() // invalid
                  || ls.contains(QLatin1Char('/'))) { // in a subdirectory or invalid
                   wallpaperFile_ = dir + files.first();
               }
               else {
                   int index = files.indexOf(ls);
                   if(index == -1) { // removed or invalid
                       wallpaperFile_ = dir + files.first();
                   }
                   else {
                       wallpaperFile_ = dir + (index + 1 < files.size()
                                               ? files.at(index + 1)
                                               : files.first());
                   }
               }
           }
       }
       else {
           if(files.size() > 1) {
               if(lastSlide_.startsWith(dir)) {
                   QString ls = lastSlide_.remove(0, dir.size());
                   if(!ls.isEmpty() && !ls.contains(QLatin1Char('/')))
                       files.removeOne(ls); // choose from other images
               }
               // this is needed for the randomness, especially when choosing the first wallpaper
               qsrand((uint)QTime::currentTime().msec());
               int randomValue = qrand() % files.size();
               wallpaperFile_ = dir + files.at(randomValue);
           }
           else {
               wallpaperFile_ = dir + files.first();
           }
       }

       if (lastSlide_ != wallpaperFile_) {
           lastSlide_ = wallpaperFile_;
           Settings& settings = static_cast<Application*>(qApp)->settings();
           settings.setLastSlide(lastSlide_);
           return true;
       }
    }

  return false;
}
Exemple #13
0
void CountryByShape::postQuestion( QObject *gameObject )
{
    //Find a random placemark

    Q_ASSERT_X( d->m_countryNames, "CountryByShape::postQuestion",
                "CountryByShapePrivate::m_countryNames is NULL" );

    QVector<GeoDataPlacemark*> countryPlacemarks = d->m_countryNames->placemarkList();

    uint randomSeed = uint(QTime::currentTime().msec());
    qsrand( randomSeed );

    bool found = false;
    GeoDataPlacemark *placemark =0;
    GeoDataPoint *point = 0;
    GeoDataCoordinates coord;
    GeoDataLatLonAltBox box;
    QVariantList answerOptions;
    while ( !found ) {
        int randomIndex = qrand()%countryPlacemarks.size();
        placemark = countryPlacemarks[randomIndex];
        point = dynamic_cast<GeoDataPoint*>( placemark->geometry() );
        coord = point->coordinates();

        if ( point ) {
            /**
             * Find the country geometry and fetch corresponding
             * GeoDataLatLonAltBox to zoom in to that country so that
             * it fills the viewport.
             */

            Q_ASSERT_X( d->m_countryBoundaries, "CountryByShape::postQuestion",
                        "CountryByShapePrivate::m_countryBoundaries is NULL" );

            QVector<GeoDataFeature*>::Iterator i = d->m_countryBoundaries->begin();
            QVector<GeoDataFeature*>::Iterator const end = d->m_countryBoundaries->end();
            for ( ; i != end; ++i ) {
                GeoDataPlacemark *country = static_cast<GeoDataPlacemark*>( *i );

                GeoDataPolygon *polygon = dynamic_cast<GeoDataPolygon*>( country->geometry() );
                GeoDataLinearRing *linearring = dynamic_cast<GeoDataLinearRing*>( country->geometry() );
                GeoDataMultiGeometry *multigeom = dynamic_cast<GeoDataMultiGeometry*>( country->geometry() );

                if ( polygon &&
                    polygon->contains( coord ) &&
                    !d->m_continentsAndOceans.contains(country->name(), Qt::CaseSensitive) )
                {
                    box = polygon->latLonAltBox();
                    found = true;
                    break;
                }
                if ( linearring &&
                    linearring->contains( coord ) &&
                    !d->m_continentsAndOceans.contains(country->name(), Qt::CaseSensitive) )
                {
                    box = linearring->latLonAltBox();
                    found = true;
                    break;
                }
                if ( multigeom ) {
                    QVector<GeoDataGeometry*>::Iterator iter = multigeom->begin();
                    QVector<GeoDataGeometry*>::Iterator const end = multigeom->end();

                    for ( ; iter != end; ++iter ) {
                        GeoDataPolygon *poly  = dynamic_cast<GeoDataPolygon*>( *iter );
                        if ( poly &&
                            poly->contains( coord ) &&
                            !d->m_continentsAndOceans.contains(country->name(), Qt::CaseSensitive) )
                        {
                            box = poly->latLonAltBox();
                            found = true;
                            break;
                        }
                    }
                }
                if ( found ) {
                    break;
                }
            }
        }
    }
    d->m_marbleWidget->setHighlightEnabled( true );
    emit announceHighlight( coord.longitude(GeoDataCoordinates::Degree),
                            coord.latitude(GeoDataCoordinates::Degree),
                            GeoDataCoordinates::Degree );

    /**
     * Now disable the highlight feature so that
     * the user click doesn't disturbe the highlight
     * we did to ask question.
     */ 
    d->m_marbleWidget->setHighlightEnabled( false );

    d->m_marbleWidget->centerOn( box, true );

    answerOptions << placemark->name()
    << countryPlacemarks[qrand()%countryPlacemarks.size()]->name()
    << countryPlacemarks[qrand()%countryPlacemarks.size()]->name()
    << countryPlacemarks[qrand()%countryPlacemarks.size()]->name();

    // Randomize options in list answerOptions
    for ( int i = 0; i < answerOptions.size(); ++i ) {
        QVariant option = answerOptions.takeAt( qrand()%answerOptions.size() );
        answerOptions.append( option );
    }

    if ( gameObject ) {
        QMetaObject::invokeMethod( gameObject, "countryByShapeQuestion",
                                   Q_ARG(QVariant, QVariant(answerOptions)),
                                   Q_ARG(QVariant, QVariant(placemark->name())) );
    }
}
Exemple #14
0
                {
                    i++;
                }
                else
                {
                    i = m_randomArenaModeArenaList.erase(i);
                }
            }

            if(m_randomArenaModeArenaList.isEmpty())
            {
                m_randomArenaModeArenaList = arenasAvailable;
            }
        }

        int nIndex = (static_cast<double>(qrand()) / RAND_MAX) * m_randomArenaModeArenaList.count();
        if(nIndex < 0)
        {
            nIndex = 0;
        }
        else if(nIndex >= m_randomArenaModeArenaList.count())
        {
            nIndex = m_randomArenaModeArenaList.count() - 1;
        }
        filePath = m_randomArenaModeArenaList.at(nIndex);
        m_randomArenaModeArenaList.removeAt(nIndex);
    }
    else
    {
        filePath = QStandardPaths::locate(QStandardPaths::AppDataLocation, Settings::self()->arena());
    }
Exemple #15
0
int Apipa::rand(int min, int max)
{
	return ((((int)((double)qrand() / (double)RAND_MAX)) * (max - min + 1)) + min);
}
Exemple #16
0
void MyRenderWidget::random(){
    sec = qrand() % 60;
    min = qrand() % 60;
    hour = qrand() % 12;
    update();
}
Exemple #17
0
Tomahawk::result_ptr
TrackProxyModel::siblingItem( int itemsAway )
{
    qDebug() << Q_FUNC_INFO;

    QModelIndex idx = index( 0, 0 );
    if( rowCount() )
    {
        if ( m_shuffled )
        {
            // random mode is enabled
            // TODO come up with a clever random logic, that keeps track of previously played items
            idx = index( qrand() % rowCount(), 0 );
        }
        else if ( currentItem().isValid() )
        {
            idx = currentItem();

            // random mode is disabled
            if ( m_repeatMode == PlaylistInterface::RepeatOne )
            {
                // repeat one track
                idx = index( idx.row(), 0 );
            }
            else
            {
                // keep progressing through the playlist normally
                idx = index( idx.row() + itemsAway, 0 );
            }
        }
    }

    if ( !idx.isValid() && m_repeatMode == PlaylistInterface::RepeatAll )
    {
        // repeat all tracks
        if ( itemsAway > 0 )
        {
            // reset to first item
            idx = index( 0, 0 );
        }
        else
        {
            // reset to last item
            idx = index( rowCount() - 1, 0 );
        }
    }

    // Try to find the next available PlaylistItem (with results)
    if ( idx.isValid() ) do
    {
        TrackModelItem* item = itemFromIndex( mapToSource( idx ) );
        qDebug() << item->query()->toString();
        if ( item && item->query()->playable() )
        {
            qDebug() << "Next PlaylistItem found:" << item->query()->toString() << item->query()->results().at( 0 )->url();
            setCurrentItem( idx );
            return item->query()->results().at( 0 );
        }

        idx = index( idx.row() + ( itemsAway > 0 ? 1 : -1 ), 0 );
    }
    while ( idx.isValid() );

    setCurrentItem( QModelIndex() );
    return Tomahawk::result_ptr();
}
Exemple #18
0
Market::Market() : Building(Building::Market)
{
  m_pos.setSize(QSize(100 + (qrand()%100),120 + (qrand()%80 - 40)));
  qWarning() << m_pos;
}
Exemple #19
0
bool rand2()
{
	return (qrand() & 0x1) == 0x1;
}
 SinusIn::SinusIn(QObject *parent) :
     BrainIn(-1, 1, parent), deg(0)
 {
     inc = 1.0f + (btScalar)qrand()/RAND_MAX * 4;
     offset = (btScalar)qrand()/RAND_MAX*360;
 }
Exemple #21
0
static QList<double> _calcJenksBreaks( QList<double> values, int classes,
                                       double minimum, double maximum,
                                       int maximumSize = 1000 )
{
  // Jenks Optimal (Natural Breaks) algorithm
  // Based on the Jenks algorithm from the 'classInt' package available for
  // the R statistical prgramming language, and from Python code from here:
  // http://danieljlewis.org/2010/06/07/jenks-natural-breaks-algorithm-in-python/
  // and is based on a JAVA and Fortran code available here:
  // https://stat.ethz.ch/pipermail/r-sig-geo/2006-March/000811.html

  // Returns class breaks such that classes are internally homogeneous while
  // assuring heterogeneity among classes.

  if ( classes <= 1 )
  {
    return QList<double>() << maximum;
  }

  if ( classes >= values.size() )
  {
    return values;
  }

  QVector<double> sample;

  // if we have lots of values, we need to take a random sample
  if ( values.size() > maximumSize )
  {
    // for now, sample at least maximumSize values or a 10% sample, whichever
    // is larger. This will produce a more representative sample for very large
    // layers, but could end up being computationally intensive...

    qsrand( time( 0 ) );

    sample.resize( qMax( maximumSize, values.size() / 10 ) );

    QgsDebugMsg( QString( "natural breaks (jenks) sample size: %1" ).arg( sample.size() ) );
    QgsDebugMsg( QString( "values:%1" ).arg( values.size() ) );

    sample[ 0 ] = minimum;
    sample[ 1 ] = maximum;;
    for ( int i = 2; i < sample.size(); i++ )
    {
      // pick a random integer from 0 to n
      double r = qrand();
      int j = floor( r / RAND_MAX * ( values.size() - 1 ) );
      sample[ i ] = values[ j ];
    }
  }
  else
  {
    sample = values.toVector();
  }

  int n = sample.size();

  // sort the sample values
  qSort( sample );

  QVector< QVector<int> > matrixOne( n + 1 );
  QVector< QVector<double> > matrixTwo( n + 1 );

  for ( int i = 0; i <= n; i++ )
  {
    matrixOne[i].resize( classes + 1 );
    matrixTwo[i].resize( classes + 1 );
  }

  for ( int i = 1; i <= classes; i++ )
  {
    matrixOne[0][i] = 1;
    matrixOne[1][i] = 1;
    matrixTwo[0][i] = 0.0;
    for ( int j = 2; j <= n; j++ )
    {
      matrixTwo[j][i] = std::numeric_limits<double>::max();
    }
  }

  for ( int l = 2; l <= n; l++ )
  {
    double s1 = 0.0;
    double s2 = 0.0;
    int w = 0;

    double v = 0.0;

    for ( int m = 1; m <= l; m++ )
    {
      int i3 = l - m + 1;

      double val = sample[ i3 - 1 ];

      s2 += val * val;
      s1 += val;
      w++;

      v = s2 - ( s1 * s1 ) / ( double ) w;
      int i4 = i3 - 1;
      if ( i4 != 0 )
      {
        for ( int j = 2; j <= classes; j++ )
        {
          if ( matrixTwo[l][j] >= v + matrixTwo[i4][j - 1] )
          {
            matrixOne[l][j] = i4;
            matrixTwo[l][j] = v + matrixTwo[i4][j - 1];
          }
        }
      }
    }
    matrixOne[l][1] = 1;
    matrixTwo[l][1] = v;
  }

  QVector<double> breaks( classes );
  breaks[classes-1] = sample[n-1];

  for ( int j = classes, k = n; j >= 2; j-- )
  {
    int id = matrixOne[k][j] - 1;
    breaks[j - 2] = sample[id];
    k = matrixOne[k][j] - 1;
  }

  return breaks.toList();
} //_calcJenksBreaks
Exemple #22
0
int GameModel::randInt(int low, int high)
    {
    return qrand() % ((high + 1) - low) + low;
    }
/**
 * @brief GameMaster::wykonajQuest	Wykonuje zadanie o podanym id.
 *					Działanie jest uzależnione od stopnia wykonania zadania.
 *					Metoda zakłada, że zadanie o podany
 * @param gracz		dane gracza, wykonującego zadanie
 * @param id		id zadania
 */
void GameMaster::doQuest(int questId)
{
	currentPlayer_->setHasFoughtRecently(false);
	int questIndex = 0;
	while (currentPlayer_->quest(questIndex)->id() != questId)
		++questIndex;

	Quest *quest = currentPlayer_->quest(questIndex);
	switch (quest->type()) {
	case przynies:
		if (quest->isPartiallyCompleted()) {
			grantPrize(currentPlayer_, quest->prize(), false);
			currentPlayer_->removeQuest(questId);
			determinePossibleActions();
			actionPanel_->displayActions(possibleActions_);
		} else {
			quest->setIsPartiallyCompleted(true);
			quest->setTargetField(quest->employerField());
			gameCycle_->endTurn();
		}
		break;
	case odnajdz: {
		if (quest->isPartiallyCompleted()) {
			grantPrize(currentPlayer_, quest->prize(), false);
			currentPlayer_->removeQuest(questId);
			determinePossibleActions();
			actionPanel_->displayActions(possibleActions_);
			break;
		}
		int chance = BAZOWA_SZANSA_NA_ODNALEZIENIE + currentPlayer_->perception() * BONUS_Z_PERCEPCJI;
		bool success = qrand() % 100 < chance;
		QMessageBox::information(
			gameCycle_->mainWindow(),
			quest->title(),
			success ?
			QString::fromUtf8("Udało Ci się wykonać zadanie.") :
			QString::fromUtf8("Niestety, nie udało Ci się wykonać zadania.")
		);

		if (success)  {
			if (quest->isReturnRequired()) {
				quest->setIsPartiallyCompleted(true);
				quest->setTargetField(quest->employerField());
			} else {
				grantPrize(currentPlayer_, quest->prize(), true);
				currentPlayer_->removeQuest(questId);
			}
		}
		gameCycle_->endTurn();
		break;
	}
	case pokonaj:
		if (quest->isPartiallyCompleted()) {
			grantPrize(currentPlayer_, quest->prize(), false);
			currentPlayer_->removeQuest(questId);
			determinePossibleActions();
			actionPanel_->displayActions(possibleActions_);
		} else {
			currentQuest_ = quest;
			startFight(QuestEnemy);
		}
		break;
	}
}
QString KQOAuthRequestPrivate::oauthNonce() const {
    // This is basically for unit tests only. In most cases we don't set the nonce beforehand.
    return QString::number(qrand());
}
Exemple #25
0
void TextContent::drawContent(QPainter * painter, const QRect & targetRect, Qt::AspectRatioMode ratio)
{
    Q_UNUSED(ratio)

    // check whether we're drawing shaped
    const bool shapedPaint = hasShape() && !m_shapeRect.isEmpty();
    QPointF shapeOffset = m_shapeRect.topLeft();

    // scale painter for adapting the Text Rect to the Contents Rect
    QRect sourceRect = shapedPaint ? m_shapeRect : m_textRect;
    painter->save();
    painter->translate(targetRect.topLeft());
    if (sourceRect.width() > 0 && sourceRect.height() > 0) {
        qreal xScale = (qreal)targetRect.width() / (qreal)sourceRect.width();
        qreal yScale = (qreal)targetRect.height() / (qreal)sourceRect.height();
        if (!qFuzzyCompare(xScale, (qreal)1.0) || !qFuzzyCompare(yScale, (qreal)1.0))
            painter->scale(xScale, yScale);
    }

    // shape
    //const bool drawHovering = RenderOpts::HQRendering ? false : isSelected();
    if (shapedPaint)
        painter->translate(-shapeOffset);
    //if (shapedPaint && drawHovering)
    //    painter->strokePath(m_shapePath, QPen(Qt::red, 0));

    // TEMP - for PDF exporting - standard rich text document drawing
    if (RenderOpts::PDFExporting) {
        if (shapedPaint)
            QMessageBox::information(0, tr("PDF Export Warning"), tr("Shaped text could not be exported in PDF"), QMessageBox::Ok);
        QAbstractTextDocumentLayout::PaintContext pCtx;
        m_text->documentLayout()->draw(painter, pCtx);
    } else {
        // manual drawing
        QPointF blockPos = shapedPaint ? QPointF(0, 0) : -m_textRect.topLeft();

        // 1. for each Text Block
        int blockRectIdx = 0;
        for (QTextBlock tb = m_text->begin(); tb.isValid(); tb = tb.next()) {
            if (!tb.isVisible() || blockRectIdx > m_blockRects.size())
                continue;

            // 1.1. compute text insertion position
            const QRect & blockRect = m_blockRects[blockRectIdx++];
            QPointF iPos = shapedPaint ? blockPos : blockPos - blockRect.topLeft();
            blockPos += QPointF(0, blockRect.height());

            qreal curLen = 8;

            // 1.2. iterate over text fragments
            for (QTextBlock::iterator tbIt = tb.begin(); !(tbIt.atEnd()); ++tbIt) {
                QTextFragment frag = tbIt.fragment();
                if (!frag.isValid())
                    continue;

                // 1.2.1. setup painter and metrics for text fragment
                QTextCharFormat format = frag.charFormat();
                QFont font = format.font();
                painter->setFont(font);
                painter->setPen(format.foreground().color());
                painter->setBrush(Qt::NoBrush);
                QFontMetrics metrics(font);

                // 1.2.2. draw each character
                QString text = frag.text();
                foreach (const QChar & textChar, text) {
                    const qreal charWidth = metrics.width(textChar);
                    if (shapedPaint) {
                        // find point on shape and angle
                        qreal t = m_shapePath.percentAtLength(curLen);
                        QPointF pt = m_shapePath.pointAtPercent(t);
                        qreal angle = -m_shapePath.angleAtPercent(t);
                        if (m_shakeRadius > 0)
                            pt += QPointF(1 + (qrand() % m_shakeRadius) - m_shakeRadius/2, 1 + (qrand() % (2*m_shakeRadius)) - m_shakeRadius);

                        // draw rotated letter
                        painter->save();
                        painter->translate(pt);
                        painter->rotate(angle);
                        painter->drawText(iPos, textChar);
                        painter->restore();

                        curLen += charWidth;
                    } else {
                        painter->drawText(iPos, textChar);
                        iPos += QPointF(charWidth, 0);
                    }
                }
            }
        }
    }

    painter->restore();
}
Exemple #26
0
QString DummyDataGenerator::randomLastName()
{
    return m_lastNames.at(qrand()%m_lastNames.count());
}
Exemple #27
0
int randInt(int low, int high)
{
    return qrand() % ((high + 1) - low) + low;
}
Exemple #28
0
const Card *ServerPlayer::getRandomHandCard() const{
    int index = qrand() % handcards.length();
    return handcards.at(index);
}
DrawFinancialChart::DrawFinancialChart(QWidget *parent) :
    QCustomPlot(parent)
{
    resize(600,400);

    legend->setVisible(true);

    // generate two sets of random walk data (one for candlestick and one for ohlc chart):
    int n = 500;
    QVector<double> time(n), value1(n), value2(n);
    QDateTime start = QDateTime(QDate(2014, 6, 11));
    start.setTimeSpec(Qt::UTC);
    double startTime = start.toTime_t();
    double binSize = 3600*24; // bin data in 1 day intervals
    time[0] = startTime;
    value1[0] = 60;
    value2[0] = 20;
    qsrand(9);
    for (int i=1; i<n; ++i)
    {
      time[i] = startTime + 3600*i;
      value1[i] = value1[i-1] + (qrand()/(double)RAND_MAX-0.5)*10;
      value2[i] = value2[i-1] + (qrand()/(double)RAND_MAX-0.5)*3;
    }

    // create candlestick chart:
    QCPFinancial *candlesticks = new QCPFinancial(xAxis, yAxis);
    addPlottable(candlesticks);
    QCPFinancialDataMap data1 = QCPFinancial::timeSeriesToOhlc(time, value1, binSize, startTime);
    candlesticks->setName("Candlestick");
    candlesticks->setChartStyle(QCPFinancial::csCandlestick);
    candlesticks->setData(&data1, true);
    candlesticks->setWidth(binSize*0.9);
    candlesticks->setTwoColored(true);
    candlesticks->setBrushPositive(QColor(245, 245, 245));
    candlesticks->setBrushNegative(QColor(0, 0, 0));
    candlesticks->setPenPositive(QPen(QColor(0, 0, 0)));
    candlesticks->setPenNegative(QPen(QColor(0, 0, 0)));

    // create ohlc chart:
    QCPFinancial *ohlc = new QCPFinancial(xAxis, yAxis);
    addPlottable(ohlc);
    QCPFinancialDataMap data2 = QCPFinancial::timeSeriesToOhlc(time, value2, binSize/3.0, startTime); // divide binSize by 3 just to make the ohlc bars a bit denser
    ohlc->setName("OHLC");
    ohlc->setChartStyle(QCPFinancial::csOhlc);
    ohlc->setData(&data2, true);
    ohlc->setWidth(binSize*0.2);
    ohlc->setTwoColored(true);

    // create bottom axis rect for volume bar chart:
    QCPAxisRect *volumeAxisRect = new QCPAxisRect(this);
    plotLayout()->addElement(1, 0, volumeAxisRect);
    volumeAxisRect->setMaximumSize(QSize(QWIDGETSIZE_MAX, 100));
    volumeAxisRect->axis(QCPAxis::atBottom)->setLayer("axes");
    volumeAxisRect->axis(QCPAxis::atBottom)->grid()->setLayer("grid");
    // bring bottom and main axis rect closer together:
    plotLayout()->setRowSpacing(0);
    volumeAxisRect->setAutoMargins(QCP::msLeft|QCP::msRight|QCP::msBottom);
    volumeAxisRect->setMargins(QMargins(0, 0, 0, 0));
    // create two bar plottables, for positive (green) and negative (red) volume bars:
    QCPBars *volumePos = new QCPBars(volumeAxisRect->axis(QCPAxis::atBottom), volumeAxisRect->axis(QCPAxis::atLeft));
    QCPBars *volumeNeg = new QCPBars(volumeAxisRect->axis(QCPAxis::atBottom), volumeAxisRect->axis(QCPAxis::atLeft));
    for (int i=0; i<n/5; ++i)
    {
      int v = qrand()%20000+qrand()%20000+qrand()%20000-10000*3;
      (v < 0 ? volumeNeg : volumePos)->addData(startTime+3600*5.0*i, qAbs(v)); // add data to either volumeNeg or volumePos, depending on sign of v
    }
    setAutoAddPlottableToLegend(false);
    addPlottable(volumePos);
    addPlottable(volumeNeg);
    volumePos->setWidth(3600*4);
    volumePos->setPen(Qt::NoPen);
    volumePos->setBrush(QColor(100, 180, 110));
    volumeNeg->setWidth(3600*4);
    volumeNeg->setPen(Qt::NoPen);
    volumeNeg->setBrush(QColor(180, 90, 90));

    // interconnect x axis ranges of main and bottom axis rects:
    connect(xAxis, SIGNAL(rangeChanged(QCPRange)), volumeAxisRect->axis(QCPAxis::atBottom), SLOT(setRange(QCPRange)));
    connect(volumeAxisRect->axis(QCPAxis::atBottom), SIGNAL(rangeChanged(QCPRange)), xAxis, SLOT(setRange(QCPRange)));
    // configure axes of both main and bottom axis rect:
    volumeAxisRect->axis(QCPAxis::atBottom)->setAutoTickStep(false);
    volumeAxisRect->axis(QCPAxis::atBottom)->setTickStep(3600*24*4); // 4 day tickstep
    volumeAxisRect->axis(QCPAxis::atBottom)->setTickLabelType(QCPAxis::ltDateTime);
    volumeAxisRect->axis(QCPAxis::atBottom)->setDateTimeSpec(Qt::UTC);
    volumeAxisRect->axis(QCPAxis::atBottom)->setDateTimeFormat("dd. MMM");
    volumeAxisRect->axis(QCPAxis::atBottom)->setTickLabelRotation(15);
    volumeAxisRect->axis(QCPAxis::atLeft)->setAutoTickCount(3);
    xAxis->setBasePen(Qt::NoPen);
    xAxis->setTickLabels(false);
    xAxis->setTicks(false); // only want vertical grid in main axis rect, so hide xAxis backbone, ticks, and labels
    xAxis->setAutoTickStep(false);
    xAxis->setTickStep(3600*24*4); // 4 day tickstep
    rescaleAxes();
    xAxis->scaleRange(1.025, xAxis->range().center());
    yAxis->scaleRange(1.1, yAxis->range().center());

    // make axis rects' left side line up:
    QCPMarginGroup *group = new QCPMarginGroup(this);
    axisRect()->setMarginGroup(QCP::msLeft|QCP::msRight, group);
    volumeAxisRect->setMarginGroup(QCP::msLeft|QCP::msRight, group);
}
Exemple #30
0
/**
 * create random numbers from low to high
 * @brief SoundManager::getRandom
 * @param low
 * @param high
 * @return
 */
int SoundManager::getRandom(int low, int high)
{
    return (qrand() % ((high + 1) - low) + low);
}