Example #1
0
QMap<int, double> TutorialUnit::moveHaptic(QMap<int, double> axes)
{
    QMap<int, double> force;
    if(axes.empty()){
        stop();
        return force;
    }

    if(mHapticStartAxes.empty()){
        mHapticStartAxes = axes;
        mStartPosition = QPointF(getPosition().x, getPosition().y);
    }

    qDebug() << "=========================";
    qDebug() << "Start: " << mHapticStartAxes[Tc::Haptic::AxisX] << "," << mHapticStartAxes[Tc::Haptic::AxisX];
    qDebug() << "Current: " << axes[Tc::Haptic::AxisX] << "," << axes[Tc::Haptic::AxisX];

    axes[Tc::Haptic::AxisX] -= mHapticStartAxes[Tc::Haptic::AxisX];
    axes[Tc::Haptic::AxisY] -= mHapticStartAxes[Tc::Haptic::AxisY];
    axes[Tc::Haptic::AxisZ] -= mHapticStartAxes[Tc::Haptic::AxisZ];

    QPointF p(axes[Tc::Haptic::AxisX], axes[Tc::Haptic::AxisY]);
    qDebug() << "Delta: " << axes[Tc::Haptic::AxisX] << "," << axes[Tc::Haptic::AxisX];

    // 1. Converte p to the rotated coordinate system
    // Rotation around "z"-axis, all values in radian
    // => R = [[cos(yaw),-sin(yaw)][sin(yaw), cos(yaw)]]
    // => x' = p.x() * cos(yaw) - p.y() * sin(yaw)
    //    y' = p.x() * sin(yaw) + p.y() * cos(yaw)
    double yawRad = qDegreesToRadians(mHapticStartAxes[Tc::Haptic::AxisYaw]);
    QPointF pNew(p.x() * qCos(yawRad) + p.y() * qSin(yawRad), p.x() * -qSin(yawRad) + p.y() * qCos(yawRad));

    double targetX = qBound<double>(0.0, mStartPosition.x() + pNew.x() * IMAGE_WIDTH, IMAGE_WIDTH);
    double targetY = qBound<double>(0.0, mStartPosition.y() + pNew.y() * IMAGE_HEIGHT, IMAGE_HEIGHT);
    QPointF targetPosition(targetX, targetY);

    qDebug() << "New: " << pNew.x() << "," << pNew.y() << " (" << mHapticStartAxes[Tc::Haptic::AxisYaw] << ")";
    qDebug() << "Target: " << targetX << "," << targetY;

    //qDebug() << p << ";" << targetPosition;

    //setPosition(targetPosition);

    return force;

    // Create return value

    // Check if robot is in "bounds"
    /*QPointF currentPosition = QPointF(getPosition().x, getPosition().y);
    QRect workspace = QRect(50,50,500,300);

    if(currentPosition.x() < workspace.left()){
        // Robot left workspace on left hand side
        force[Tc::Haptic::AxisX] = abs(currentPosition.x()-workspace.left())*10.0;
    } else if(workspace.right() < currentPosition.x()){
        // Robot left workspace on right hand side
        force[Tc::Haptic::AxisX] = abs(currentPosition.x()-workspace.right())*-10.0;
    }

    if(currentPosition.y() < workspace.top()){
        // Robot left workspace on the top
        force[Tc::Haptic::AxisY] = abs(currentPosition.y()-workspace.top())*-10.0;
    } else if(workspace.bottom() < currentPosition.y()){
        // Robot left workspace on the bottom
        force[Tc::Haptic::AxisY] = abs(currentPosition.y()-workspace.bottom())*10.0;
    }*/


}
Example #2
0
/**
 * Add entries to a variable. Will just add the variables to the existing line, removing duplicates
 * Will preserve += constructs and make sure that the variable only has one copy of the value across
 * all += constructs
 * @param fileName
 * @param variables key=value string of entries to add
 * @param add true= add these key,value pairs, false = remove. You can have empty values for an add - the whole line is
 * removed. For adding, we will not add an empty line.
 */
void AutoProjectTool::addRemoveMakefileam(const QString &fileName, QMap<QString, QString> variables,  bool add)
{
	// input file reading
	QFile fin(fileName);
	if (!fin.open(IO_ReadOnly))
	{
		return ;
	}
	QTextStream ins(&fin);

	// output file writing.
	QFile fout(fileName + "#");
	if (!fout.open(IO_WriteOnly))
	{
		fin.close();
		return ;
	}
	QTextStream outs(&fout);

	// variables
	QRegExp re("^(#kdevelop:[ \t]*)?([A-Za-z][@A-Za-z0-9_]*)[ \t]*([:\\+]?=)[ \t]*(.*)$");

	// build key=map of values to add
	// map can be empty.we never add an empty key, but do remove empty keys from the file..
	QDict< QMap<QString, bool> > interest;
	for (QMap<QString, QString>::Iterator it0 = variables.begin(); it0 != variables.end(); ++it0)
	{
		kdDebug(9020) << "key (" << add<<"): " << it0.key() << "="<< it0.data() << endl;

		QMap<QString, bool>* set = new QMap<QString, bool>();
		if (!it0.data().stripWhiteSpace().isEmpty())
		{
			QStringList variableList = QStringList::split(' ', it0.data());

			for (uint i = 0; i < variableList.count(); i++)
			{
				set->insert(variableList[i], true);
			}
		}
		interest.insert(it0.key(), set);
	}

	bool multiLine = false;
	QString lastLhs;
	QStringList lastRhs;
	QMap<QString, QString> seenLhs;
	while (!fin.atEnd())
	{
		QString s = ins.readLine();
		if (re.exactMatch(s))
		{
			QString lhs = re.cap(2);
			QMap<QString, bool>* ourRhs = interest.find(lhs);

			if (!ourRhs)
			{
				// not interested in this line at all
				// write it out as is..
				outs << s << endl;
			}
			else
			{
				// we are interested in this line..
				QString rhs = re.cap(4).stripWhiteSpace();
				if (rhs[ rhs.length() - 1 ] == '\\')
				{
					// save it for when we have the whole line..
					multiLine = true;
					lastLhs = lhs;
					rhs.setLength(rhs.length() - 1);
					lastRhs += QStringList::split(" ", rhs);
				}
				else
				{
					// deal with it now.

					QStringList bits = QStringList::split(" ", rhs);
					if (add)
					{
						// we are adding our interested values to this line and writing it

						// add this line to we we want to add to remove duplicates.
						for (uint index = 0; index < bits.size(); index++)
						{
							QMap<QString, bool>::iterator findEntry = ourRhs->find(bits[index]);
							if (findEntry == ourRhs->end())
							{
								// we haven't seen it, so add it, so we don't add it again later..
								ourRhs->insert(bits[index], true);
							}
							// else we have this value in our 'to add list' , it is either already been
							// added, so we don't want to add it again, or it hasn't been added, in which
							// case we will do so soon. so we can ignore this now..
						}
						// now write the line out if it is not going to be empty.
						QString newLine(lhs);
						if (seenLhs.find(lhs) == seenLhs.end())
						{
							newLine += " = ";
							seenLhs[lhs] = "";
						}
						else
						{
							newLine += " += ";
						}

						int len = newLine.length();
						bool added = false;
						QValueList<QString> keys = ourRhs->keys();
						for (uint count = 0; count < keys.size(); count++)
						{
							// if out entry is true, add it..
							if ((*ourRhs)[keys[count]])
							{
								added = true;
								len += keys[count].length() + 1;
								if (len > 80)
								{
									newLine += "\\\n\t";
									len = 8;
								}
								newLine += keys[count];
								newLine += ' ';
								// set our value so we don't add it again.
								(*ourRhs)[keys[count]] = false;
							}
						}
						// only print it out if there was a value to add..
						if (added)
						{
							newLine.setLength(newLine.length() - 1);
							outs << newLine << endl;
						}
					}
					else
					{
						// we are removing our interested values from this line

						// special case - no values, remove the line..
						if (!ourRhs->empty())
						{
							// check if any of these values are down to remove.
							QString newLine(lhs);
							if (seenLhs.find(lhs) == seenLhs.end())
							{
								newLine += " = ";
								seenLhs[lhs] = "";
							}
							else
							{
								newLine += " += ";
							}

							int len = newLine.length();
							bool added = false;
							for (QStringList::Iterator posIter = bits.begin(); posIter != bits.end();posIter++)
							{
								QMap<QString, bool>::iterator findEntry = ourRhs->find(*posIter);
								if (findEntry == ourRhs->end())
								{
									// we do not want to remove it..
									added = true;
									len += (*posIter).length() + 1;
									if (len > 80)
									{
										newLine += "\\\n\t";
										len = 8;
									}
									newLine += (*posIter);
									newLine += ' ';
								}
								// else we have this value in our 'to remove list', so don't add it.
							}
							// only print it out if there was a value on it..
							if (added)
							{
								newLine.setLength(newLine.length() - 1);
								outs << newLine << endl;
							}
						}
					}//if (add)
				}//if ( rhs[ rhs.length() - 1 ] == '\\'  )
			}//if ( found == interest.end())
		}
		else if (multiLine)
		{
			s = s.stripWhiteSpace();
			// we are only here if were interested in this line..
			if (s[s.length()-1] == '\\')
			{
				s.setLength(s.length() - 1);
				// still more multi line we wait for..
			}
			else
			{
				// end of the multi line..
				multiLine = false;
			}
			lastRhs += QStringList::split(" ", s);

			if (!multiLine)
			{
				// now we have to deal with this multiLine value..
				// ourRhs will always be a value, as we only get multiLine if we're interested in it..
				QMap<QString, bool>* ourRhs = interest.find(lastLhs);

				if (add)
				{
					// we are adding our interested values to this line and writing it

					// add this line to we we want to add to remove duplicates.
					for (uint index = 0; index < lastRhs.size(); index++)
					{
						QMap<QString, bool>::iterator findEntry = ourRhs->find(lastRhs[index]);
						if (findEntry == ourRhs->end())
						{
							// we haven't seen it, so add it, so we don't add it again later..
							ourRhs->insert(lastRhs[index], true);
						}
						// else we have this value in our 'to add list' , it is either already been
						// added, so we don't want to add it again, or it hasn't been added, in which
						// case we will do so soon. so we can ignore this now..
					}
					// now write the line out if it is not going to be empty.
					QString newLine(lastLhs);
					if (seenLhs.find(lastLhs) == seenLhs.end())
					{
						newLine += " = ";
						seenLhs[lastLhs] = "";
					}
					else
					{
						newLine += " += ";
					}

					int len = newLine.length();
					bool added = false;
					QValueList<QString> keys = ourRhs->keys();
					for (uint count = 0; count < keys.size(); count++)
					{
						// if out entry is true, add it..
						if ((*ourRhs)[keys[count]])
						{
							added = true;
							len += keys[count].length() + 1;
							if (len > 80)
							{
								newLine += "\\\n\t";
								len = 8;
							}
							newLine += keys[count];
							newLine += ' ';
							// set our value so we don't add it again.
							(*ourRhs)[keys[count]] = false;
						}
					}
					// only print it out if there was a value to add..
					if (added)
					{
						newLine.setLength(newLine.length() - 1);
						outs << newLine << endl;
					}
				}
				else
				{
					// we are removing our interested values from this line
					// special case - no values, remove the line..
					if (!ourRhs->empty())
					{
						// check if any of these values are down to remove.
						QString newLine(lastLhs);
						if (seenLhs.find(lastLhs) == seenLhs.end())
						{
							newLine += " = ";
							seenLhs[lastLhs] = "";
						}
						else
						{
							newLine += " += ";
						}
						int len = newLine.length();
						bool added = false;
						for (QStringList::Iterator posIter = lastRhs.begin(); posIter != lastRhs.end();posIter++)
						{
							QMap<QString, bool>::iterator findEntry = ourRhs->find(*posIter);
							if (findEntry == ourRhs->end())
							{
								// we do not want to remove it..
								added = true;
								len += (*posIter).length() + 1;
								if (len > 80)
								{
									newLine += "\\\n\t";
									len = 8;
								}
								newLine += (*posIter);
								newLine += ' ';
							}
							// else we have this value in our 'to remove list', so don't add it.
						}
						// only print it out if there was a value on it..
						if (added)
						{
							newLine.setLength(newLine.length() - 1);
							outs << newLine << endl;
						}
					}
				}

				lastLhs.setLength(0);
				lastRhs.clear();
			}
		}
		else
		{
			// can write this line out..
			// not a match, not a multi line,
			outs << s << endl;
		}
	}

	if (add)
	{
		QDictIterator<QMap<QString, bool> > it(interest);
		for (; it.current(); ++it)
		{
			QString lhs = it.currentKey();
			QMap<QString, bool>* ourRhs = it.current();

			QString newLine(lhs);
			if (seenLhs.find(lhs) == seenLhs.end())
			{
				newLine += " = ";
				seenLhs[lastLhs] = "";
			}
			else
			{
				newLine += " += ";
			}
			int len = newLine.length();
			bool added = false;
			QValueList<QString> keys = ourRhs->keys();
			for (uint count = 0; count < keys.size(); count++)
			{
				if ((*ourRhs)[keys[count]])
				{
					added = true;
					len += keys[count].length() + 1;
					if (len > 80)
					{
						newLine += "\\\n\t";
						len = 8;
					}
					newLine += keys[count];
					newLine += ' ';
					// set our value so we don't add it again.
					(*ourRhs)[keys[count]] = false;
				}
			}
			// only print it out if there was a value to add..
			if (added)
			{
				newLine.setLength(newLine.length() - 1);
				outs << newLine << endl;
			}
		}
	}
	interest.setAutoDelete(true);
	interest.clear();

	fin.close();
	fout.close();

	QDir().rename(fileName + "#", fileName);
}
Example #3
0
Order changeTrendAgent::bestRateOrder()
{
    QMap<double, Order> bestOrders;
    for(int i = 2; i <=  STOKS_NUMBER; ++i)
    {
        double diffForSell = m_stocksInfo[i].lowestPrice(m_lowestBuyTime) - m_stocksInfo[i].greatestPrice(m_greatestBuyTime);
        if(m_store.contains(i) && m_stocksInfo[i].lastPrice() && diffForSell > 0.001 &&
                ( (m_stocksInfo[i].getBestSellPrice()*1.005 <=  m_store.getMoney() && m_stocksInfo[i].getBestSellPrice()) ||
                  (m_stocksInfo[i].lastPrice() <= m_store.getMoney()) ) )
        {
            bestOrders.insertMulti(diffForSell, Order(Order::SELL, i, 0, 0));
        }
        double diffForBuy =  m_stocksInfo[i].lowestPrice(m_lowestSellTime) - m_stocksInfo[i].greatestPrice(m_greatestSellTime);
        if(  m_stocksInfo[i].lastPrice() && diffForBuy > 0.001 &&
              ( (m_stocksInfo[i].getBestBuyPrice()*1.025 <=  m_store.getMoney() && m_stocksInfo[i].getBestBuyPrice()) ||
                (m_stocksInfo[i].lastPrice() <= m_store.getMoney()) ))
        {
            bestOrders.insertMulti(diffForBuy, Order(Order::BUY, i, 0, 0));
        }
    }

    if(bestOrders.empty())
        return Order();

    QMutableMapIterator<double, Order> i(bestOrders);
    while (i.hasNext()) {
        i.next();
        if((1.0*qrand())/RAND_MAX < m_bestChooseChance)
        {
            Order order = i.value();
            qint32 price;
            if(m_stocksInfo[order.getStockId()].getBestSellPrice() && m_stocksInfo[order.getStockId()].getBestBuyPrice())
            {
                if(order.getTransactionType() == Order::SELL)
                {
                    price = m_stocksInfo[order.getStockId()].getBestSellPrice()*(1.005 - (0.03*qrand())/RAND_MAX);
                }
                else
                {
                    price = m_stocksInfo[order.getStockId()].getBestBuyPrice()*(0.095 + (0.03*qrand())/RAND_MAX);
                }
            }
            else price = m_stocksInfo[order.getStockId()].lastPrice();

            if(!price)
                continue;
            order.setPrice(price);

            qint32 maxAmount = m_store.getMoney()/price;
            double rand = (1.0*qrand())/RAND_MAX;
            qint32 amount = 3 + qrand()%13;
            if(rand > 0.45 && rand < 0.88)
                amount = 16 + qrand()%35;
            else if(rand >= 0.88)
                amount = 51 + qrand()%75;
            if(maxAmount)
                amount %= maxAmount;
            order.setAmount(amount);
            if(order.getAmount()&& order.getPrice())
                return order;
        }
    }

    Order order = i.value();
    qint32 price;
    if(m_stocksInfo[order.getStockId()].getBestSellPrice() && m_stocksInfo[order.getStockId()].getBestBuyPrice())
    {
        if(order.getTransactionType() == Order::SELL)
        {
            price = m_stocksInfo[order.getStockId()].getBestSellPrice()*(1.005 - (0.03*qrand())/RAND_MAX);
        }
        else
        {
            price = m_stocksInfo[order.getStockId()].getBestBuyPrice()*(0.095 + (0.03*qrand())/RAND_MAX);
        }
    }
    else price = m_stocksInfo[order.getStockId()].lastPrice();
    if(!price)
        return Order();
    order.setPrice(price);

    qint32 maxAmount = m_store.getMoney()/price;
    double rand = (1.0*qrand())/RAND_MAX;
    qint32 amount = 3 + qrand()%13;
    if(rand > 0.45 && rand < 0.88)
        amount = 16 + qrand()%35;
    else if(rand >= 0.88)
        amount = 51 + qrand()%75;
    if(maxAmount)
        amount %= maxAmount;
    order.setAmount(amount);
    if(order.getAmount()&& order.getPrice())
        return order;
    else return Order();
}
Example #4
0
AudioOutput *AudioOutput::OpenAudio(AudioSettings &settings,
                                    bool willsuspendpa)
{
    QString &main_device = settings.main_device;
    AudioOutput *ret = NULL;

    // Don't suspend Pulse if unnecessary.  This can save 100mS
    if (settings.format == FORMAT_NONE || settings.channels <= 0)
        willsuspendpa = false;

#ifdef USING_PULSE
    bool pulsestatus = false;
#else
    {
        static bool warned = false;
        if (!warned && IsPulseAudioRunning())
        {
            warned = true;
            LOG(VB_GENERAL, LOG_WARNING,
                "WARNING: ***Pulse Audio is running***");
        }
    }
#endif

    settings.FixPassThrough();

    if (main_device.startsWith("PulseAudio:"))
    {
#ifdef USING_PULSEOUTPUT
        return new AudioOutputPulseAudio(settings);
#else
        LOG(VB_GENERAL, LOG_ERR, "Audio output device is set to PulseAudio "
                                 "but PulseAudio support is not compiled in!");
        return NULL;
#endif
    }
    else if (main_device.startsWith("NULL"))
    {
        return new AudioOutputNULL(settings);
    }

#ifdef USING_PULSE
    if (willsuspendpa)
    {
        bool ispulse = false;
#ifdef USING_ALSA
        // Check if using ALSA, that the device doesn't contain the word
        // "pulse" in its hint
        if (main_device.startsWith("ALSA:"))
        {
            QString device_name = main_device;

            device_name.remove(0, 5);
            QMap<QString, QString> *alsadevs =
                AudioOutputALSA::GetDevices("pcm");
            if (!alsadevs->empty() && alsadevs->contains(device_name))
            {
                if (alsadevs->value(device_name).contains("pulse",
                                                          Qt::CaseInsensitive))
                {
                    ispulse = true;
                }
            }
            delete alsadevs;
        }
#endif
        if (main_device.contains("pulse", Qt::CaseInsensitive))
        {
            ispulse = true;
        }
        if (!ispulse)
        {
            pulsestatus = PulseHandler::Suspend(PulseHandler::kPulseSuspend);
        }
    }
#endif

    if (main_device.startsWith("ALSA:"))
    {
#ifdef USING_ALSA
        settings.TrimDeviceType();
        ret = new AudioOutputALSA(settings);
#else
        LOG(VB_GENERAL, LOG_ERR, "Audio output device is set to an ALSA device "
                                 "but ALSA support is not compiled in!");
#endif
    }
    else if (main_device.startsWith("JACK:"))
    {
#ifdef USING_JACK
        settings.TrimDeviceType();
        ret = new AudioOutputJACK(settings);
#else
        LOG(VB_GENERAL, LOG_ERR, "Audio output device is set to a JACK device "
                                 "but JACK support is not compiled in!");
#endif
    }
    else if (main_device.startsWith("DirectX:"))
    {
#ifdef _WIN32
        ret = new AudioOutputDX(settings);
#else
        LOG(VB_GENERAL, LOG_ERR, "Audio output device is set to DirectX device "
                                 "but DirectX support is not compiled in!");
#endif
    }
    else if (main_device.startsWith("Windows:"))
    {
#ifdef _WIN32
        ret = new AudioOutputWin(settings);
#else
        LOG(VB_GENERAL, LOG_ERR, "Audio output device is set to a Windows "
                                 "device but Windows support is not compiled "
                                 "in!");
#endif
    }
    else if (main_device.startsWith("OpenSLES:"))
    {
#ifdef Q_OS_ANDROID
        ret = new AudioOutputOpenSLES(settings);
#else
        LOG(VB_GENERAL, LOG_ERR, "Audio output device is set to a OpenSLES "
                                 "device but Android support is not compiled "
                                 "in!");
#endif
    }
#if defined(USING_OSS)
    else
        ret = new AudioOutputOSS(settings);
#elif CONFIG_DARWIN
    else
Example #5
0
CC_FILE_ERROR PhotoScanFilter::loadFile(const QString& filename,
										ccHObject& container,
										LoadParameters& parameters)
{
	QuaZip zip(filename);

	if (!zip.open(QuaZip::mdUnzip))
	{
		//failed to open or read the zip file
		return CC_FERR_READING;
	}

	QStringList fileList = zip.getFileNameList();
	if (fileList.isEmpty())
	{
		//empty archive?
		return CC_FERR_NO_LOAD;
	}

	static const QString s_defaultXMLFilename("doc.xml");

	if (!fileList.contains(s_defaultXMLFilename))
	{
		//empty archive?
		ccLog::Warning(QString("[Photoscan] Couldn't find '%1' in Photoscan archive").arg(s_defaultXMLFilename));
		return CC_FERR_NO_LOAD;
	}

	//look for the XML file
	if (!zip.setCurrentFile(s_defaultXMLFilename))
	{
		ccLog::Warning(QString("[Photoscan] Failed to locate '%1' in the Photoscan archive").arg(s_defaultXMLFilename));
		return CC_FERR_MALFORMED_FILE;
	}

	//decompress the XML file
	QuaZipFile zipXML(&zip);
	if (!zipXML.open(QFile::ReadOnly))
	{
		ccLog::Warning(QString("[Photoscan] Failed to extract '%1' from Photoscan archive").arg(s_defaultXMLFilename));
		return CC_FERR_NO_LOAD;
	}

	QXmlStreamReader stream(&zipXML);

	//expected: "document"
	if (!stream.readNextStartElement() || stream.name() != "document")
	{
		return CC_FERR_MALFORMED_FILE;
	}

	std::vector<Sections> sections;
	sections.push_back(DOCUMENT);

	QMap<int, ccCameraSensor*> sensors;
	QMap<int, CameraDesc> cameras;
	QList<CloudDesc> clouds;
	QList<MeshDesc> meshes;
	ccGLMatrixd globalTransform;
	bool hasGlobalTransform = false;

	while (true)
	{
		if (!stream.readNextStartElement())
		{
			//end of section?
			if (!sections.empty())
			{
				ccLog::PrintDebug(" < " + stream.name().toString() + QString(" [%1]").arg(ToName(sections.back())));
				sections.pop_back();
				//stream.skipCurrentElement();
				continue;
			}
			else
			{
				//end of file
				break;
			}
		}
		ccLog::PrintDebug(" > " + stream.name().toString());

		switch (sections.back())
		{
		case DOCUMENT:
			if (stream.name() == "chunks")
			{
				sections.push_back(CHUNKS);
			}
			else
			{
				//not handled
				stream.skipCurrentElement();
			}
			break;

		case CHUNKS:
			if (stream.name() == "chunk")
			{
				sections.push_back(CHUNK);
			}
			else
			{
				//not handled
				stream.skipCurrentElement();
			}
			break;

		case CHUNK:
			if (stream.name() == "sensors")
			{
				sections.push_back(SENSORS);
			}
			else if (stream.name() == "cameras")
			{
				sections.push_back(CAMERAS);
			}
			else if (stream.name() == "frames")
			{
				sections.push_back(FRAMES);
			}
			else if (stream.name() == "transform")
			{
				//inner loop
				while (stream.readNextStartElement())
				{
					if (stream.name() == "rotation")
					{
						QString rotationValues = stream.readElementText();
						if (DecodeRotation<double>(rotationValues, globalTransform))
						{
							hasGlobalTransform = true;
						}
						else
						{
							assert(false);
						}
					}
					stream.skipCurrentElement();
				}
			}
			else //frames, reference, region, settings, meta, etc.
			{
				//not handled for now
				stream.skipCurrentElement();
			}
			break;

		case SENSORS:
			if (stream.name() == "sensor")
			{
				int sensorId = -1;
				ccCameraSensor* sensor = DecodeSensor(stream, sensorId);
				if (sensor)
				{
					assert(!sensors.contains(sensorId));
					sensors.insert(sensorId, sensor);
					//currentContainer->addChild(sensor);
				}
			}
			else
			{
				//not handled
				stream.skipCurrentElement();
			}
			break;

		case CAMERAS:
			if (stream.name() == "camera")
			{
				CameraDesc camera;
				ccGLMatrix trans;
				if (DecodeCamera(stream, camera))
				{
					assert(!cameras.contains(camera.id));
					cameras.insert(camera.id, camera);
					//currentContainer->addChild(camera.image);
				}
			}
			else
			{
				//not handled
				stream.skipCurrentElement();
			}
			break;

		case FRAMES:
			if (stream.name() == "frame")
			{
				sections.push_back(FRAME);
			}
			else
			{
				//not handled
				stream.skipCurrentElement();
			}
			break;

		case FRAME:
			if (stream.name() == "point_cloud" || stream.name() == "dense_cloud")
			{
				//inner loop
				bool denseCloud = (stream.name() == "dense_cloud");
				while (stream.readNextStartElement())
				{
					if (stream.name() == "points")
					{
						if (stream.attributes().hasAttribute("path"))
						{
							CloudDesc desc;
							desc.filename = stream.attributes().value("path").toString();
							desc.type = (denseCloud ? "dense cloud" : "keypoints");
							clouds.push_back(desc);
						}
						else
						{
							assert(false);
						}
					}
					stream.skipCurrentElement();
				}
			}
			else if (stream.name() == "model")
			{
				MeshDesc desc;

				//inner loop
				while (stream.readNextStartElement())
				{
					if (stream.name() == "mesh")
					{
						if (stream.attributes().hasAttribute("path"))
						{
							desc.filename = stream.attributes().value("path").toString();
						}
						else
						{
							assert(false);
						}
					}
					else if (stream.name() == "texture")
					{
						if (stream.attributes().hasAttribute("path"))
						{
							desc.texture = stream.attributes().value("path").toString();
						}
						else
						{
							assert(false);
						}
					}
					stream.skipCurrentElement();
				}
				if (!desc.filename.isEmpty())
				{
					meshes.push_back(desc);
				}
			}
			else
			{
				//not handled
				stream.skipCurrentElement();
			}
			break;

		case TRANSFORM:
			//not handled
			stream.skipCurrentElement();
			break;

		default:
			break;
		}
	}

	QScopedPointer<ccProgressDialog> progressDialog(0);
	if (parameters.parentWidget)
	{
		progressDialog.reset(new ccProgressDialog(parameters.parentWidget));
		progressDialog->setRange(0, cameras.size() + clouds.size() + meshes.size());
		progressDialog->setWindowTitle("Loading data");
		progressDialog->start();
	}
	bool wasCanceled = false;
	int currentProgress = 0;

	//end of file: now we can sort the various extracted components
	QDir dir = QFileInfo(filename).dir();
	ccHObject* imageGroup = new ccHObject("Images");
	if (progressDialog && !cameras.empty())
	{
		progressDialog->setInfo(QString("Loading %1 image(s)").arg(cameras.size()));
	}
	for (CameraDesc& camera : cameras)
	{
		//progress
		if (progressDialog)
		{
			progressDialog->setValue(++currentProgress);
			if (progressDialog->wasCanceled())
			{
				wasCanceled = true;
				break;
			}
		}
		if (camera.imageFilename.isEmpty())
		{
			assert(false);
			continue;
		}

		//DGM: the images are not in the archive!
		//if (!zip.setCurrentFile(camera.imageFilename))
		//{
		//	ccLog::Warning(QString("[Photoscan] Failed to locate image '%1' in the Photoscan archive").arg(camera.imageFilename));
		//	continue;
		//}

		////decompress the image file
		//QuaZipFile zipImage(&zip);
		//if (!zipImage.open(QFile::ReadOnly))
		//{
		//	ccLog::Warning(QString("[Photoscan] Failed to extract '%1' from Photoscan archive").arg(camera.imageFilename));
		//	continue;
		//}

		QImage qImage;
		QString absoluteImageFilename = dir.absoluteFilePath(camera.imageFilename);
		//if (!qImage.load(&zipImage, qPrintable(QFileInfo(camera.imageFilename).suffix())))
		if (!qImage.load(absoluteImageFilename))
		{
			ccLog::Warning(QString("[Photoscan] Failed to load image '%1'").arg(camera.imageFilename));
			continue;
		}

		ccCameraSensor* const origSensor = sensors[camera.sensorId];
		if (origSensor)
		{
			origSensor->undistort(qImage);
		}

		ccImage* image = new ccImage(qImage);
		image->setName(camera.imageFilename);
		image->setAlpha(0.5f);
		image->setVisible(false);

		//associated sensor (if any)
		if (origSensor)
		{
			//make a copy of the original sensor
			ccCameraSensor* sensor = new ccCameraSensor(*origSensor);

			camera.trans.setColumn(1, -camera.trans.getColumnAsVec3D(1));
			camera.trans.setColumn(2, -camera.trans.getColumnAsVec3D(2));

			//FIXME: we would have to transform the clouds and meshes as well!
			//if (hasGlobalTransform)
			//{
			//	//apply global transformation (if any)
			//	camera.trans = ccGLMatrix(globalTransform.data()) * camera.trans;
			//}
			sensor->setRigidTransformation(camera.trans);
			sensor->setVisible(true);
			sensor->setGraphicScale(0.1f);
			image->setAssociatedSensor(sensor);
			image->addChild(sensor);
			imageGroup->addChild(image);
		}
	}
	if (imageGroup->getChildrenNumber())
	{
		container.addChild(imageGroup);
	}
	else
	{
		//no image?!
		delete imageGroup;
		imageGroup = 0;
	}

	//we can get rid of the original sensors
	for (ccCameraSensor*& sensor : sensors)
	{
		delete sensor;
		sensor = 0;
	}
	sensors.clear();

	//clouds
	if (!wasCanceled)
	{
		if (progressDialog && !clouds.empty())
		{
			progressDialog->setInfo(QString("Loading %1 cloud(s)").arg(cameras.size()));
		}
		for (CloudDesc& desc : clouds)
		{
			//progress
			if (progressDialog)
			{
				progressDialog->setValue(++currentProgress);
				if (progressDialog->wasCanceled())
				{
					wasCanceled = true;
					break;
				}
			}

			if (desc.filename.isEmpty())
			{
				assert(false);
				continue;
			}

			if (desc.filename.endsWith(".oc3", Qt::CaseInsensitive))
			{
				ccLog::Warning(QString("[Photoscan] OC3 format not supported. Can't import %1 from the Photoscan archive").arg(desc.type));
				continue;
			}

			QString tempFilename = CreateTempFile(zip, desc.filename);
			if (tempFilename.isNull())
			{
				continue;
			}

			ccHObject tempContainer;
			FileIOFilter::LoadParameters params;
			params.alwaysDisplayLoadDialog = false;
			params.autoComputeNormals = false;
			params.parentWidget = 0;
			CC_FILE_ERROR result = CC_FERR_NO_ERROR;
			ccHObject* newGroup = FileIOFilter::LoadFromFile(tempFilename, params, result);
			if (newGroup)
			{
				newGroup->setName(desc.type);
				if (desc.type == "keypoints")
				{
					newGroup->setEnabled(false);
				}
				container.addChild(newGroup);
			}
			else
			{
				ccLog::Warning(QString("[Photoscan] Failed to extract '%1' from Photoscan archive").arg(desc.filename));
			}
			QFile::remove(tempFilename);
		}
	}

	//meshes
	if (!wasCanceled)
	{
		if (progressDialog && !meshes.empty())
		{
			progressDialog->setInfo(QString("Loading %1 mesh(es)").arg(cameras.size()));
		}
		for (MeshDesc& desc : meshes)
		{
			//progress
			if (progressDialog)
			{
				progressDialog->setValue(++currentProgress);
				if (progressDialog->wasCanceled())
				{
					wasCanceled = true;
					break;
				}
			}

			if (desc.filename.isEmpty())
			{
				assert(false);
				continue;
			}

			QString tempFilename = CreateTempFile(zip, desc.filename);
			if (tempFilename.isNull())
			{
				continue;
			}

			FileIOFilter::LoadParameters params;
			params.alwaysDisplayLoadDialog = false;
			params.autoComputeNormals = false;
			params.parentWidget = 0;

			bool success = false;
			if (!desc.texture.isEmpty() && desc.filename.endsWith("ply", Qt::CaseInsensitive))
			{
				QString tempTextureFilename = CreateTempFile(zip, desc.texture);

				ccHObject tempContainer;
				if (PlyFilter().loadFile(tempFilename, desc.texture, tempContainer, params) == CC_FERR_NO_ERROR)
				{
					success = true;
					//transfer the loaded entities to the current container
					for (unsigned i = 0; i < tempContainer.getChildrenNumber(); ++i)
					{
						container.addChild(tempContainer.getChild(i));
					}
					tempContainer.detatchAllChildren();
				}

				if (!tempTextureFilename.isNull())
				{
					QFile::remove(tempTextureFilename);
				}
			}
			else
			{
				CC_FILE_ERROR result = CC_FERR_NO_ERROR;
				ccHObject* newGroup = FileIOFilter::LoadFromFile(tempFilename, params, result);
				if (newGroup)
				{
					success = true;
					//transfer the loaded entities to the current container
					for (unsigned i = 0; i < newGroup->getChildrenNumber(); ++i)
					{
						container.addChild(newGroup->getChild(i));
					}
					newGroup->detatchAllChildren();
					delete newGroup;
					newGroup = 0;
				}
			}

			if (!success)
			{
				ccLog::Warning(QString("[Photoscan] Failed to extract '%1' from Photoscan archive").arg(desc.filename));
			}

			QFile::remove(tempFilename);
		}
	}

	if (progressDialog)
	{
		progressDialog->stop();
	}

	return wasCanceled ? CC_FERR_CANCELED_BY_USER : CC_FERR_NO_ERROR;
}
Example #6
0
void KstEditViewObjectDialogI::updateWidgets() {
  // clear all the current widgets from the grid
  clearWidgets();

  // get the qt properties of the viewobject
  if (_viewObject) {
    _customWidget = _viewObject->configWidget();
    if (_customWidget) {
      _grid = new QGridLayout(_propertiesFrame, 1, 1);
      _customWidget->reparent(_propertiesFrame, QPoint(0, 0));
      _grid->addWidget(_customWidget, 0, 0);
      _viewObject->fillConfigWidget(_customWidget, _isNew);
      if (!_isNew) {
        _viewObject->connectConfigWidget(this, _customWidget);
      }
      resize(minimumSizeHint());
      return;
    }
    
    //---------------------------------------------------------------
    // NOTE: due to Early return, nothing after this line is executed
    // if the view object provides a custom widget.

    int numProperties = _viewObject->metaObject()->numProperties(true);

    // create a new grid
    _grid = new QGridLayout(_propertiesFrame, numProperties, 2, 0, 8);
    _grid->setColStretch(0,0);
    _grid->setColStretch(1,1);
    
    // get the property names and types
    for (int i = 0; i < numProperties; i++) {
      const QMetaProperty* property = _viewObject->metaObject()->property(i, true);
      QString propertyType(property->type());
      QString propertyName(property->name());
     
      // for this property, get the meta-data map
      QMap<QString, QVariant> metaData = _viewObject->widgetHints(propertyName);
      
      if (!metaData.empty()) {
        QString friendlyName = metaData["_kst_label"].toString();
        QString widgetType = metaData["_kst_widgetType"].toString();
        metaData.erase("_kst_label");
        metaData.erase("_kst_widgetType");
        
        // use friendly name for label
        QLabel* propertyLabel = new QLabel(_propertiesFrame, "label-"+i);
        propertyLabel->setText(friendlyName);
        _grid->addWidget(propertyLabel,i,0);
        _widgets.append(propertyLabel);
        propertyLabel->show();
        
        // display different types of widgets depending on what dialogData specifies
        QWidget* propertyWidget = 0L;
        if (widgetType == "QSpinBox") {
          // insert a spinbox
          propertyWidget = new QSpinBox(_propertiesFrame, (propertyName+","+"value").latin1()); 
          propertyWidget->setProperty("value", _viewObject->property(property->name()));
          if (!_isNew) {
            connect(propertyWidget, SIGNAL(valueChanged(const QString&)), this, SLOT(modified()));
            connect(propertyWidget->child("qt_spinbox_edit"), SIGNAL(textChanged(const QString&)), this, SLOT(modified()));
          }
        } else if (widgetType == "KColorButton") {
QMap<QString, Utente *> *FileManager::caricaUtenti() const {
    QMap<QString, Utente*>* lista = new QMap<QString, Utente*>();
    QXmlStreamReader rxml;

    QFile file(_fileNameUtenti);
    if (file.open(QFile::ReadOnly | QFile::Text))
    {
        rxml.setDevice(&file);
        rxml.readNext();

        QString username, password, nome, cognome, tipo;
        bool isAdmin = false;

        bool utenteAperto = false;

        while(!rxml.atEnd())
        {
            if(rxml.isStartElement())
            {
                if(rxml.name() == "Utenti")
                    rxml.readNext();
                else if(rxml.name() == "Utente")
                {
                    utenteAperto = true;

                    while(!rxml.atEnd())
                    {
                        if(rxml.isEndElement())
                        {
                            if(utenteAperto)
                            {
                                if(tipo == "1")
                                {
                                    lista->insert(username,
                                                  (new UtenteBasic(username, password, isAdmin))
                                                  ->setNome(nome)->setCognome(cognome));
                                }
                                else if(tipo == "2")
                                {
                                    lista->insert(username,
                                                  (new UtenteBusiness(username, password, isAdmin))
                                                  ->setNome(nome)->setCognome(cognome));
                                }
                                else
                                {
                                    lista->insert(username,
                                                  (new UtenteExecutive(username, password, isAdmin))
                                                  ->setNome(nome)->setCognome(cognome));
                                }
                                utenteAperto = false;
                            }
                            rxml.readNext();
                            break;
                        }
                        else if(rxml.isCharacters())
                            rxml.readNext();
                        else if(rxml.isStartElement())
                        {
                            if(rxml.name() == "Username")
                                username = rxml.readElementText();
                            else if(rxml.name() == "Password")
                                password = rxml.readElementText();
                            else if(rxml.name() == "Tipo")
                                tipo = rxml.readElementText();
                            else if(rxml.name() == "IsAdmin")
                                isAdmin = rxml.readElementText() == "true" ? true : false;
                            else if(rxml.name() == "Nome")
                                nome = rxml.readElementText();
                            else if(rxml.name() == "Cognome")
                                cognome = rxml.readElementText();
                            rxml.readNext();
                        }
                        else
                            rxml.readNext();
                    }
                }
            }
            else
                rxml.readNext();
        }

        file.close();
    }
    if(lista->empty())
        lista->insert("matteo",
                      (new UtenteExecutive("matteo", "matteo", true))
                      ->setNome("Matteo")->setCognome("Bortolazzo"));
    return lista;
}
void 
BestIntervalDialog::findClicked()
{
    const RideFile *ride = mainWindow->currentRide();
    if (!ride) {
        QMessageBox::critical(this, tr("Select Ride"), tr("No ride selected!"));
        return;
    }

    int maxIntervals = (int) countSpinBox->value();
    double windowSizeSecs = (hrsSpinBox->value() * 3600.0
                             + minsSpinBox->value() * 60.0
                             + secsSpinBox->value());

    if (windowSizeSecs == 0.0) {
        QMessageBox::critical(this, tr("Bad Interval Length"), 
                              tr("Interval length must be greater than zero!"));
        return;
    }

    QList<const RideFilePoint*> window;
    QMap<double,double> bests;

    double secsDelta = ride->recIntSecs();
    int expectedSamples = (int) floor(windowSizeSecs / secsDelta);
    double totalWatts = 0.0;

    foreach (const RideFilePoint *point, ride->dataPoints()) {
        while (!window.empty()
               && (point->secs >= window.first()->secs + windowSizeSecs)) {
            totalWatts -= window.first()->watts;
            window.takeFirst();
        }
        totalWatts += point->watts;
        window.append(point);
        int divisor = std::max(window.size(), expectedSamples);
        double avg = totalWatts / divisor;
        bests.insertMulti(avg, point->secs);
    }

    QMap<double,double> results;
    while (!bests.empty() && maxIntervals--) {
        QMutableMapIterator<double,double> j(bests);
        j.toBack();
        j.previous();
        double secs = j.value();
        results.insert(j.value() - windowSizeSecs, j.key());
        j.remove();
        while (j.hasPrevious()) {
            j.previous();
            if (abs(secs - j.value()) < windowSizeSecs)
                j.remove();
        }
    }

    QString resultsHtml = 
        "<center>"
        "<table width=\"80%\">"
        "<tr><td align=\"center\">Start Time</td>"
        "    <td align=\"center\">Average Power</td></tr>";
    QMapIterator<double,double> j(results);
    while (j.hasNext()) {
        j.next();
        double secs = j.key();
        double mins = ((int) secs) / 60;
        secs = secs - mins * 60.0;
        double hrs = ((int) mins) / 60;
        mins = mins - hrs * 60.0;
        QString row = 
            "<tr><td align=\"center\">%1:%2:%3</td>"
            "    <td align=\"center\">%4</td></tr>";
        row = row.arg(hrs, 0, 'f', 0);
        row = row.arg(mins, 2, 'f', 0, QLatin1Char('0'));
        row = row.arg(secs, 2, 'f', 0, QLatin1Char('0'));
        row = row.arg(j.value(), 0, 'f', 0, QLatin1Char('0'));
        resultsHtml += row;
    }
    resultsHtml += "</table></center>";
    resultsText->setHtml(resultsHtml);
}
const QMap<QString, QChar> &
Translator::namedEntities()
{
	static QMap<QString, QChar> entities;
	if(entities.empty()) {
		entities["quot"] = 34;
		entities["amp"] = 38;
		entities["lt"] = 60;
		entities["gt"] = 62;
		entities["oelig"] = 338;
		entities["oelig"] = 339;
		entities["scaron"] = 352;
		entities["scaron"] = 353;
		entities["yuml"] = 376;
		entities["circ"] = 710;
		entities["tilde"] = 732;
		entities["ensp"] = 8194;
		entities["emsp"] = 8195;
		entities["thinsp"] = 8201;
		entities["zwnj"] = 8204;
		entities["zwj"] = 8205;
		entities["lrm"] = 8206;
		entities["rlm"] = 8207;
		entities["ndash"] = 8211;
		entities["mdash"] = 8212;
		entities["lsquo"] = 8216;
		entities["rsquo"] = 8217;
		entities["sbquo"] = 8218;
		entities["ldquo"] = 8220;
		entities["rdquo"] = 8221;
		entities["bdquo"] = 8222;
		entities["dagger"] = 8224;
		entities["dagger"] = 8225;
		entities["permil"] = 8240;
		entities["lsaquo"] = 8249;
		entities["rsaquo"] = 8250;
		entities["euro"] = 8364;
		entities["fnof"] = 402;
		entities["alpha"] = 913;
		entities["beta"] = 914;
		entities["gamma"] = 915;
		entities["delta"] = 916;
		entities["epsilon"] = 917;
		entities["zeta"] = 918;
		entities["eta"] = 919;
		entities["theta"] = 920;
		entities["iota"] = 921;
		entities["kappa"] = 922;
		entities["lambda"] = 923;
		entities["mu"] = 924;
		entities["nu"] = 925;
		entities["xi"] = 926;
		entities["omicron"] = 927;
		entities["pi"] = 928;
		entities["rho"] = 929;
		entities["sigma"] = 931;
		entities["tau"] = 932;
		entities["upsilon"] = 933;
		entities["phi"] = 934;
		entities["chi"] = 935;
		entities["psi"] = 936;
		entities["omega"] = 937;
		entities["alpha"] = 945;
		entities["beta"] = 946;
		entities["gamma"] = 947;
		entities["delta"] = 948;
		entities["epsilon"] = 949;
		entities["zeta"] = 950;
		entities["eta"] = 951;
		entities["theta"] = 952;
		entities["iota"] = 953;
		entities["kappa"] = 954;
		entities["lambda"] = 955;
		entities["mu"] = 956;
		entities["nu"] = 957;
		entities["xi"] = 958;
		entities["omicron"] = 959;
		entities["pi"] = 960;
		entities["rho"] = 961;
		entities["sigmaf"] = 962;
		entities["sigma"] = 963;
		entities["tau"] = 964;
		entities["upsilon"] = 965;
		entities["phi"] = 966;
		entities["chi"] = 967;
		entities["psi"] = 968;
		entities["omega"] = 969;
		entities["thetasym"] = 977;
		entities["upsih"] = 978;
		entities["piv"] = 982;
		entities["bull"] = 8226;
		entities["hellip"] = 8230;
		entities["prime"] = 8242;
		entities["prime"] = 8243;
		entities["oline"] = 8254;
		entities["frasl"] = 8260;
		entities["weierp"] = 8472;
		entities["image"] = 8465;
		entities["real"] = 8476;
		entities["trade"] = 8482;
		entities["alefsym"] = 8501;
		entities["larr"] = 8592;
		entities["uarr"] = 8593;
		entities["rarr"] = 8594;
		entities["darr"] = 8595;
		entities["harr"] = 8596;
		entities["crarr"] = 8629;
		entities["larr"] = 8656;
		entities["uarr"] = 8657;
		entities["rarr"] = 8658;
		entities["darr"] = 8659;
		entities["harr"] = 8660;
		entities["forall"] = 8704;
		entities["part"] = 8706;
		entities["exist"] = 8707;
		entities["empty"] = 8709;
		entities["nabla"] = 8711;
		entities["isin"] = 8712;
		entities["notin"] = 8713;
		entities["ni"] = 8715;
		entities["prod"] = 8719;
		entities["sum"] = 8721;
		entities["minus"] = 8722;
		entities["lowast"] = 8727;
		entities["radic"] = 8730;
		entities["prop"] = 8733;
		entities["infin"] = 8734;
		entities["ang"] = 8736;
		entities["and"] = 8743;
		entities["or"] = 8744;
		entities["cap"] = 8745;
		entities["cup"] = 8746;
		entities["int"] = 8747;
		entities["there4"] = 8756;
		entities["sim"] = 8764;
		entities["cong"] = 8773;
		entities["asymp"] = 8776;
		entities["ne"] = 8800;
		entities["equiv"] = 8801;
		entities["le"] = 8804;
		entities["ge"] = 8805;
		entities["sub"] = 8834;
		entities["sup"] = 8835;
		entities["nsub"] = 8836;
		entities["sube"] = 8838;
		entities["supe"] = 8839;
		entities["oplus"] = 8853;
		entities["otimes"] = 8855;
		entities["perp"] = 8869;
		entities["sdot"] = 8901;
		entities["lceil"] = 8968;
		entities["rceil"] = 8969;
		entities["lfloor"] = 8970;
		entities["rfloor"] = 8971;
		entities["lang"] = 9001;
		entities["rang"] = 9002;
		entities["loz"] = 9674;
		entities["spades"] = 9824;
		entities["clubs"] = 9827;
		entities["hearts"] = 9829;
		entities["diams"] = 9830;
		entities["nbsp"] = 160;
		entities["iexcl"] = 161;
		entities["cent"] = 162;
		entities["pound"] = 163;
		entities["curren"] = 164;
		entities["yen"] = 165;
		entities["brvbar"] = 166;
		entities["sect"] = 167;
		entities["uml"] = 168;
		entities["copy"] = 169;
		entities["ordf"] = 170;
		entities["laquo"] = 171;
		entities["not"] = 172;
		entities["shy"] = 173;
		entities["reg"] = 174;
		entities["macr"] = 175;
		entities["deg"] = 176;
		entities["plusmn"] = 177;
		entities["sup2"] = 178;
		entities["sup3"] = 179;
		entities["acute"] = 180;
		entities["micro"] = 181;
		entities["para"] = 182;
		entities["middot"] = 183;
		entities["cedil"] = 184;
		entities["sup1"] = 185;
		entities["ordm"] = 186;
		entities["raquo"] = 187;
		entities["frac14"] = 188;
		entities["frac12"] = 189;
		entities["frac34"] = 190;
		entities["iquest"] = 191;
		entities["agrave"] = 192;
		entities["aacute"] = 193;
		entities["acirc"] = 194;
		entities["atilde"] = 195;
		entities["auml"] = 196;
		entities["aring"] = 197;
		entities["aelig"] = 198;
		entities["ccedil"] = 199;
		entities["egrave"] = 200;
		entities["eacute"] = 201;
		entities["ecirc"] = 202;
		entities["euml"] = 203;
		entities["igrave"] = 204;
		entities["iacute"] = 205;
		entities["icirc"] = 206;
		entities["iuml"] = 207;
		entities["eth"] = 208;
		entities["ntilde"] = 209;
		entities["ograve"] = 210;
		entities["oacute"] = 211;
		entities["ocirc"] = 212;
		entities["otilde"] = 213;
		entities["ouml"] = 214;
		entities["times"] = 215;
		entities["oslash"] = 216;
		entities["ugrave"] = 217;
		entities["uacute"] = 218;
		entities["ucirc"] = 219;
		entities["uuml"] = 220;
		entities["yacute"] = 221;
		entities["thorn"] = 222;
		entities["szlig"] = 223;
		entities["agrave"] = 224;
		entities["aacute"] = 225;
		entities["acirc"] = 226;
		entities["atilde"] = 227;
		entities["auml"] = 228;
		entities["aring"] = 229;
		entities["aelig"] = 230;
		entities["ccedil"] = 231;
		entities["egrave"] = 232;
		entities["eacute"] = 233;
		entities["ecirc"] = 234;
		entities["euml"] = 235;
		entities["igrave"] = 236;
		entities["iacute"] = 237;
		entities["icirc"] = 238;
		entities["iuml"] = 239;
		entities["eth"] = 240;
		entities["ntilde"] = 241;
		entities["ograve"] = 242;
		entities["oacute"] = 243;
		entities["ocirc"] = 244;
		entities["otilde"] = 245;
		entities["ouml"] = 246;
		entities["divide"] = 247;
		entities["oslash"] = 248;
		entities["ugrave"] = 249;
		entities["uacute"] = 250;
		entities["ucirc"] = 251;
		entities["uuml"] = 252;
		entities["yacute"] = 253;
		entities["thorn"] = 254;
		entities["yuml"] = 255;
	}

	return entities;
}
Example #10
0
AudioOutput *AudioOutput::OpenAudio(AudioSettings &settings,
                                    bool willsuspendpa)
{
    QString &main_device = settings.main_device;
    AudioOutput *ret = NULL;

#ifdef USING_PULSE
    bool pulsestatus = false;
#else
    {
        static bool warned = false;
        if (!warned && IsPulseAudioRunning())
        {
            warned = true;
            VERBOSE(VB_IMPORTANT, "WARNING: ***Pulse Audio is running***");
        }
    }
#endif

    settings.FixPassThrough();

    if (main_device.startsWith("PulseAudio:"))
    {
#ifdef USING_PULSEOUTPUT
        return new AudioOutputPulseAudio(settings);
#else
        VERBOSE(VB_IMPORTANT, "Audio output device is set to PulseAudio "
                              "but PulseAudio support is not compiled in!");
        return NULL;
#endif
    }
    else if (main_device.startsWith("NULL"))
    {
        return new AudioOutputNULL(settings);
    }

#ifdef USING_PULSE
    if (willsuspendpa)
    {
        bool ispulse = false;
#ifdef USE_ALSA
        // Check if using ALSA, that the device doesn't contain the word
        // "pulse" in its hint
        if (main_device.startsWith("ALSA:"))
        {
            QString device_name = main_device;

            device_name.remove(0, 5);
            QMap<QString, QString> *alsadevs =
                AudioOutputALSA::GetALSADevices("pcm");
            if (!alsadevs->empty() && alsadevs->contains(device_name))
            {
                if (alsadevs->value(device_name).contains("pulse",
                                                          Qt::CaseInsensitive))
                {
                    ispulse = true;
                }
            }
            delete alsadevs;
        }
#endif
        if (main_device.contains("pulse", Qt::CaseInsensitive))
        {
            ispulse = true;
        }
        if (!ispulse)
        {
            pulsestatus = PulseHandler::Suspend(PulseHandler::kPulseSuspend);
        }
    }
#endif

    if (main_device.startsWith("ALSA:"))
    {
#ifdef USE_ALSA
        settings.TrimDeviceType();
        ret = new AudioOutputALSA(settings);
#else
        VERBOSE(VB_IMPORTANT, "Audio output device is set to an ALSA device "
                              "but ALSA support is not compiled in!");
#endif
    }
    else if (main_device.startsWith("JACK:"))
    {
#ifdef USE_JACK
        settings.TrimDeviceType();
        ret = new AudioOutputJACK(settings);
#else
        VERBOSE(VB_IMPORTANT, "Audio output device is set to a JACK device "
                              "but JACK support is not compiled in!");
#endif
    }
    else if (main_device.startsWith("DirectX:"))
    {
#ifdef USING_MINGW
        ret = new AudioOutputDX(settings);
#else
        VERBOSE(VB_IMPORTANT, "Audio output device is set to DirectX device "
                              "but DirectX support is not compiled in!");
#endif
    }
    else if (main_device.startsWith("Windows:"))
    {
#ifdef USING_MINGW
        ret = new AudioOutputWin(settings);
#else
        VERBOSE(VB_IMPORTANT, "Audio output device is set to a Windows device "
                              "but Windows support is not compiled in!");
#endif
    }
#if defined(USING_OSS)
    else
        ret = new AudioOutputOSS(settings);
#elif CONFIG_DARWIN
    else
Order TrendFollowerAgent::bestRateOrder()
{
    QMap<double, Order> bestOrders;
    for(int i = 2; i <=  STOKS_NUMBER; ++i)
    {
        if(m_store.contains(i) && m_stocksInfo[i].lastPrice() &&
                ( (m_stocksInfo[i].getBestSellPrice()*1.005 <=  m_store.getMoney() && m_stocksInfo[i].getBestSellPrice()) ||
                  (m_stocksInfo[i].lastPrice() <= m_store.getMoney()) ) )
        {

            double upTrendValue1 = m_stocksInfo[i].trendValue(m_upTrendTime);
            double upTrendValue2 = 2*m_stocksInfo[i].trendValue(m_upTrendTime/2);
            double upTrendValue = 0;
            if(upTrendValue1 && upTrendValue2)
                upTrendValue = - 1.0/upTrendValue1 - 1.0/upTrendValue2;
            bestOrders.insertMulti(upTrendValue, Order(Order::SELL, i, 0, 0));
        }
        double downTrendValue =  - m_stocksInfo[i].trendValue(m_downTrendTime) - 2*m_stocksInfo[i].trendValue(m_downTrendTime/2);
        if(  m_stocksInfo[i].lastPrice() &&
              ( (m_stocksInfo[i].getBestBuyPrice()*1.025 <=  m_store.getMoney() && m_stocksInfo[i].getBestBuyPrice()) ||
                (m_stocksInfo[i].lastPrice() <= m_store.getMoney()) ))
        {
            bestOrders.insertMulti(downTrendValue, Order(Order::BUY, i, 0, 0));
        }
    }

    if(bestOrders.empty())
        return Order();

    QMutableMapIterator<double, Order> i(bestOrders);
    while (i.hasNext()) {
        i.next();
        if((1.0*qrand())/RAND_MAX < m_bestChooseChance)
        {
            Order order = i.value();
            qint32 price;
            if(m_stocksInfo[order.getStockId()].getBestSellPrice() && m_stocksInfo[order.getStockId()].getBestBuyPrice())
            {
                if(order.getTransactionType() == Order::SELL)
                {
                    price = m_stocksInfo[order.getStockId()].getBestSellPrice()*(1.005 - (0.03*qrand())/RAND_MAX);
                }
                else
                {
                    price = m_stocksInfo[order.getStockId()].getBestBuyPrice()*(0.095 + (0.03*qrand())/RAND_MAX);
                }
            }
            else price = m_stocksInfo[order.getStockId()].lastPrice();

            if(!price)
                continue;
            order.setPrice(price);

            qint32 maxAmount = m_store.getMoney()/price;
            qint32 amount = pow(pow(std::min(-i.key()/3.0, 1.075), 25.0 + qrand()%10), 2.0 + static_cast<double>(qrand())/RAND_MAX) *
                    (1 + static_cast<double>(2*qrand())/RAND_MAX) + 2 + qrand() % 5;
            if(maxAmount)
                amount %= maxAmount;
            order.setAmount(amount);
            if(order.getAmount()&& order.getPrice())
                return order;
        }
    }

    Order order = i.value();
    qint32 price;
    if(m_stocksInfo[order.getStockId()].getBestSellPrice() && m_stocksInfo[order.getStockId()].getBestBuyPrice())
    {
        if(order.getTransactionType() == Order::SELL)
        {
            price = m_stocksInfo[order.getStockId()].getBestSellPrice()*(1.005 - (0.03*qrand())/RAND_MAX);
        }
        else
        {
            price = m_stocksInfo[order.getStockId()].getBestBuyPrice()*(0.095 + (0.03*qrand())/RAND_MAX);
        }
    }
    else price = m_stocksInfo[order.getStockId()].lastPrice();
    if(!price)
        return Order();
    order.setPrice(price);

    qint32 maxAmount = m_store.getMoney()/price;
    qint32 amount = pow(pow(std::min(-i.key()/3.0, 1.075), 25.0 + qrand()%10), 2.0 + static_cast<double>(qrand())/RAND_MAX) *
            (1 + static_cast<double>(2*qrand())/RAND_MAX) + 2 + qrand() % 5;
    if(maxAmount)
        amount %= maxAmount;
    order.setAmount(amount);
    if(order.getAmount()&& order.getPrice())
        return order;
    else return Order();
}
Example #12
0
bool setupTVs(bool ismaster, bool &error)
{
    error = false;
    QString localhostname = gContext->GetHostName();

    MSqlQuery query(MSqlQuery::InitCon());

    if (ismaster)
    {
        // Hack to make sure recorded.basename gets set if the user
        // downgrades to a prior version and creates new entries
        // without it.
        if (!query.exec("UPDATE recorded SET basename = CONCAT(chanid, '_', "
                        "DATE_FORMAT(starttime, '%Y%m%d%H%i00'), '_', "
                        "DATE_FORMAT(endtime, '%Y%m%d%H%i00'), '.nuv') "
                        "WHERE basename = '';"))
            MythContext::DBError("Updating record basename",
                                 query.lastQuery());

        // Hack to make sure record.station gets set if the user
        // downgrades to a prior version and creates new entries
        // without it.
        if (!query.exec("UPDATE channel SET callsign=chanid "
                        "WHERE callsign IS NULL OR callsign='';"))
            MythContext::DBError("Updating channel callsign",
                                 query.lastQuery());

        if (query.exec("SELECT MIN(chanid) FROM channel;"))
        {
            query.first();
            int min_chanid = query.value(0).toInt();
            if (!query.exec(QString("UPDATE record SET chanid = %1 "
                                    "WHERE chanid IS NULL;").arg(min_chanid)))
                MythContext::DBError("Updating record chanid",
                                     query.lastQuery());
        }
        else
            MythContext::DBError("Querying minimum chanid",
                                 query.lastQuery());

        MSqlQuery records_without_station(MSqlQuery::InitCon());
        records_without_station.prepare("SELECT record.chanid,"
                                        " channel.callsign FROM record LEFT JOIN channel"
                                        " ON record.chanid = channel.chanid WHERE record.station='';");
        records_without_station.exec();
        if (records_without_station.first())
        {
            MSqlQuery update_record(MSqlQuery::InitCon());
            update_record.prepare("UPDATE record SET station = :CALLSIGN"
                                  " WHERE chanid = :CHANID;");
            do
            {
                update_record.bindValue(":CALLSIGN",
                                        records_without_station.value(1));
                update_record.bindValue(":CHANID",
                                        records_without_station.value(0));
                if (!update_record.exec())
                {
                    MythContext::DBError("Updating record station",
                                         update_record.lastQuery());
                }
            } while (records_without_station.next());
        }
    }

    if (!query.exec(
                "SELECT cardid, hostname "
                "FROM capturecard "
                "ORDER BY cardid"))
    {
        MythContext::DBError("Querying Recorders", query);
        return false;
    }

    vector<uint>    cardids;
    vector<QString> hosts;
    while (query.next())
    {
        uint    cardid = query.value(0).toUInt();
        QString host   = query.value(1).toString();
        QString cidmsg = QString("Card %1").arg(cardid);

        if (host.isEmpty())
        {
            QString msg = cidmsg + " does not have a hostname defined.\n"
                          "Please run setup and confirm all of the capture cards.\n";

            VERBOSE(VB_IMPORTANT, msg);
            gContext->LogEntry("mythbackend", LP_CRITICAL,
                               "Problem with capture cards", msg);
            continue;
        }

        cardids.push_back(cardid);
        hosts.push_back(host);
    }

    for (uint i = 0; i < cardids.size(); i++)
    {
        if (hosts[i] == localhostname)
            new TVRec(cardids[i]);
    }

    for (uint i = 0; i < cardids.size(); i++)
    {
        uint    cardid = cardids[i];
        QString host   = hosts[i];
        QString cidmsg = QString("Card %1").arg(cardid);

        if (!ismaster)
        {
            if (host == localhostname)
            {
                TVRec *tv = TVRec::GetTVRec(cardid);
                if (tv->Init())
                {
                    EncoderLink *enc = new EncoderLink(cardid, tv);
                    tvList[cardid] = enc;
                }
                else
                {
                    gContext->LogEntry("mythbackend", LP_CRITICAL,
                                       "Problem with capture cards",
                                       cidmsg + " failed init");
                    delete tv;
                    // The master assumes card comes up so we need to
                    // set error and exit if a non-master card fails.
                    error = true;
                }
            }
        }
        else
        {
            if (host == localhostname)
            {
                TVRec *tv = TVRec::GetTVRec(cardid);
                if (tv->Init())
                {
                    EncoderLink *enc = new EncoderLink(cardid, tv);
                    tvList[cardid] = enc;
                }
                else
                {
                    gContext->LogEntry("mythbackend", LP_CRITICAL,
                                       "Problem with capture cards",
                                       cidmsg + "failed init");
                    delete tv;
                }
            }
            else
            {
                EncoderLink *enc = new EncoderLink(cardid, NULL, host);
                tvList[cardid] = enc;
            }
        }
    }

    if (tvList.empty())
    {
        cerr << "ERROR: no valid capture cards are defined in the database.\n";
        cerr << "Perhaps you should read the installation instructions?\n";
        gContext->LogEntry("mythbackend", LP_CRITICAL,
                           "No capture cards are defined",
                           "Please run the setup program.");
        return false;
    }

    return true;
}
Example #13
0
void KstEditViewObjectDialogI::updateWidgets() {
  // clear all the current widgets from the grid
  clearWidgets();

  // get the qt properties of the viewobject
  if (_viewObject) {
    _customWidget = _viewObject->configWidget();
    if (_customWidget) {
      _grid = new QGridLayout(_propertiesFrame, 1, 1);
      _customWidget->reparent(_propertiesFrame, QPoint(0, 0));
      _grid->addWidget(_customWidget, 0, 0);
      _viewObject->fillConfigWidget(_customWidget, _isNew);
      resize(minimumSizeHint());
      return;
    }
    
    //---------------------------------------------------------------
    // NOTE: due to Early return, nothing after this line is executed
    // if the view object provides a custom widget.

    int numProperties = _viewObject->metaObject()->numProperties(true);

    // create a new grid
    _grid = new QGridLayout(_propertiesFrame, numProperties, 2, 0, 8);
    _grid->setColStretch(0,0);
    _grid->setColStretch(1,1);
    
    // get the property names and types
    for (int i = 0; i < numProperties; i++) {
      const QMetaProperty* property = _viewObject->metaObject()->property(i, true);
      QString propertyType(property->type());
      QString propertyName(property->name());
     
      // for this property, get the meta-data map
      QMap<QString, QVariant> metaData = _viewObject->widgetHints(propertyName);
      
      if (!metaData.empty()) {
        QString friendlyName = metaData["_kst_label"].toString();
        QString widgetType = metaData["_kst_widgetType"].toString();
        metaData.erase("_kst_label");
        metaData.erase("_kst_widgetType");
        
        // use friendly name for label
        QLabel* propertyLabel = new QLabel(_propertiesFrame, "label-"+i);
        propertyLabel->setText(friendlyName);
        _grid->addWidget(propertyLabel,i,0);
        _widgets.append(propertyLabel);
        propertyLabel->show();
        
        // display different types of widgets depending on what dialogData specifies
        QWidget* propertyWidget = 0L;
        if (widgetType == "QSpinBox") {
          // insert a spinbox
          propertyWidget = new QSpinBox(_propertiesFrame, (propertyName+","+"value").latin1()); 
          propertyWidget->setProperty("value", _viewObject->property(property->name()));
        } else if (widgetType == "KColorButton") {
          // insert a colorbutton
          propertyWidget = new KColorButton(_propertiesFrame, (propertyName+","+"color").latin1());
          propertyWidget->setProperty("color", _viewObject->property(property->name()));
        } else if (widgetType == "QLineEdit") {
          // insert a text field
          propertyWidget = new QLineEdit(_propertiesFrame, (propertyName+","+"text").latin1());
          propertyWidget->setProperty("text", _viewObject->property(property->name()));
        } else if (widgetType == "KURLRequester") {
          // insert a url requester
          propertyWidget = new KURLRequester(_propertiesFrame, (propertyName+","+"url").latin1());
          propertyWidget->setProperty("url", _viewObject->property(property->name()));
        } else if (widgetType == "PenStyleWidget") {
          // insert a combobox with QT pen styles
          QComboBox* combo = new QComboBox(_propertiesFrame, (propertyName+","+"currentItem").latin1());
          fillPenStyleWidget(combo);
          propertyWidget = combo;
          propertyWidget->setProperty("currentItem", _viewObject->property(property->name()));
        } else if (widgetType == "QCheckBox") {
          // insert a checkbox
          propertyWidget = new QCheckBox(_propertiesFrame, (propertyName+","+"checked").latin1());
          propertyWidget->setProperty("checked", _viewObject->property(property->name()));
        } else if (widgetType == "KDoubleSpinBox") {
          // insert a double num spinbox
          KDoubleSpinBox* input = new KDoubleSpinBox(_propertiesFrame, (propertyName+","+"value").latin1());
          // need this so that setValue later works
          input->setMinValue(metaData["minValue"].toDouble());
          input->setMaxValue(metaData["maxValue"].toDouble());
          input->setLineStep(metaData["lineStep"].toDouble());
          metaData.erase("minValue");
          metaData.erase("maxValue");
          metaData.erase("lineStep");
          propertyWidget = input; 
          propertyWidget->setProperty("value", _viewObject->property(property->name())); 
        } else if (widgetType == "KFontCombo") {
          // insert a font combo box
          propertyWidget = new KFontCombo(_propertiesFrame, (propertyName+","+"currentText").latin1());
          propertyWidget->setProperty("currentText", _viewObject->property(property->name()));  
        } else if (widgetType == "HJustifyCombo") {
          // insert a combo box filled with horizontal justifications
          QComboBox* combo = new QComboBox(_propertiesFrame, (propertyName+","+"currentItem").latin1());
          fillHJustifyWidget(combo);
          propertyWidget = combo;
          propertyWidget->setProperty("currentItem", _viewObject->property(property->name()));
        } else if (widgetType == "VJustifyCombo") {
          // insert a combo box filled with vertical justifications
          QComboBox* combo = new QComboBox(_propertiesFrame, (propertyName+","+"currentItem").latin1());
          fillVJustifyWidget(combo);
          propertyWidget = combo;
          propertyWidget->setProperty("currentItem", _viewObject->property(property->name()));
        }
        
        // also set any additional properties specified by metaData
        for (QMap<QString, QVariant>::ConstIterator it = metaData.begin(); it != metaData.end(); ++it) {
          propertyWidget->setProperty(it.key().latin1(), it.data());
        }
        
        _grid->addWidget(propertyWidget, i, 1);
        _inputWidgets.append(propertyWidget);
        propertyWidget->show();
      }   
    }
    
    // geometry cleanup
    resize(minimumSizeHint());
    //setFixedHeight(height());
  }
}
Example #14
0
bool CSVToolWindow::importStart()
{
  QString mapname = atlasWindow()->map();
  CSVAtlas *atlas = _atlasWindow->getAtlas();

  if (mapname.isEmpty())
  {
    QStringList mList = atlas->mapList();

    if(mList.isEmpty())
    {
      _msghandler->message(QtWarningMsg, tr("No Maps Loaded"),
                           tr("<p>There are no maps loaded to select from. "
                              "Either load an atlas that contains maps or "
                              "create a new one before continuing."));
      return false;
    }

    mList.sort();
    bool valid;
    mapname = QInputDialog::getItem(this, tr("Select Map"), tr("Select Map:"),
                                    mList, 0, FALSE, &valid);
    if (!valid)
      return false;
  }

  CSVMap map = atlas->map(mapname);
  map.simplify();
  QList<CSVMapField> fields = map.fields();

  if (map.name() != mapname || fields.isEmpty())
  {
    _msghandler->message(QtWarningMsg, tr("Invalid Map"),
                         tr("<p>The selected map does not appear to be valid."));
    return false;
  }

  CSVMap::Action action = map.action();
  if (action != CSVMap::Insert)
  {
    _msghandler->message(QtWarningMsg, tr("Action not implemented"),
                         tr("<p>The action %1 for this map is not supported.")
                         .arg(CSVMap::actionToName(action)));
    return false;
  }

  if (!_data || _data->rows() < 1)
  {
    _msghandler->message(QtWarningMsg, tr("No data"),
                         tr("<p>There are no data to process. "
                            "Load a CSV file before continuing."));
    return false;
  }

  int total = _data->rows();
  int current = 0, error = 0, ignored = 0;

  if (! _log)
    _log = new LogWindow(this);

  if(usetransaction) QSqlQuery begin("BEGIN;");

  QString errMsg;
  if(!map.sqlPre().trimmed().isEmpty())
  {
    if(usetransaction) QSqlQuery savepoint("SAVEPOINT presql;");
    QSqlQuery pre;
    if(!pre.exec(map.sqlPre()))
    {
      errMsg = QString("ERROR Running Pre SQL query: %1").arg(pre.lastError().text());
      _log->_log->append("\n\n----------------------\n");
      _log->_log->append(errMsg);
      _log->show();
      _log->raise();
      if(map.sqlPreContinueOnError())
      {
        _log->_log->append(tr("\n\nContinuing with rest of import\n\n"));
        if(usetransaction) QSqlQuery sprollback("ROLLBACK TO SAVEPOINT presql;");
        if(usetransaction) QSqlQuery savepoint("RELEASE SAVEPOINT presql;");
      }
      else
      {
        if(usetransaction) QSqlQuery rollback("ROLLBACK;");
        _msghandler->message(QtWarningMsg, tr("Error"),
                             tr("<p>There was an error running the Pre SQL "
                                "query. Please see the log for more details. "
                                "Aborting transaction."));
        return false;
      }
    }
  }

  QString progresstext(tr("Importing %1: %2 rows out of %3"));
  int expected = total;
  QProgressDialog *progress = new QProgressDialog(progresstext
                                        .arg(map.name()).arg(0).arg(expected),
                                        tr("Cancel"), 0, expected, this);
  progress->setWindowModality(Qt::WindowModal);
  bool userCanceled = false;

  QString query;
  QString front;
  QString back;
  QString value;
  QString label;
  QVariant var;

  QStringList errorList;

  for(current = 0; current < total; ++current)
  {
    if(usetransaction) QSqlQuery savepoint("SAVEPOINT csvinsert;");
    if(action == CSVMap::Insert)
    {
      query = QString("INSERT INTO %1 ").arg(map.table());
      front = "(";
      back = " VALUES(";
      QList<CSVMapField> fields = map.fields();
      QMap<QString,QVariant> values;
      for (int i = 0; i < fields.size(); i++)
      {
        switch(fields.at(i).action())
        {
          case CSVMapField::Action_UseColumn:
          {
            value = _data->value(current, fields.at(i).column()-1);
            if(value.isNull())
            {
              switch (fields.at(i).ifNullAction())
              {
                case CSVMapField::UseDefault:
                  continue;
                case CSVMapField::UseEmptyString:
                {
                  var = QVariant(QString(""));
                  break;
                }
                case CSVMapField::UseAlternateValue:
                {
                  var = QVariant(fields.at(i).valueAlt());
                  break;
                }
                case CSVMapField::UseAlternateColumn:
                {
                  value = _data->value(current, fields.at(i).columnAlt()-1);
                  if(value.isNull())
                  {
                    switch (fields.at(i).ifNullActionAlt())
                    {
                      case CSVMapField::UseDefault:
                        continue;
                      case CSVMapField::UseEmptyString:
                      {
                        var = QVariant(QString(""));
                        break;
                      }
                      case CSVMapField::UseAlternateValue:
                      {
                        var = QVariant(fields.at(i).valueAlt());
                        break;
                      }
                      default: // Nothing
                        var = QVariant(QString::null);
                    }
                  }
                  else
                    var = QVariant(value);
                  break;
                }
                default: // Nothing
                  var = QVariant(QString::null);
              }
            }
            else
              var = QVariant(value);
            break;
          }
          case CSVMapField::Action_UseEmptyString:
          {
            var = QVariant(QString(""));
            break;
          }
          case CSVMapField::Action_UseAlternateValue:
          {
            var = QVariant(fields.at(i).valueAlt());
            break;
          }
          case CSVMapField::Action_UseNull:
          {
            var = QVariant(QString::null);
            break;
          }
          default:
            continue;
        }

        label = ":" + fields.at(i).name();
        if(!values.empty())
        {
          front += ", ";
          back  += ", ";
        }
        values.insert(label, var);
        front += fields.at(i).name();
        back  += label;
      }

      if(values.empty())
      {
        ignored++;
        errMsg = QString("IGNORED Record %1: There are no columns to insert").arg(current+1);
        errorList.append(errMsg);
        continue;
      }

      front += ") ";
      back += ")";
      query += front + back;
      QSqlQuery qry;
      qry.prepare(query);

      QMap<QString,QVariant>::iterator vit;
      for(vit = values.begin(); vit != values.end(); ++vit)
        qry.bindValue(vit.key(), vit.value());

      if(!qry.exec())
      {
        if(usetransaction) QSqlQuery sprollback("ROLLBACK TO SAVEPOINT csvinsert;");
        error++;
        errMsg = QString("ERROR Record %1: %2").arg(current+1).arg(qry.lastError().text());
        errorList.append(errMsg);
      }
    }
    if (progress->wasCanceled())
    {
      userCanceled = true;
      break;
    }
    if(! (current % 1000))
    {
      progress->setLabelText(progresstext.arg(map.name()).arg(current).arg(expected));
      progress->setValue(current);
    }
  }
  progress->setValue(total);

  if (error || ignored || userCanceled)
  {
    _log->_log->append(tr("Map: %1\n"
                          "Table: %2\n"
                          "Method: %3\n\n"
                          "Total Records: %4\n"
                          "# Processed:   %5\n"
                          "# Ignored:     %6\n"
                          "# Errors:      %7\n\n")
                          .arg(map.name()).arg(map.table())
                          .arg(CSVMap::actionToName(map.action()))
                          .arg(total).arg(current).arg(ignored).arg(error));
    _log->_log->append(errMsg);
    _log->_log->append(errorList.join("\n"));
    _log->show();
    _log->raise();
    if (_msghandler &&  // log messages there's a non-interactive message handler
        qobject_cast<XAbstractMessageHandler*>(_msghandler) &&
        ! qobject_cast<InteractiveMessageHandler*>(_msghandler))
      _msghandler->message(error ? QtCriticalMsg : QtWarningMsg,
                           tr("Import Processing Status"),
                           _log->_log->toPlainText());
  }

  if (! userCanceled && ! map.sqlPost().trimmed().isEmpty())
  {
    QSqlQuery post;
    if(!post.exec(map.sqlPost()))
    {
      errMsg = QString("ERROR Running Post SQL query: %1").arg(post.lastError().text());
      _log->_log->append("\n\n----------------------\n");
      _log->_log->append(errMsg);
      _log->show();
      _log->raise();
      if(usetransaction) QSqlQuery rollback("ROLLBACK;");
      _msghandler->message(QtCriticalMsg, tr("Error"),
                           tr("<p>There was an error running the post sql "
                              "query and changes were rolled back. "
                              "Please see the log for more details."));
      return false;
    }
  }

  if (userCanceled)
  {
    if(usetransaction) QSqlQuery rollback("ROLLBACK;");
    _log->_log->append(tr("\n\nImport canceled by user. Changes were rolled back."));

    return false;
  }

  if(usetransaction) QSqlQuery commit("COMMIT");
  if (! error)
  {
    _msghandler->message(QtDebugMsg, tr("Import Complete"),
                         tr("The import of %1 completed successfully.")
                         .arg(_currentDir));
    return true;
  }

  return false;
}
GroupWise::ContactDetails PollSearchResultsTask::extractUserDetails( Field::FieldList & fields )
{
	ContactDetails cd;
	cd.status = GroupWise::Invalid;
	cd.archive = false;
	// read the supplied fields, set metadata and status.
	Field::SingleField * sf;
	if ( ( sf = fields.findSingleField ( Field::NM_A_SZ_AUTH_ATTRIBUTE ) ) )
		cd.authAttribute = sf->value().toString();
	if ( ( sf = fields.findSingleField ( Field::NM_A_SZ_DN ) ) )
		cd.dn =sf->value().toString().toLower(); // HACK: lowercased DN
	if ( ( sf = fields.findSingleField ( Field::KOPETE_NM_USER_DETAILS_CN ) ) )
		cd.cn = sf->value().toString();
	if ( ( sf = fields.findSingleField ( Field::KOPETE_NM_USER_DETAILS_GIVEN_NAME ) ) )
		cd.givenName = sf->value().toString();
	if ( ( sf = fields.findSingleField ( Field::KOPETE_NM_USER_DETAILS_SURNAME ) ) )
		cd.surname = sf->value().toString();
	if ( ( sf = fields.findSingleField ( Field::KOPETE_NM_USER_DETAILS_FULL_NAME ) ) )
		cd.fullName = sf->value().toString();
	if ( ( sf = fields.findSingleField ( Field::KOPETE_NM_USER_DETAILS_ARCHIVE_FLAG ) ) )
		cd.archive = ( sf->value().toInt() == 1 );
	if ( ( sf = fields.findSingleField ( Field::NM_A_SZ_STATUS ) ) )
		cd.status = sf->value().toInt();
	if ( ( sf = fields.findSingleField ( Field::NM_A_SZ_MESSAGE_BODY ) ) )
		cd.awayMessage = sf->value().toString();
	Field::MultiField * mf;
	QMap< QString, QVariant > propMap;
	if ( ( mf = fields.findMultiField ( Field::NM_A_FA_INFO_DISPLAY_ARRAY ) ) )
	{
		Field::FieldList fl = mf->fields();
		const Field::FieldListIterator end = fl.end();
		for ( Field::FieldListIterator it = fl.begin(); it != end; ++it )
		{
			// assumes each property only present once
			// check in logintask.cpp and if it's a multi field,
			// get the value of this instance, check if it's already in the property map and append if found.
			Field::SingleField * propField = dynamic_cast<Field::SingleField *>( *it );
			if ( propField )
			{
				QString propName = propField->tag();
				QString propValue = propField->value().toString();
				propMap.insert( propName, propValue );
			}
			else
			{
				Field::MultiField * propList = dynamic_cast<Field::MultiField*>( *it );
				if ( propList )
				{
					QString parentName = propList->tag();
					Field::FieldList propFields = propList->fields();
					const Field::FieldListIterator end = propFields.end();
					for ( Field::FieldListIterator it = propFields.begin(); it != end; ++it )
					{
						propField = dynamic_cast<Field::SingleField *>( *it );
						if ( propField )
						{
							QString propValue = propField->value().toString();
							QString contents = propMap[ propField->tag() ].toString();
							if ( !contents.isEmpty() )
								contents.append( ", " );
							contents.append( propField->value().toString());
							propMap.insert( propField->tag(), contents );
						}
					}
				}
			}
		}
	}
	if ( !propMap.empty() )
	{
		cd.properties = propMap;
	}
	return cd;
}