void LocalHTTPServer::respondToClient(QTcpSocket * socket)
{
    QTextStream stream(socket);
    stream << "HTTP/1.0 200 Ok\r\n";
    socket->close();
}
Example #2
0
GTEST_TEST(MemoryReadStream, getData) {
	static const byte data[3] = { 0 };
	Common::MemoryReadStream stream(data);

	EXPECT_EQ(stream.getData(), data);
}
Example #3
0
OrcFile::OrcFile(const std::string &filename)
{
	std::ifstream stream(filename.c_str(), std::ios_base::in | std::ios_base::binary);
	read(stream);
}
Example #4
0
CC_FILE_ERROR SinusxFilter::loadFile(QString filename, ccHObject& container, LoadParameters& parameters)
{
	//open file
	QFile file(filename);
	if (!file.open(QFile::ReadOnly))
		return CC_FERR_READING;
	QTextStream stream(&file);

	QString currentLine("C");
	ccPolyline* currentPoly = 0;
	ccPointCloud* currentVertices = 0;
	unsigned lineNumber = 0;
	CurveType curveType = INVALID;
	unsigned cpIndex = 0;
	CC_FILE_ERROR result = CC_FERR_NO_ERROR;
	CCVector3d Pshift(0,0,0);
	bool firstVertex = true;

	while (!currentLine.isEmpty() && file.error() == QFile::NoError)
	{
		currentLine = stream.readLine();
		++lineNumber;

		if (currentLine.startsWith("C "))
		{
			//ignore comments
			continue;
		}
		else if (currentLine.startsWith("B"))
		{
			//new block
			if (currentPoly)
			{
				if (	currentVertices
					&&	currentVertices->size() != 0
					&& currentVertices->resize(currentVertices->size())
					&&	currentPoly->addPointIndex(0,currentVertices->size()) )
				{
					container.addChild(currentPoly);
				}
				else
				{
					delete currentPoly;
				}
				currentPoly = 0;
				currentVertices = 0;

			}
			//read type
			QStringList tokens = currentLine.split(QRegExp("\\s+"),QString::SkipEmptyParts);
			if (tokens.size() < 2 || tokens[1].length() > 1)
			{
				ccLog::Warning(QString("[SinusX] Line %1 is corrupted").arg(lineNumber));
				result = CC_FERR_MALFORMED_FILE;
				continue;
			}
			QChar curveTypeChar = tokens[1].at(0);
			curveType = INVALID;
			if (curveTypeChar == SHORTCUT[CUREV_S])
				curveType = CUREV_S;
			else if (curveTypeChar == SHORTCUT[CURVE_P])
				curveType = CURVE_P;
			else if (curveTypeChar == SHORTCUT[CURVE_N])
				curveType = CURVE_N;
			else if (curveTypeChar == SHORTCUT[CURVE_C])
				curveType = CURVE_C;

			if (curveType == INVALID)
			{
				ccLog::Warning(QString("[SinusX] Unhandled curve type '%1' on line '%2'!").arg(curveTypeChar).arg(lineNumber));
				result = CC_FERR_MALFORMED_FILE;
				continue;
			}

			//TODO: what about the local coordinate system and scale?! (7 last values)
			if (tokens.size() > 7)
			{
			}

			//block is ready
			currentVertices = new ccPointCloud("vertices");
			currentPoly = new ccPolyline(currentVertices);
			currentPoly->addChild(currentVertices);
			currentVertices->setEnabled(false);
			cpIndex = 0;
		}
		else if (currentPoly)
		{
			if (currentLine.startsWith("CN"))
			{
				if (currentLine.length() > 3)
				{
					QString name = currentLine.right(currentLine.length()-3);
					currentPoly->setName(name);
				}
			}
			else if (currentLine.startsWith("CP"))
			{
				QStringList tokens = currentLine.split(QRegExp("\\s+"),QString::SkipEmptyParts);

				switch (cpIndex)
				{
				case 0: //first 'CP' line
					{
						//expected: CP + 'connected' + 'closed' flags
						bool ok = (tokens.size() == 3);
						if (ok)
						{
							bool ok1 = true, ok2 = true;
							int isConnected = tokens[1].toInt(&ok1);
							int isClosed = tokens[2].toInt(&ok2);
							ok = ok1 && ok2;
							if (ok)
							{
								if (isConnected == 0)
								{
									//points are not connected?!
									//--> we simply hide the polyline and display its vertices
									currentPoly->setVisible(false);
									currentVertices->setEnabled(true);
								}
								currentPoly->setClosed(isClosed != 0);
							}
						}
						if (!ok)
						{
							ccLog::Warning(QString("[SinusX] Line %1 is corrupted (expected: 'CP connected_flag closed_flag')").arg(lineNumber));
							result = CC_FERR_MALFORMED_FILE;
							continue;
						}
						++cpIndex;
					}
					break;

				case 1: //second 'CP' line
					{
						if (curveType == CUREV_S)
						{
							++cpIndex;
							//no break: we go directly to the next case (cpIndex = 2)
						}
						else if (curveType == CURVE_P)
						{
							//nothing particular for profiles (they are not handled in the same way in CC!)
							++cpIndex;
							break;
						}
						else if (curveType == CURVE_N)
						{
							//expected: CP + const_altitude
							bool ok = (tokens.size() == 2);
							if (ok)
							{
								double z = tokens[1].toDouble(&ok);
								if (ok)
									currentPoly->setMetaData(ccPolyline::MetaKeyConstAltitude(),QVariant(z));
							}
							if (!ok)
							{
								ccLog::Warning(QString("[SinusX] Line %1 is corrupted (expected: 'CP const_altitude')").arg(lineNumber));
								result = CC_FERR_MALFORMED_FILE;
								continue;
							}
							++cpIndex;
							break;
						}
						else if (curveType == CURVE_C)
						{
							//skip the next 16 values
							int skipped = tokens.size()-1; //all but the 'CP' keyword
							while (skipped < 16 && !currentLine.isEmpty() && file.error() == QFile::NoError)
							{
								currentLine = stream.readLine();
								++lineNumber;
								tokens = currentLine.split(QRegExp("\\s+"),QString::SkipEmptyParts);
								skipped += tokens.size();
							}
							assert(skipped == 16); //no more than 16 normally!
							++cpIndex;
							break;
						}
						else
						{
							assert(false);
							++cpIndex;
							break;
						}
					}

				case 2:
					{
						//CP + base plane: 0 = (XY), 1 = (YZ), 2 = (ZX)
						bool ok = (tokens.size() == 2);
						if (ok)
						{
							int vertDir = 2;
							QChar basePlaneChar = tokens[1].at(0);
							if (basePlaneChar == '0')
								vertDir = 2;
							else if (basePlaneChar == '1')
								vertDir = 0;
							else if (basePlaneChar == '2')
								vertDir = 1;
							else
								ok = false;
							if (ok)
								currentPoly->setMetaData(ccPolyline::MetaKeyUpDir(),QVariant(vertDir));
						}
						if (!ok)
						{
							ccLog::Warning(QString("[SinusX] Line %1 is corrupted (expected: 'CP base_plane')").arg(lineNumber));
							result = CC_FERR_MALFORMED_FILE;
							continue;
						}
					}
					++cpIndex;
					break;

				default:
					//ignored
					break;
				}
			}
			else if (!currentLine.isEmpty())
			{
				assert(currentVertices);

				//shoud be a point!
				QStringList tokens = currentLine.split(QRegExp("\\s+"),QString::SkipEmptyParts);
				bool ok = (tokens.size() == 4);
				if (ok)
				{
					CCVector3d Pd;
					Pd.x = tokens[0].toDouble(&ok);
					if (ok)
					{
						Pd.y = tokens[1].toDouble(&ok);
						if (ok)
						{
							Pd.z = tokens[2].toDouble(&ok);
							if (ok)
							{
								//resize vertex cloud if necessary
								if (	currentVertices->size() == currentVertices->capacity()
									&&	!currentVertices->reserve(currentVertices->size() + 10))
								{
									delete currentPoly;
									return CC_FERR_NOT_ENOUGH_MEMORY;
								}
								//first point: check for 'big' coordinates
								if (firstVertex/*currentVertices->size() == 0*/)
								{
									firstVertex = false;
									if (HandleGlobalShift(Pd,Pshift,parameters))
									{
										if (currentPoly)
											currentPoly->setGlobalShift(Pshift);
										else
											currentVertices->setGlobalShift(Pshift);
										ccLog::Warning("[SinusX::loadFile] Polyline has been recentered! Translation: (%.2f,%.2f,%.2f)",Pshift.x,Pshift.y,Pshift.z);
									}
								}

								currentVertices->addPoint(CCVector3::fromArray((Pd+Pshift).u));
							}
						}
					}
				}
				if (!ok)
				{
					ccLog::Warning(QString("[SinusX] Line %1 is corrupted (expected: 'X Y Z Key ...')").arg(lineNumber));
					result = CC_FERR_MALFORMED_FILE;
					continue;
				}
			}
		}
	}

	//don't forget the last polyline!
	if (currentPoly)
	{
		if (	currentVertices
			&&	currentVertices->size() != 0
			&&	currentVertices->resize(currentVertices->size())
			&&	currentPoly->addPointIndex(0,currentVertices->size()) )
		{
			container.addChild(currentPoly);
		}
	}

	return result;
}
Example #5
0
QMenu* SslButton::buildCertMenu(QMenu *parent, const QSslCertificate& cert,
                                const QList<QSslCertificate>& userApproved, int pos)
{
    QString cn = QStringList(cert.subjectInfo(QSslCertificate::CommonName)).join(QChar(';'));
    QString ou = QStringList(cert.subjectInfo(QSslCertificate::OrganizationalUnitName)).join(QChar(';'));
    QString org = QStringList(cert.subjectInfo(QSslCertificate::Organization)).join(QChar(';'));
    QString country = QStringList(cert.subjectInfo(QSslCertificate::CountryName)).join(QChar(';'));
    QString state = QStringList(cert.subjectInfo(QSslCertificate::StateOrProvinceName)).join(QChar(';'));
    QString issuer = QStringList(cert.issuerInfo(QSslCertificate::CommonName)).join(QChar(';'));
    if (issuer.isEmpty())
        issuer = QStringList(cert.issuerInfo(QSslCertificate::OrganizationalUnitName)).join(QChar(';'));
    QString md5 = Utility::formatFingerprint(cert.digest(QCryptographicHash::Md5).toHex());
    QString sha1 = Utility::formatFingerprint(cert.digest(QCryptographicHash::Sha1).toHex());
    QString serial = QString::fromUtf8(cert.serialNumber(), true);
    QString effectiveDate = cert.effectiveDate().date().toString();
    QString expiryDate = cert.expiryDate().date().toString();
    QString sna = QStringList(cert.alternateSubjectNames().values()).join(" ");

    QString details;
    QTextStream stream(&details);

    stream << QLatin1String("<html><body>");

    stream << tr("<h3>Certificate Details</h3>");

    stream << QLatin1String("<table>");
    stream << addCertDetailsField(tr("Common Name (CN):"), Utility::escape(cn));
    stream << addCertDetailsField(tr("Subject Alternative Names:"), Utility::escape(sna)
                                  .replace(" ", "<br/>"));
    stream << addCertDetailsField(tr("Organization (O):"), Utility::escape(org));
    stream << addCertDetailsField(tr("Organizational Unit (OU):"), Utility::escape(ou));
    stream << addCertDetailsField(tr("State/Province:"), Utility::escape(state));
    stream << addCertDetailsField(tr("Country:"), Utility::escape(country));
    stream << addCertDetailsField(tr("Serial:"), Utility::escape(serial), true);
    stream << QLatin1String("</table>");

    stream << tr("<h3>Issuer</h3>");

    stream << QLatin1String("<table>");
    stream << addCertDetailsField(tr("Issuer:"), Utility::escape(issuer));
    stream << addCertDetailsField(tr("Issued on:"), Utility::escape(effectiveDate));
    stream << addCertDetailsField(tr("Expires on:"), Utility::escape(expiryDate));
    stream << QLatin1String("</table>");

    stream << tr("<h3>Fingerprints</h3>");

    stream << QLatin1String("<table>");
    stream << addCertDetailsField(tr("MD 5:"), Utility::escape(md5), true);
    stream << addCertDetailsField(tr("SHA-1:"), Utility::escape(sha1), true);
    stream << QLatin1String("</table>");

    if (userApproved.contains(cert)) {
        stream << tr("<p><b>Note:</b> This certificate was manually approved</p>");
    }
    stream << QLatin1String("</body></html>");

    QString txt;
    if (pos > 0) {
        txt += QString(2*pos, ' ');
        if (!Utility::isWindows()) {
            // doesn't seem to work reliably on Windows
            txt += QChar(0x21AA); // nicer '->' symbol
            txt += QChar(' ');
        }
    }

    QString certId = cn.isEmpty() ? ou : cn;

    if (QSslSocket::systemCaCertificates().contains(cert)) {
        txt += certId;
    } else {
        if (isSelfSigned(cert)) {
            txt += tr("%1 (self-signed)").arg(certId);
        } else {
            txt += tr("%1").arg(certId);
        }
    }

    // create label first
    QLabel *label = new QLabel(parent);
    label->setStyleSheet(QLatin1String("QLabel { padding: 8px; background-color: #fff; }"));
    label->setText(details);
    // plug label into widget action
    QWidgetAction *action = new QWidgetAction(parent);
    action->setDefaultWidget(label);
    // plug action into menu
    QMenu *menu = new QMenu(parent);
    menu->menuAction()->setText(txt);
    menu->addAction(action);

    return menu;

}
Example #6
0
void PSPApplication::getAppName(QString filename)
{
    QFile file(filename);
    
    if(!(file.open(QIODevice::ReadOnly)))
    {
//        throw QPSPManagerPBPException();
    }
    
    QDataStream stream(&file);

    quint8 signature[4];
    //Signature
    for (int i = 0; i < 4; i++)
    {
        stream >> signature[i];
    }

    //Version
    quint32 version;
    stream >> version;

    //Files offset
    unsigned long offset[8];
    stream.readRawData((char *)(offset), sizeof(offset));


    //PARAM.SFO
    int paramSFOSize = offset[1] - offset[0];
    char *buffer=new char[paramSFOSize];
    
    if (stream.readRawData(buffer, paramSFOSize) != paramSFOSize)
    {
 //       throw QPSPManagerPBPException();
    }

    //We have the SFO file in the buffer, now we have to
    //seek the title field on it
    //TODO: document the SFO file format ffs!
    SFOHeader *header = (SFOHeader *)buffer;
    SFODir *entries = (SFODir *)(buffer+sizeof(SFOHeader));
    
    
    for (int i = 0; i < header->nitems; i++)
    {
        if (strcmp(buffer+header->fields_table_offs+entries[i].field_offs, "TITLE") == 0)
        {
            char *title=new char[entries[i].size];
            strncpy(title, buffer + header->values_table_offs+entries[i].val_offs, entries[i].size);
            appTitle = QString::fromUtf8(title);
        }
	    if (strcmp(buffer+header->fields_table_offs+entries[i].field_offs, "DISC_ID") == 0)
        {
            char *title=new char[entries[i].size];
            strncpy(title, buffer + header->values_table_offs+entries[i].val_offs, entries[i].size);
            appID = QString::fromUtf8(title);
        }
		 if (strcmp(buffer+header->fields_table_offs+entries[i].field_offs, "PSP_SYSTEM_VER") == 0)
        {
            char *title=new char[entries[i].size];
            strncpy(title, buffer + header->values_table_offs+entries[i].val_offs, entries[i].size);
            appFW = QString::fromUtf8(title);
        }
    }

    file.close();
}
void MotionCombinator::update(JointRequest& jointRequest)
{
  specialActionOdometry += theSpecialActionsOutput.odometryOffset;

  copy(theLegJointRequest, jointRequest, theStiffnessSettings, Joints::headYaw, Joints::headPitch);

  copy(theArmJointRequest, jointRequest, theStiffnessSettings, Joints::firstArmJoint, Joints::rHand);
  copy(theLegJointRequest, jointRequest, theStiffnessSettings, Joints::firstLegJoint, Joints::rAnkleRoll);

  ASSERT(jointRequest.isValid());

  // Find fully active motion and set MotionInfo
  if(theLegMotionSelection.ratios[theLegMotionSelection.targetMotion] == 1.f)
  {
    // default values
    motionInfo.motion = theLegMotionSelection.targetMotion;
    motionInfo.isMotionStable = true;
    motionInfo.upcomingOdometryOffset = Pose2f();

    Pose2f odometryOffset;
    switch(theLegMotionSelection.targetMotion)
    {
      case MotionRequest::walk:
        odometryOffset = theWalkingEngineOutput.odometryOffset;
        motionInfo.walkRequest = theWalkingEngineOutput.executedWalk;
        motionInfo.upcomingOdometryOffset = theWalkingEngineOutput.upcomingOdometryOffset;
        break;
      case MotionRequest::kick:
        odometryOffset = theKickEngineOutput.odometryOffset;
        motionInfo.kickRequest = theKickEngineOutput.executedKickRequest;
        motionInfo.isMotionStable = theKickEngineOutput.isStable;
        break;
      case MotionRequest::specialAction:
        odometryOffset = specialActionOdometry;
        specialActionOdometry = Pose2f();
        motionInfo.specialActionRequest = theSpecialActionsOutput.executedSpecialAction;
        motionInfo.isMotionStable = theSpecialActionsOutput.isMotionStable;
        break;
      case MotionRequest::getUp:
        motionInfo.isMotionStable = false;
        odometryOffset = theGetUpEngineOutput.odometryOffset;
        break;
      case MotionRequest::stand:
      default:
        break;
    }

    if(theRobotInfo.hasFeature(RobotInfo::zGyro) && (theFallDownState.state == FallDownState::upright || theLegMotionSelection.targetMotion == MotionRequest::getUp))
    {
      Vector3f rotatedGyros = theInertialData.orientation * theInertialData.gyro.cast<float>();
      odometryOffset.rotation = rotatedGyros.z() * theFrameInfo.cycleTime;
    }

    odometryData += odometryOffset;
  }

  if(emergencyOffEnabled && motionInfo.motion != MotionRequest::getUp)
  {
    if(theFallDownState.state == FallDownState::falling && motionInfo.motion != MotionRequest::specialAction)

    {
      safeFall(jointRequest);
      centerHead(jointRequest);
      currentRecoveryTime = 0;

      ASSERT(jointRequest.isValid());
    }
    else if(theFallDownState.state == FallDownState::onGround && motionInfo.motion != MotionRequest::specialAction)
    {
      centerHead(jointRequest);
    }
    else
    {
      if(theFallDownState.state == FallDownState::upright)
      {
        headYawInSafePosition = false;
        headPitchInSafePosition = false;
      }

      if(currentRecoveryTime < recoveryTime)
      {
        currentRecoveryTime += 1;
        float ratio = (1.f / float(recoveryTime)) * currentRecoveryTime;
        for(int i = 0; i < Joints::numOfJoints; i++)
        {
          jointRequest.stiffnessData.stiffnesses[i] = 30 + int(ratio * float(jointRequest.stiffnessData.stiffnesses[i] - 30));
        }
      }
    }
  }

  if(debugArms)
    debugReleaseArms(jointRequest);
  eraseStiffness(jointRequest);

  float sum = 0;
  int count = 0;
  for(int i = Joints::lHipYawPitch; i < Joints::numOfJoints; i++)
  {
    if(jointRequest.angles[i] != JointAngles::off && jointRequest.angles[i] != JointAngles::ignore &&
       lastJointRequest.angles[i] != JointAngles::off && lastJointRequest.angles[i] != JointAngles::ignore)
    {
      sum += std::abs(jointRequest.angles[i] - lastJointRequest.angles[i]);
      count++;
    }
  }
  PLOT("module:MotionCombinator:deviations:JointRequest:legsOnly", sum / count);
  for(int i = 0; i < Joints::lHipYawPitch; i++)
  {
    if(jointRequest.angles[i] != JointAngles::off && jointRequest.angles[i] != JointAngles::ignore &&
       lastJointRequest.angles[i] != JointAngles::off && lastJointRequest.angles[i] != JointAngles::ignore)
    {
      sum += std::abs(jointRequest.angles[i] - lastJointRequest.angles[i]);
      count++;
    }
  }
  PLOT("module:MotionCombinator:deviations:JointRequest:all", sum / count);

  sum = 0;
  count = 0;
  for(int i = Joints::lHipYawPitch; i < Joints::numOfJoints; i++)
  {
    if(lastJointRequest.angles[i] != JointAngles::off && lastJointRequest.angles[i] != JointAngles::ignore)
    {
      sum += std::abs(lastJointRequest.angles[i] - theJointAngles.angles[i]);
      count++;
    }
  }
  PLOT("module:MotionCombinator:differenceToJointData:legsOnly", sum / count);

  for(int i = 0; i < Joints::lHipYawPitch; i++)
  {
    if(lastJointRequest.angles[i] != JointAngles::off && lastJointRequest.angles[i] != JointAngles::ignore)
    {
      sum += std::abs(lastJointRequest.angles[i] - theJointAngles.angles[i]);
      count++;
    }
  }
  lastJointRequest = jointRequest;
  PLOT("module:MotionCombinator:differenceToJointData:all", sum / count);

#ifndef NDEBUG
  if(!jointRequest.isValid())
  {
    {
      std::string logDir = "";
#ifdef TARGET_ROBOT
      logDir = "../logs/";
#endif
      OutMapFile stream(logDir + "jointRequest.log");
      stream << jointRequest;
      OutMapFile stream2(logDir + "motionSelection.log");
      stream2 << theLegMotionSelection;
    }
    ASSERT(false);
  }
#endif
}
Example #8
0
void tst_QLayout::smartMaxSize()
{
    QVector<int> expectedWidths;

    QFile f(QLatin1String(SRCDIR "/baseline/smartmaxsize"));

    QCOMPARE(f.open(QIODevice::ReadOnly | QIODevice::Text), true);

    QTextStream stream(&f);

    while(!stream.atEnd()) {
        QString line = stream.readLine(200);
        expectedWidths.append(line.section(QLatin1Char(' '), 6, -1, QString::SectionSkipEmpty).toInt());
    }
    f.close();

    int sizeCombinations[] = { 0, 10, 20, QWIDGETSIZE_MAX};
    QSizePolicy::Policy policies[] = {  QSizePolicy::Fixed,
                                        QSizePolicy::Minimum,
                                        QSizePolicy::Maximum,
                                        QSizePolicy::Preferred,
                                        QSizePolicy::Expanding,
                                        QSizePolicy::MinimumExpanding,
                                        QSizePolicy::Ignored
                                     };
    Qt::Alignment alignments[] = {  0,
                                    Qt::AlignLeft,
                                    Qt::AlignRight,
                                    Qt::AlignHCenter
                                 };

    int expectedIndex = 0;
    int regressionCount = 0;
    for (int p = 0; p < sizeof(policies)/sizeof(QSizePolicy::Policy); ++p) {
        QSizePolicy sizePolicy;
        sizePolicy.setHorizontalPolicy(policies[p]);
        for (int min = 0; min < sizeof(sizeCombinations)/sizeof(int); ++min) {
            int minSize = sizeCombinations[min];
            for (int max = 0; max < sizeof(sizeCombinations)/sizeof(int); ++max) {
                int maxSize = sizeCombinations[max];
                for (int sh = 0; sh < sizeof(sizeCombinations)/sizeof(int); ++sh) {
                    int sizeHint = sizeCombinations[sh];
                    for (int a = 0; a < sizeof(alignments)/sizeof(int); ++a) {
                        Qt::Alignment align = alignments[a];
                        QSize sz = qSmartMaxSize(QSize(sizeHint, 1), QSize(minSize, 1), QSize(maxSize, 1), sizePolicy, align);
                        int width = sz.width();
#if 0
                        qDebug() << expectedIndex << sizePolicy.horizontalPolicy() << align << minSize << sizeHint << maxSize << width;
#else
                        int expectedWidth = expectedWidths[expectedIndex];
                        if (width != expectedWidth) {
                            qDebug() << "error at index" << expectedIndex << ":" << sizePolicy.horizontalPolicy() << align << minSize << sizeHint << maxSize << width;
                            ++regressionCount;
                        }
#endif
                        ++expectedIndex;
                    }
                }
            }
        }
    }
    QCOMPARE(regressionCount, 0);
}
Example #9
0
bool OperaBookmarksImporter::import(const QString &path)
{
	QFile file(getSuggestedPath(path));

	if (!file.open(QIODevice::ReadOnly))
	{
		emit importFinished(BookmarksImport, FailedImport, 0);

		return false;
	}

	QTextStream stream(&file);
	stream.setCodec("UTF-8");

	QString line(stream.readLine());

	if (line != QLatin1String("Opera Hotlist version 2.0"))
	{
		emit importFinished(BookmarksImport, FailedImport, 0);

		return false;
	}

	emit importStarted(BookmarksImport, -1);

	if (m_optionsWidget)
	{
		if (m_optionsWidget->hasToRemoveExisting())
		{
			removeAllBookmarks();

			if (m_optionsWidget->isImportingIntoSubfolder())
			{
				setImportFolder(BookmarksManager::addBookmark(BookmarksModel::FolderBookmark, {{BookmarksModel::TitleRole, m_optionsWidget->getSubfolderName()}}, BookmarksManager::getModel()->getRootItem()));
			}
			else
			{
				setImportFolder(BookmarksManager::getModel()->getRootItem());
			}
		}
		else
		{
			setAllowDuplicates(m_optionsWidget->areDuplicatesAllowed());
			setImportFolder(m_optionsWidget->getTargetFolder());
		}
	}

	const int estimatedAmount((file.size() > 0) ? (file.size() / 250) : 0);
	int totalAmount(0);

	BookmarksManager::getModel()->beginImport(getImportFolder(), estimatedAmount, qMin(estimatedAmount, 100));

	BookmarksItem *bookmark(nullptr);
	OperaBookmarkEntry type(NoEntry);
	bool isHeader(true);

	while (!stream.atEnd())
	{
		line = stream.readLine();

		if (isHeader && (line.isEmpty() || line.at(0) != QLatin1Char('#')))
		{
			continue;
		}

		isHeader = false;

		if (line.startsWith(QLatin1String("#URL")))
		{
			bookmark = BookmarksManager::addBookmark(BookmarksModel::UrlBookmark, {}, getCurrentFolder());
			type = UrlEntry;

			++totalAmount;
		}
		else if (line.startsWith(QLatin1String("#FOLDER")))
		{
			bookmark = BookmarksManager::addBookmark(BookmarksModel::FolderBookmark, {}, getCurrentFolder());
			type = FolderStartEntry;

			++totalAmount;
		}
		else if (line.startsWith(QLatin1String("#SEPERATOR")))
		{
			bookmark = BookmarksManager::addBookmark(BookmarksModel::SeparatorBookmark, {}, getCurrentFolder());
			type = SeparatorEntry;

			++totalAmount;
		}
		else if (line == QLatin1String("-"))
		{
			type = FolderEndEntry;
		}
		else if (line.startsWith(QLatin1String("\tURL=")) && bookmark)
		{
			const QUrl url(line.section(QLatin1Char('='), 1, -1));

			if (!areDuplicatesAllowed() && BookmarksManager::hasBookmark(url))
			{
				bookmark->remove();
				bookmark = nullptr;
			}
			else
			{
				bookmark->setData(url, BookmarksModel::UrlRole);
			}
		}
		else if (line.startsWith(QLatin1String("\tNAME=")) && bookmark)
		{
			bookmark->setData(line.section(QLatin1Char('='), 1, -1), BookmarksModel::TitleRole);
		}
		else if (line.startsWith(QLatin1String("\tDESCRIPTION=")) && bookmark)
		{
			bookmark->setData(line.section(QLatin1Char('='), 1, -1).replace(QLatin1String("\x02\x02"), QLatin1String("\n")), BookmarksModel::DescriptionRole);
		}
		else if (line.startsWith(QLatin1String("\tSHORT NAME=")) && bookmark)
		{
			const QString keyword(line.section(QLatin1Char('='), 1, -1));

			if (!BookmarksManager::hasKeyword(keyword))
			{
				bookmark->setData(keyword, BookmarksModel::KeywordRole);
			}
		}
		else if (line.startsWith(QLatin1String("\tCREATED=")) && bookmark)
		{
			bookmark->setData(QDateTime::fromTime_t(line.section(QLatin1Char('='), 1, -1).toUInt()), BookmarksModel::TimeAddedRole);
		}
		else if (line.startsWith(QLatin1String("\tVISITED=")) && bookmark)
		{
			bookmark->setData(QDateTime::fromTime_t(line.section(QLatin1Char('='), 1, -1).toUInt()), BookmarksModel::TimeVisitedRole);
		}
		else if (line.isEmpty())
		{
			if (bookmark)
			{
				if (type == FolderStartEntry)
				{
					setCurrentFolder(bookmark);
				}

				bookmark = nullptr;
			}
			else if (type == FolderEndEntry)
			{
				goToParent();
			}

			type = NoEntry;
		}
	}

	BookmarksManager::getModel()->endImport();

	emit importFinished(BookmarksImport, SuccessfullImport, totalAmount);

	file.close();

	return true;
}
Example #10
0
SkMovie* SkMovie::DecodeMemory(const void* data, size_t length) {
    SkMemoryStream stream(data, length, false);
    return SkMovie::DecodeStream(&stream);
}
QString QStandardPaths::writableLocation(StandardLocation type)
{
    switch (type) {
    case HomeLocation:
        return QDir::homePath();
    case TempLocation:
        return QDir::tempPath();
    case CacheLocation:
    case GenericCacheLocation:
    {
        // http://standards.freedesktop.org/basedir-spec/basedir-spec-0.6.html
        QString xdgCacheHome = QFile::decodeName(qgetenv("XDG_CACHE_HOME"));
        if (isTestModeEnabled())
            xdgCacheHome = QDir::homePath() + QLatin1String("/.qttest/cache");
        if (xdgCacheHome.isEmpty())
            xdgCacheHome = QDir::homePath() + QLatin1String("/.cache");
        if (type == QStandardPaths::CacheLocation)
            appendOrganizationAndApp(xdgCacheHome);
        return xdgCacheHome;
    }
    case DataLocation:
    case GenericDataLocation:
    {
        QString xdgDataHome = QFile::decodeName(qgetenv("XDG_DATA_HOME"));
        if (isTestModeEnabled())
            xdgDataHome = QDir::homePath() + QLatin1String("/.qttest/share");
        if (xdgDataHome.isEmpty())
            xdgDataHome = QDir::homePath() + QLatin1String("/.local/share");
        if (type == QStandardPaths::DataLocation)
            appendOrganizationAndApp(xdgDataHome);
        return xdgDataHome;
    }
    case ConfigLocation:
    case GenericConfigLocation:
    {
        // http://standards.freedesktop.org/basedir-spec/latest/
        QString xdgConfigHome = QFile::decodeName(qgetenv("XDG_CONFIG_HOME"));
        if (isTestModeEnabled())
            xdgConfigHome = QDir::homePath() + QLatin1String("/.qttest/config");
        if (xdgConfigHome.isEmpty())
            xdgConfigHome = QDir::homePath() + QLatin1String("/.config");
        return xdgConfigHome;
    }
    case RuntimeLocation:
    {
        const uid_t myUid = geteuid();
        // http://standards.freedesktop.org/basedir-spec/latest/
        QString xdgRuntimeDir = QFile::decodeName(qgetenv("XDG_RUNTIME_DIR"));
        if (xdgRuntimeDir.isEmpty()) {
            const QString userName = QFileSystemEngine::resolveUserName(myUid);
            xdgRuntimeDir = QDir::tempPath() + QLatin1String("/runtime-") + userName;
            QDir dir(xdgRuntimeDir);
            if (!dir.exists()) {
                if (!QDir().mkdir(xdgRuntimeDir)) {
                    qWarning("QStandardPaths: error creating runtime directory %s: %s", qPrintable(xdgRuntimeDir), qPrintable(qt_error_string(errno)));
                    return QString();
                }
            }
            qWarning("QStandardPaths: XDG_RUNTIME_DIR not set, defaulting to '%s'", qPrintable(xdgRuntimeDir));
        }
        // "The directory MUST be owned by the user"
        QFileInfo fileInfo(xdgRuntimeDir);
        if (fileInfo.ownerId() != myUid) {
            qWarning("QStandardPaths: wrong ownership on runtime directory %s, %d instead of %d", qPrintable(xdgRuntimeDir),
                     fileInfo.ownerId(), myUid);
            return QString();
        }
        // "and he MUST be the only one having read and write access to it. Its Unix access mode MUST be 0700."
        QFile file(xdgRuntimeDir);
        const QFile::Permissions wantedPerms = QFile::ReadUser | QFile::WriteUser | QFile::ExeUser;
        if (file.permissions() != wantedPerms && !file.setPermissions(wantedPerms)) {
            qWarning("QStandardPaths: wrong permissions on runtime directory %s", qPrintable(xdgRuntimeDir));
            return QString();
        }
        return xdgRuntimeDir;
    }
    default:
        break;
    }

    // http://www.freedesktop.org/wiki/Software/xdg-user-dirs
    QString xdgConfigHome = QFile::decodeName(qgetenv("XDG_CONFIG_HOME"));
    if (xdgConfigHome.isEmpty())
        xdgConfigHome = QDir::homePath() + QLatin1String("/.config");
    QFile file(xdgConfigHome + QLatin1String("/user-dirs.dirs"));
    if (!isTestModeEnabled() && file.open(QIODevice::ReadOnly)) {
        QHash<QString, QString> lines;
        QTextStream stream(&file);
        // Only look for lines like: XDG_DESKTOP_DIR="$HOME/Desktop"
        QRegExp exp(QLatin1String("^XDG_(.*)_DIR=(.*)$"));
        while (!stream.atEnd()) {
            const QString &line = stream.readLine();
            if (exp.indexIn(line) != -1) {
                const QStringList lst = exp.capturedTexts();
                const QString key = lst.at(1);
                QString value = lst.at(2);
                if (value.length() > 2
                    && value.startsWith(QLatin1Char('\"'))
                    && value.endsWith(QLatin1Char('\"')))
                    value = value.mid(1, value.length() - 2);
                // Store the key and value: "DESKTOP", "$HOME/Desktop"
                lines[key] = value;
            }
        }

        QString key;
        switch (type) {
        case DesktopLocation:
            key = QLatin1String("DESKTOP");
            break;
        case DocumentsLocation:
            key = QLatin1String("DOCUMENTS");
            break;
        case PicturesLocation:
            key = QLatin1String("PICTURES");
            break;
        case MusicLocation:
            key = QLatin1String("MUSIC");
            break;
        case MoviesLocation:
            key = QLatin1String("VIDEOS");
            break;
        case DownloadLocation:
            key = QLatin1String("DOWNLOAD");
            break;
        default:
            break;
        }
        if (!key.isEmpty()) {
            QString value = lines.value(key);
            if (!value.isEmpty()) {
                // value can start with $HOME
                if (value.startsWith(QLatin1String("$HOME")))
                    value = QDir::homePath() + value.mid(5);
                return value;
            }
        }
    }

    QString path;
    switch (type) {
    case DesktopLocation:
        path = QDir::homePath() + QLatin1String("/Desktop");
        break;
    case DocumentsLocation:
        path = QDir::homePath() + QLatin1String("/Documents");
       break;
    case PicturesLocation:
        path = QDir::homePath() + QLatin1String("/Pictures");
        break;

    case FontsLocation:
        path = QDir::homePath() + QLatin1String("/.fonts");
        break;

    case MusicLocation:
        path = QDir::homePath() + QLatin1String("/Music");
        break;

    case MoviesLocation:
        path = QDir::homePath() + QLatin1String("/Videos");
        break;
    case DownloadLocation:
        path = QDir::homePath() + QLatin1String("/Downloads");
        break;
    case ApplicationsLocation:
        path = writableLocation(GenericDataLocation) + QLatin1String("/applications");
        break;

    default:
        break;
    }

    return path;
}
bool QmlProfilerFileReader::loadQzt(QIODevice *device)
{
    QDataStream stream(device);
    stream.setVersion(QDataStream::Qt_5_5);

    QByteArray magic;
    stream >> magic;
    if (magic != QByteArray("QMLPROFILER")) {
        emit error(tr("Invalid magic: %1").arg(QLatin1String(magic)));
        return false;
    }

    qint32 dataStreamVersion;
    stream >> dataStreamVersion;

    if (dataStreamVersion > QDataStream::Qt_DefaultCompiledVersion) {
        emit error(tr("Unknown data stream version: %1").arg(dataStreamVersion));
        return false;
    }
    stream.setVersion(dataStreamVersion);

    stream >> m_traceStart >> m_traceEnd;

    QBuffer buffer;
    QDataStream bufferStream(&buffer);
    bufferStream.setVersion(dataStreamVersion);
    QByteArray data;
    updateProgress(device);

    stream >> data;
    buffer.setData(qUncompress(data));
    buffer.open(QIODevice::ReadOnly);
    bufferStream >> m_eventTypes;
    buffer.close();
    emit typesLoaded(m_eventTypes);
    updateProgress(device);

    stream >> data;
    buffer.setData(qUncompress(data));
    buffer.open(QIODevice::ReadOnly);
    bufferStream >> m_notes;
    buffer.close();
    emit notesLoaded(m_notes);
    updateProgress(device);

    const int eventBufferLength = 1024;
    QVector<QmlEvent> eventBuffer(eventBufferLength);
    int eventBufferIndex = 0;
    while (!stream.atEnd()) {
        stream >> data;
        buffer.setData(qUncompress(data));
        buffer.open(QIODevice::ReadOnly);
        while (!buffer.atEnd()) {
            if (isCanceled())
                return false;
            QmlEvent &event = eventBuffer[eventBufferIndex];
            bufferStream >> event;
            if (bufferStream.status() == QDataStream::Ok) {
                if (event.typeIndex() >= m_eventTypes.length()) {
                    emit error(tr("Invalid type index %1").arg(event.typeIndex()));
                    return false;
                }
                m_loadedFeatures |= (1ULL << m_eventTypes[event.typeIndex()].feature());
            } else if (bufferStream.status() == QDataStream::ReadPastEnd) {
                break; // Apparently EOF is a character so we end up here after the last event.
            } else if (bufferStream.status() == QDataStream::ReadCorruptData) {
                emit error(tr("Corrupt data before position %1.").arg(device->pos()));
                return false;
            } else {
                Q_UNREACHABLE();
            }
            if (++eventBufferIndex == eventBufferLength) {
                emit qmlEventsLoaded(eventBuffer);
                eventBufferIndex = 0;
            }
        }
        buffer.close();
        updateProgress(device);
    }
    eventBuffer.resize(eventBufferIndex);
    emit qmlEventsLoaded(eventBuffer);
    emit success();
    return true;
}
void PTXPointReader::scanForAABB() {
    // read bounding box
    double x(0), y(0), z(0);
    // TODO: verify that this initial values are ok 
    double minx = std::numeric_limits<float>::max();
    double miny = std::numeric_limits<float>::max();
    double minz = std::numeric_limits<float>::max();
    double maxx = -std::numeric_limits<float>::max();
    double maxy = -std::numeric_limits<float>::max();
    double maxz = -std::numeric_limits<float>::max();
    double intensity(0);
    bool firstPoint = true;
    bool pleaseStop = false;
    long currentChunk = 0;
    long count = 0;
    double tr[16];
    vector<double> split;
    for (const auto &file : files) {
        fstream stream(file, ios::in);
        currentChunk = 0;
        getlined(stream, split);
        while (!pleaseStop) {
            if (1 == split.size()) {
                if (!loadChunk(&stream, currentChunk, tr)) {
                    break;
                }
            }
            while (true) {
                getlined(stream, split);
                if (4 == split.size() || 7 == split.size()) {
                    x = split[0];
                    y = split[1];
                    z = split[2];
                    intensity = split[3];
                    if (0.5 != intensity) {
                        Point p = transform(tr, x, y, z);
                        if (firstPoint) {
                            maxx = minx = p.position.x;
                            maxy = miny = p.position.y;
                            maxz = minz = p.position.z;
                            firstPoint = false;
                        } else {
                            minx = p.position.x < minx ? p.position.x : minx;
                            maxx = p.position.x > maxx ? p.position.x : maxx;
                            miny = p.position.y < miny ? p.position.y : miny;
                            maxy = p.position.y > maxy ? p.position.y : maxy;
                            minz = p.position.z < minz ? p.position.z : minz;
                            maxz = p.position.z > maxz ? p.position.z : maxz;
                        }
                        count++;
                        if (0 == count % 1000000)
                            cout << "AABB-SCANNING: " << count << " points; " << currentChunk << " chunks" << endl;
                    }
                } else {
                    break;
                }
            }
            if (stream.eof()) {
                pleaseStop = true;
                break;
            }
            currentChunk++;
        }
        stream.close();
    }

    counts[path] = count;
    AABB lAABB(Vector3<double>(minx, miny, minz), Vector3<double>(maxx, maxy, maxz));
    PTXPointReader::aabbs[path] = lAABB;
   
}
void
GDBGetStack::HandleSuccess
	(
	const JString& cmdData
	)
{
	JTreeNode* root       = (GetTree())->GetRoot();
	JIndex initFrameIndex = 0;

	const JString& data = GetLastResult();
	std::istringstream stream(data.GetCString());

	JIndexRange origRange, newRange;
	JStringPtrMap<JString> map(JPtrArrayT::kDeleteAll);
	JString frameName, fileName;
	while (framePattern.MatchAfter(data, origRange, &newRange))
		{
		stream.seekg(newRange.last);
		if (!GDBLink::ParseMap(stream, &map))
			{
			(CMGetLink())->Log("invalid data map");
			break;
			}
		origRange.first = origRange.last = ((std::streamoff) stream.tellg()) + 1;

		JString* s;
		JIndex frameIndex;
		if (!map.GetElement("level", &s))
			{
			(CMGetLink())->Log("missing frame index");
			continue;
			}
		if (!s->ConvertToUInt(&frameIndex))
			{
			(CMGetLink())->Log("frame index is not integer");
			continue;
			}

		frameName = *s;
		while (frameName.GetLength() < kFrameIndexWidth)
			{
			frameName.PrependCharacter('0');
			}
		frameName += ":  ";

		JString* fnName;
		if (!map.GetElement("func", &fnName))
			{
			(CMGetLink())->Log("missing function name");
			continue;
			}
		frameName += *fnName;

		if (map.GetElement("file", &s))
			{
			fileName = *s;
			}

		JIndex lineIndex = 0;
		if (map.GetElement("line", &s) &&
			!s->ConvertToUInt(&lineIndex))
			{
			(CMGetLink())->Log("line number is not integer");
			continue;
			}

		CMStackFrameNode* node =
			new CMStackFrameNode(root, frameIndex, frameName,
								 fileName, lineIndex);
		assert( node != NULL );
		root->Prepend(node);

		if (assertPattern.Match(*fnName))
			{
			initFrameIndex = frameIndex + 1;
			}
		}

	itsArgsCmd->Send();

	(GetWidget())->FinishedLoading(initFrameIndex);
}
Example #15
0
bool Exporter_json::write(const std::string& name, const Model& model) const
{
	std::ofstream stream(name + ".json");

	if (!stream)
	{
		return false;
	}

	stream << "{" << std::endl;

	stream << "\t\"geometry\":" << std::endl;
	stream << "\t{" << std::endl;

	//Groups
	stream << "\t\t\"parts\":" << std::endl;
	stream << "\t\t[" << std::endl;

	for (size_t i = 0; i < model.groups.size(); ++i)
	{
		stream << "\t\t\t{" << std::endl;

		stream << "\t\t\t\t\"material_index\": ";
		stream << model.groups[i].material_index;
		stream << "," << std::endl;

		stream << "\t\t\t\t\"start_index\": ";
		stream << model.groups[i].start_index;
		stream << "," << std::endl;

		stream << "\t\t\t\t\"num_indices\": ";
		stream << model.groups[i].num_indices;
		stream << std::endl;

		stream << "\t\t\t}";

		if (i < model.groups.size() - 1)
		{
			stream << "," << std::endl;
		}
	}

	stream << std::endl;

	stream << "\t\t]," << std::endl << std::endl;

	//Primitive Topology
	stream << "\t\t\"primitive_topology\": \"triangle_list\"," << std::endl << std::endl;

	stream << "\t\t\"vertices\": " << std::endl;
	stream << "\t\t{" << std::endl;

	//Positions
	if (model.has_positions())
	{
		stream << "\t\t\t\"positions\": " << std::endl;
		stream << "\t\t\t[" << std::endl;

		stream << "\t\t\t\t";

		for (size_t i = 0; i < model.positions.size(); ++i)
		{
			stream << model.positions[i].x << "," << model.positions[i].y << "," << model.positions[i].z;

			if (i < model.positions.size() - 1)
			{
				stream << ",";
			}

			if ((i + 1) % 8 == 0)
			{
				stream << std::endl << "\t\t\t\t";
			}
		}

		stream << std::endl;
		stream << "\t\t\t]," << std::endl << std::endl;
	}

	//Texture_2D Coordinates
	if (model.has_texture_coordinates())
	{
		stream << "\t\t\t\"texture_coordinates_0\": " << std::endl;
		stream << "\t\t\t[" << std::endl;

		stream << "\t\t\t\t";

		for (size_t i = 0; i < model.texture_coordinates.size(); ++i)
		{
			stream << model.texture_coordinates[i].x << "," << model.texture_coordinates[i].y;

			if (i < model.texture_coordinates.size() - 1)
			{
				stream << ",";
			}

			if ((i + 1) % 8 == 0)
			{
				stream << std::endl << "\t\t\t\t";
			}
		}

		stream << std::endl;
		stream << "\t\t\t]," << std::endl << std::endl;
	}

	//Normals
	if (model.has_normals())
	{
		stream << "\t\t\t\"normals\": " << std::endl;
		stream << "\t\t\t[" << std::endl;

		stream << "\t\t\t\t";

		for (size_t i = 0; i < model.normals.size(); ++i)
		{
			stream << model.normals[i].x << "," << model.normals[i].y << "," << model.normals[i].z;

			if (i < model.normals.size() - 1)
			{
				stream << ",";
			}

			if ((i + 1) % 8 == 0)
			{
				stream << std::endl << "\t\t\t\t";
			}
		}

		stream << std::endl;
		stream << "\t\t\t]";

		if (model.has_tangent_space()) {
			stream << ",";
		}

		stream << std::endl << std::endl;
	}

	//Tangent Space
	if (model.has_tangent_space())
	{
		//Tangents
		stream << "\t\t\t\"tangents_and_bitangent_signs\": " << std::endl;
		stream << "\t\t\t[" << std::endl;

		stream << "\t\t\t\t";

		for (size_t i = 0; i < model.tangents_and_bitangent_signs.size(); ++i)
		{
			stream << model.tangents_and_bitangent_signs[i].x << ","
				   << model.tangents_and_bitangent_signs[i].y << ","
				   << model.tangents_and_bitangent_signs[i].z << ","
				   << model.tangents_and_bitangent_signs[i].w;

			if (i < model.tangents_and_bitangent_signs.size() - 1)
			{
				stream << ",";
			}

			if ((i + 1) % 8 == 0)
			{
				stream << std::endl << "\t\t\t\t";
			}
		}

		stream << std::endl;
		stream << "\t\t\t]" << std::endl << std::endl;
	}

	stream << "\t\t}," << std::endl << std::endl;

	//Indices
	stream << "\t\t\"indices\": " << std::endl;
	stream << "\t\t[" << std::endl;

	stream << "\t\t\t";

	for (size_t i = 0; i < model.indices.size(); ++i)
	{
		stream << model.indices[i];

		if (i < model.indices.size() - 1)
		{
			stream << ",";
		}

		if ((i + 1) % 8 == 0)
		{
			stream << std::endl << "\t\t\t";
		}
	}

	stream << std::endl;
	stream << "\t\t]" << std::endl;

	stream << "\t}" << std::endl;

	stream << "}";

	return true;
}
Example #16
0
short PMenuItem::parse( QFileInfo *fi, PMenu *menu )
{
  QString lang = KApplication::getKApplication()->getLocale()->language();
  real_name = fi->fileName().copy();
  old_name = real_name;
  QString type_string = "";
  int pos = fi->fileName().find(".kdelnk");
  if( pos >= 0 )
    text_name = fi->fileName().left(pos);
  else
    text_name = fi->fileName();
  if( !(fi->isWritable()) )
    read_only = TRUE;
  if( menu != NULL )
    {
      QString file_name = fi->absFilePath();
      file_name += "/.directory";
      QFileInfo fi_config(file_name);
      if( fi_config.isReadable() ) 
	{
	  KConfig kconfig(file_name);
	  kconfig.setGroup("KDE Desktop Entry");
	  comment         = kconfig.readEntry("Comment");
	  text_name       = kconfig.readEntry("Name", text_name);
	  pixmap_name     = kconfig.readEntry("MiniIcon");
	  big_pixmap_name = kconfig.readEntry("Icon");
	  dir_path        = fi->dirPath(TRUE);
	}
      entry_type  = submenu;
      sub_menu    = menu;
      cmenu       = new CPopupMenu;      
    }
  else
    {
      // test if file is a kdelnk file
      QFile file(fi->absFilePath());
      if( file.open(IO_ReadOnly) )
	{
	  char s[19];
	  int r = file.readLine(s, 18);
	  if(r > -1)
	    {
	      s[r] = '\0';
	      if(QString(s).left(17) != "# KDE Config File") 
		{
		  file.close();
		  return -1;
		}
	    }
	}
      else
	{
	  file.close();
	  return -1;
	}
      // parse file
      file.at(0);
      QTextStream stream(&file);
      QString current_line, key, value;
      QString temp_swallow_title, temp_term_opt, temp_exec_path, temp_text_name;
      QString temp_use_term, temp_pattern, temp_protocols, temp_extensions, temp_url_name;
      QString temp_dev_name, temp_mount_point, temp_fs_type, temp_umount_pixmap_name;
      QString temp_dev_read_only = "0";
      temp_use_term = "0";
      bool inside_group = FALSE;
      int equal_pos;
      comment = "";
      while(!stream.eof())
	{
	  current_line = stream.readLine();
	  if( current_line[0] == '#' )
	    continue;
	  if( !inside_group ) 
	    {
	      if( current_line != "[KDE Desktop Entry]" ) 
		{
		  continue;
		}
	      else
		{
		  inside_group = TRUE;
		  continue;
		}
	    }
	  equal_pos = current_line.find('=');
	  if( equal_pos == -1 )
	    continue;
	  key = current_line.left(equal_pos).stripWhiteSpace();
	  value = current_line.right(current_line.length() - equal_pos - 1).stripWhiteSpace();
	  
	  if( key == "Exec" ) 
	    { command_name = value; continue; }
	  else if( key == "SwallowExec" )
	    { swallow_exec = value; continue; }
	  else if( key.left(7) == "Comment" )
	    { 
	      if( key == "Comment" )
		{
		  if( comment.isEmpty() )
		    comment = value;
		}
	      else 
		{
		  if( key == "Comment[" + lang + "]" )
		    comment = value;
		}
	      continue; 
	    }
	  else if( key.left(4) == "Name" )
	    { 
	      if( key == "Name" )
		{
		  if( temp_text_name.isEmpty() )
		    temp_text_name = value;
		}
	      else 
		{
		  if( key == "Name[" + lang + "]" )
		    temp_text_name = value;
		}
	      continue; 
	    }
	  else if( key == "MiniIcon" )
	    { pixmap_name = value; continue; }
	  else if( key == "Icon" )
	    { big_pixmap_name = value; continue; }
	  else if( key == "Type" )
	    { type_string = value; continue; }
	  else if( key == "SwallowTitle" )
	    { temp_swallow_title = value; continue; }
	  else if( key == "TerminalOptions" )
	    { temp_term_opt = value; continue; }
	  else if( key == "Path" )
	    { temp_exec_path = value; continue; }
	  else if( key == "Terminal" )
	    { temp_use_term = value; continue; }
	  else if( key == "BinaryPattern" )
	    { temp_pattern = value; continue; }
	  else if( key == "Protocols" )
	    { temp_protocols = value; continue; }
	  else if( key == "MimeType" )
	    { temp_extensions = value; continue; }
	  else if( key == "URL" )
	    { temp_url_name = value; continue; }
	  else if( key == "Dev" )
	    { temp_dev_name = value; continue; }
	  else if( key == "MountPoint" )
	    { temp_mount_point = value; continue; }
	  else if( key == "FSType" )
	    { temp_fs_type = value; continue; }
	  else if( key == "UnmountIcon" )
	    { temp_umount_pixmap_name = value; continue; }
	  else if( key == "ReadOnly" )
	    { temp_dev_read_only = value; continue; }
	}
      file.close();
      if( type_string.isEmpty() )
	return -1;
      if( !temp_text_name.isEmpty() )
	text_name = temp_text_name;
      if( type_string == "Application" ) 
	{
	  if( !swallow_exec.isEmpty() )
	    {
	      entry_type = swallow_com;
	      swallow_title = temp_swallow_title;
	    }
	  else
	    {
	      entry_type = unix_com;
	      term_opt   = temp_term_opt;
	    }
	  exec_path  = temp_exec_path;
	  dir_path   = fi->dirPath(TRUE);
	  if( temp_use_term == "0" )
	    use_term = 0;
	  else 
	    use_term = 1;
	  pattern    = temp_pattern;
	  protocols  = temp_protocols;
	  extensions = temp_extensions;
	}
      else if( type_string == "Link" )
	{
	  entry_type = url;
	  url_name   = temp_url_name;
	}
      else if( type_string == "FSDevice" )
	{
	  entry_type  = device;
	  dev_name    = temp_dev_name;
	  mount_point = temp_mount_point;
	  fs_type     = temp_fs_type;
	  umount_pixmap_name = temp_umount_pixmap_name;
	  if( temp_dev_read_only == "0" )
	    dev_read_only = 0;
	  else
	    dev_read_only = 1;
	}

//    if( !fi->isReadable() ) 
// 	return -1;
//       KConfig kconfig(fi->absFilePath());
//       kconfig.setGroup("KDE Desktop Entry");
//       command_name    = kconfig.readEntry("Exec");
//       swallow_exec    = kconfig.readEntry("SwallowExec");
//       comment         = kconfig.readEntry("Comment");
//       text_name       = kconfig.readEntry("Name", text_name);
//       pixmap_name     = kconfig.readEntry("MiniIcon");
//       big_pixmap_name = kconfig.readEntry("Icon");
//       type_string     = kconfig.readEntry("Type");
//       if( type_string == "Application" ) 
// 	{
// 	  if( !swallow_exec.isEmpty() )
// 	    {
// 	      entry_type = swallow_com;
// 	      swallow_title = kconfig.readEntry("SwallowTitle");
// 	    }
// 	  else
// 	    {
// 	      entry_type = unix_com;
// 	      term_opt   = kconfig.readEntry("TerminalOptions");
// 	    }
// 	  exec_path       = kconfig.readEntry("Path");
// 	  dir_path        = fi->dirPath(TRUE);
// 	  use_term        = kconfig.readNumEntry("Terminal");
// 	  pattern         = kconfig.readEntry("BinaryPattern");
// 	  protocols       = kconfig.readEntry("Protocols");
// 	  extensions      = kconfig.readEntry("MimeType");
// 	}
//       else if( type_string == "Link" )
// 	{
// 	  entry_type = url;
// 	  url_name   = kconfig.readEntry("URL");
// 	}
//       else if( type_string == "FSDevice" )
// 	{
// 	  entry_type  = device;
// 	  dev_name    = kconfig.readEntry("Dev");
// 	  mount_point = kconfig.readEntry("MountPoint");
// 	  fs_type     = kconfig.readEntry("FSType");
// 	  umount_pixmap_name = kconfig.readEntry("UnmountIcon");
// 	  dev_read_only = kconfig.readNumEntry("ReadOnly");
// 	}
    }
  
  // some code from kpanel
  QPixmap tmppix;
  pixmap = tmppix;
  if( !pixmap_name.isEmpty() ){
    pixmap = global_pix_loader->loadApplicationMiniIcon(pixmap_name, 16, 16);
  }
  if (pixmap.isNull() && !big_pixmap_name.isEmpty()){
    pixmap = global_pix_loader->loadApplicationMiniIcon(big_pixmap_name, 16, 16);
  }
  if (pixmap.isNull() && getType() == unix_com){
    QString tmp = real_name.copy();
    int pos = tmp.find(".kdelnk");
    if( pos >= 0 )
      tmp = tmp.left(pos);
    tmp.append(".xpm");
    pixmap = global_pix_loader->loadApplicationMiniIcon(tmp, 16, 16);
  }
  
  if (pixmap.isNull())
    pixmap = global_pix_loader->loadApplicationMiniIcon("mini-default.xpm", 16, 16);
  
  if (comment.isEmpty())
    comment = text_name;
  if (big_pixmap_name.isEmpty()){
    QString tmp = real_name.copy();
    int pos = tmp.find(".kdelnk");
    if( pos >= 0 )
      tmp = tmp.left(pos);
    tmp.append(".xpm");
    big_pixmap_name = tmp.copy();
  }
  // end kpanel

  return 0;
}
bool SkImageEncoder::encodeFile(const char file[], const SkBitmap& bm,
                                int quality) {
    quality = SkMin32(100, SkMax32(0, quality));
    SkFILEWStream   stream(file);
    return this->onEncode(&stream, bm, quality);
}
bool QTableModelHtmlWriter::write(QAdvancedTableView* view, bool all)
{
    if (!m_device->isWritable() && ! m_device->open(QIODevice::WriteOnly)) {
        qWarning() << "QTableModelHtmlWriter::writeAll: the device can not be opened for writing";
        return false;
    }
	QXmlStreamWriter stream(m_device);
	stream.setAutoFormatting(true);
	stream.setAutoFormattingIndent(2);

	stream.writeStartElement("html");
	stream.writeStartElement("head");
	stream.writeEndElement();

	stream.writeStartElement("body");
	stream.writeStartElement("table");
	stream.writeAttribute("border", view->showGrid()?"1":"0");
	if (view->showGrid()){
		stream.writeAttribute("style", "border-style:none");
	}
	//
	QPair<QModelIndex, QModelIndex> e;
	if (!all){
		e = selectionEdges(view->selectionModel()->selection());
	} else {
		e.first = view->model()->index(0, 0);
		e.second = view->model()->index(view->model()->rowCount() - 1, view->model()->columnCount() - 1);
	}
	if (m_includeHeader){
		// start tag <tr>
		stream.writeStartElement("tr");
		writeBorderStyle(stream, view->gridStyle());
		for (int c = e.first.column(); c <= e.second.column(); c++){
			if (all || !view->horizontalHeader()->isSectionHidden(c)){
				stream.writeStartElement("th");
				writeAlignment(stream, static_cast<Qt::AlignmentFlag>(view->model()->headerData(view->horizontalHeader()->visualIndex(c), Qt::Horizontal, Qt::TextAlignmentRole).toInt()));
				stream.writeStartElement("font");
				writeFontAttributes(stream, qvariant_cast<QFont>(view->model()->headerData(view->horizontalHeader()->visualIndex(c), Qt::Horizontal, Qt::FontRole)));
				stream.writeCharacters(view->model()->headerData(view->horizontalHeader()->visualIndex(c), Qt::Horizontal, Qt::DisplayRole).toString());
				stream.writeEndElement();
				// end tag <th>
				stream.writeEndElement();
			}
		}
		// end tag <tr>
		stream.writeEndElement();
	}
	for (int r = e.first.row(); r <= e.second.row(); r++){
		stream.writeStartElement("tr");
		for (int c = e.first.column(); c <= e.second.column(); c++){
			if (!view->horizontalHeader()->isSectionHidden(c)){
				stream.writeStartElement("td");
				writeAlignment(stream, static_cast<Qt::AlignmentFlag>(view->model()->index(r, view->horizontalHeader()->visualIndex(c)).data(Qt::TextAlignmentRole).toInt()));
				writeBorderStyle(stream, view->gridStyle());
				writeBackgroundColor(stream, qvariant_cast<QBrush>(view->filterProxyModel()->index(r, view->horizontalHeader()->visualIndex(c)).data(Qt::BackgroundRole)));
				writeDecoration(stream, view->model()->index(r, view->horizontalHeader()->visualIndex(c)).data(Qt::DecorationRole));
				stream.writeStartElement("font");
				writeFontAttributes(stream, qvariant_cast<QFont>(view->model()->index(r, view->horizontalHeader()->visualIndex(c)).data(Qt::FontRole)));
				writeCharacters(stream, view->model()->index(r, view->horizontalHeader()->visualIndex(c)).data(Qt::DisplayRole).toString());
				stream.writeEndElement();
				// end tag <td>
				stream.writeEndElement();
			}
		}
		// end tag <tr>
		stream.writeEndElement();
	}

	// end tag <table>
	stream.writeEndElement();
	// end tag <body>
	stream.writeEndElement();
	// end tag <html>
	stream.writeEndElement();
	return true;
}
Example #19
0
void MyMoneyStorageXML::writeFile(QIODevice* qf, IMyMoneySerialize* storage)
{
  Q_CHECK_PTR(qf);
  Q_CHECK_PTR(storage);
  if (!storage) {
    return;
  }
  m_storage = storage;

  // qDebug("XMLWRITER: Starting file write");
  m_doc = new QDomDocument("KMYMONEY-FILE");
  Q_CHECK_PTR(m_doc);
  QDomProcessingInstruction instruct = m_doc->createProcessingInstruction("xml", "version=\"1.0\" encoding=\"utf-8\"");
  m_doc->appendChild(instruct);

  QDomElement mainElement = m_doc->createElement("KMYMONEY-FILE");
  m_doc->appendChild(mainElement);

  QDomElement fileInfo = m_doc->createElement("FILEINFO");
  writeFileInformation(fileInfo);
  mainElement.appendChild(fileInfo);

  QDomElement userInfo = m_doc->createElement("USER");
  writeUserInformation(userInfo);
  mainElement.appendChild(userInfo);

  QDomElement institutions = m_doc->createElement("INSTITUTIONS");
  writeInstitutions(institutions);
  mainElement.appendChild(institutions);

  QDomElement payees = m_doc->createElement("PAYEES");
  writePayees(payees);
  mainElement.appendChild(payees);

  QDomElement tags = m_doc->createElement("TAGS");
  writeTags(tags);
  mainElement.appendChild(tags);

  QDomElement accounts = m_doc->createElement("ACCOUNTS");
  writeAccounts(accounts);
  mainElement.appendChild(accounts);

  QDomElement transactions = m_doc->createElement("TRANSACTIONS");
  writeTransactions(transactions);
  mainElement.appendChild(transactions);

  QDomElement keyvalpairs = writeKeyValuePairs(m_storage->pairs());
  mainElement.appendChild(keyvalpairs);

  QDomElement schedules = m_doc->createElement("SCHEDULES");
  writeSchedules(schedules);
  mainElement.appendChild(schedules);

  QDomElement equities = m_doc->createElement("SECURITIES");
  writeSecurities(equities);
  mainElement.appendChild(equities);

  QDomElement currencies = m_doc->createElement("CURRENCIES");
  writeCurrencies(currencies);
  mainElement.appendChild(currencies);

  QDomElement prices = m_doc->createElement("PRICES");
  writePrices(prices);
  mainElement.appendChild(prices);

  QDomElement reports = m_doc->createElement("REPORTS");
  writeReports(reports);
  mainElement.appendChild(reports);

  QDomElement budgets = m_doc->createElement("BUDGETS");
  writeBudgets(budgets);
  mainElement.appendChild(budgets);

  QDomElement onlineJobs = m_doc->createElement("ONLINEJOBS");
  writeOnlineJobs(onlineJobs);
  mainElement.appendChild(onlineJobs);

  QTextStream stream(qf);
  stream.setCodec("UTF-8");
  stream << m_doc->toString();

  delete m_doc;
  m_doc = 0;

  //hides the progress bar.
  signalProgress(-1, -1);

  // this seems to be nonsense, but it clears the dirty flag
  // as a side-effect.
  m_storage->setLastModificationDate(m_storage->lastModificationDate());

  m_storage = 0;
}
Example #20
0
/*----------------------------------------------------------------------
|   main
+---------------------------------------------------------------------*/
int
main(int argc, char** argv)
{
    NPT_COMPILER_UNUSED(argc);

    NPT_HttpRequestHandler *handler, *custom_handler;
    NPT_Reference<NPT_DataBuffer> buffer;
    NPT_Size size;
    bool result;
    PLT_RingBufferStreamReference ringbuffer_stream(new PLT_RingBufferStream());

    /* parse command line */
    ParseCommandLine(argv);

    /* create http server */
    PLT_HttpServer http_server(Options.port?Options.port:80);
    NPT_String url = "http://127.0.0.1:" + NPT_String::FromInteger(http_server.GetPort());
    NPT_String custom_url = url;

    if (!Options.path.IsEmpty()) {
        /* extract folder path */
        int index1 = Options.path.ReverseFind('\\');
        int index2 = Options.path.ReverseFind('/');
        if (index1 <= 0 && index2 <=0) {
            fprintf(stderr, "ERROR: invalid path\n");
            exit(1);
        }

        NPT_FileInfo info;
        NPT_CHECK_SEVERE(NPT_File::GetInfo(Options.path, &info));

        /* add file request handler */
        handler = new NPT_HttpFileRequestHandler(
            Options.path.Left(index1>index2?index1:index2), 
            "/");
        http_server.AddRequestHandler(handler, "/", true);

        /* build url*/
        url += "/" + Options.path.SubString((index1>index2?index1:index2)+1);
    } else {
        /* create random data */
        buffer = new NPT_DataBuffer(32768);
        buffer->SetDataSize(32768);

        /* add static handler */
        handler = new NPT_HttpStaticRequestHandler(buffer->GetData(),
            buffer->GetDataSize(),
            "text/xml");
        http_server.AddRequestHandler(handler, "/test");

        /* build url*/
        url += "/test";
    }

    /* add custom handler */
    NPT_InputStreamReference stream(ringbuffer_stream);
    custom_handler = new PLT_HttpCustomRequestHandler(stream,
        "text/xml");
    http_server.AddRequestHandler(custom_handler, "/custom");
    custom_url += "/custom";

    /* start server */
    NPT_CHECK_SEVERE(http_server.Start());

    /* a task manager for the tests downloader */
    PLT_TaskManager task_manager;

    /* small delay to let the server start */
    NPT_System::Sleep(NPT_TimeInterval(1, 0));
    
    /* execute tests */
    result = Test1(&task_manager, url.GetChars(), size);
    if (!result) return -1;

    result = Test2(&task_manager, url.GetChars(), size);
    if (!result) return -1;

    result = Test3(&task_manager, custom_url.GetChars(), ringbuffer_stream, size);
    if (!result) return -1;

    NPT_System::Sleep(NPT_TimeInterval(1, 0));

    http_server.Stop();
    delete handler;
    delete custom_handler;
    return 0;
}
Example #21
0
void Compilation::compile_only_this_method() {
  ResourceMark rm;
  fileStream stream(fopen("c1_compile_only", "wt"));
  stream.print_cr("# c1 compile only directives");
  compile_only_this_scope(&stream, hir()->top_scope());
}
Example #22
0
Try<Storage::State> LevelDBStorage::restore(const string& path)
{
  leveldb::Options options;
  options.create_if_missing = true;

  // TODO(benh): Can't use varint comparator until bug discussed at
  // groups.google.com/group/leveldb/browse_thread/thread/17eac39168909ba7
  // gets fixed. For now, we are using the default byte-wise
  // comparator and *assuming* that the encoding from unsigned long to
  // string produces a stable ordering. Checks below.
  // options.comparator = &comparator;

  const string& one = encode(1);
  const string& two = encode(2);
  const string& ten = encode(10);

  CHECK(leveldb::BytewiseComparator()->Compare(one, two) < 0);
  CHECK(leveldb::BytewiseComparator()->Compare(two, one) > 0);
  CHECK(leveldb::BytewiseComparator()->Compare(one, ten) < 0);
  CHECK(leveldb::BytewiseComparator()->Compare(ten, two) > 0);
  CHECK(leveldb::BytewiseComparator()->Compare(ten, ten) == 0);

  Stopwatch stopwatch;
  stopwatch.start();

  leveldb::Status status = leveldb::DB::Open(options, path, &db);

  if (!status.ok()) {
    // TODO(benh): Consider trying to repair the DB.
    return Error(status.ToString());
  }

  LOG(INFO) << "Opened db in " << stopwatch.elapsed();

  stopwatch.start(); // Restart the stopwatch.

  // TODO(benh): Conditionally compact to avoid long recovery times?
  db->CompactRange(NULL, NULL);

  LOG(INFO) << "Compacted db in " << stopwatch.elapsed();

  State state;
  state.begin = 0;
  state.end = 0;

  // TODO(benh): Consider just reading the "promise" record (e.g.,
  // 'encode(0, false)') and then iterating over the rest of the
  // records and confirming that they are all indeed of type
  // Record::Action.

  stopwatch.start(); // Restart the stopwatch.

  leveldb::Iterator* iterator = db->NewIterator(leveldb::ReadOptions());

  LOG(INFO) << "Created db iterator in " << stopwatch.elapsed();

  stopwatch.start(); // Restart the stopwatch.

  iterator->SeekToFirst();

  LOG(INFO) << "Seeked to beginning of db in " << stopwatch.elapsed();

  stopwatch.start(); // Restart the stopwatch.

  uint64_t keys = 0;

  while (iterator->Valid()) {
    keys++;
    const leveldb::Slice& slice = iterator->value();

    google::protobuf::io::ArrayInputStream stream(slice.data(), slice.size());

    Record record;

    if (!record.ParseFromZeroCopyStream(&stream)) {
      return Error("Failed to deserialize record");
    }

    switch (record.type()) {
      case Record::METADATA: {
        CHECK(record.has_metadata());
        state.metadata.CopyFrom(record.metadata());
        break;
      }

      // DEPRECATED!
      case Record::PROMISE: {
        CHECK(record.has_promise());
        // This replica is in old format. Set its status to VOTING
        // since there is no catch-up logic in the old code and this
        // replica is obviously not empty.
        state.metadata.set_status(Metadata::VOTING);
        state.metadata.set_promised(record.promise().proposal());
        break;
      }

      case Record::ACTION: {
        CHECK(record.has_action());
        const Action& action = record.action();
        if (action.has_learned() && action.learned()) {
          state.learned.insert(action.position());
          state.unlearned.erase(action.position());
          if (action.has_type() && action.type() == Action::TRUNCATE) {
            state.begin = std::max(state.begin, action.truncate().to());
          }
        } else {
          state.learned.erase(action.position());
          state.unlearned.insert(action.position());
        }
        state.end = std::max(state.end, action.position());

        // Cache the first position in this replica so during a
        // truncation, we can attempt to delete all positions from the
        // first position up to the truncate position. Note that this
        // is not the beginning position of the log, but rather the
        // first position that remains (i.e., hasn't been deleted) in
        // leveldb.
        first = min(first, action.position());
        break;
      }

      default: {
        return Error("Bad record");
      }
    }

    iterator->Next();
  }

  LOG(INFO) << "Iterated through " << keys
            << " keys in the db in " << stopwatch.elapsed();

  delete iterator;

  return state;
}
Example #23
0
void LinkedDB::save() const{
    QFile db("db.json");
    if (!db.open(QIODevice::WriteOnly)) {
        throw MyExc(database, "can't open DB!");
    }
    else{ //just for debug purpose
//QTextStream(stdout)<<"\n saving file! \n";                                          //solo per debug
    }
    if(!db.exists())
        throw MyExc(database, "DB file does not exists!");

    //start the real saving
    QTextStream stream( &db );

    //saving of all users and their relative informations
    QJsonArray json_users;
    QJsonObject users_wrapper;
    for(std::list<SmartUser>::const_iterator it = users.begin(); it!= users.end() ; ++it){

        //creating the user
        QJsonObject json_user;
        QString tmp = QString::fromUtf8((*it)->account()->username().getPassword().c_str());
        json_user["password"]= tmp;
        tmp = QString::fromUtf8((*it)->account()->username().getLogin().c_str());
        json_user["username"]= tmp;


        std::map<std::string,std::string> infos = (*it)->account()->getInfo()->getAllInfo();
        json_user["name"]    =  QString::fromUtf8(infos["name"].c_str());
        json_user["surname"] =  QString::fromUtf8(infos["surname"].c_str());
        json_user["email"]   =  QString::fromUtf8(infos["email"].c_str());
        json_user["address"] =  QString::fromUtf8(infos["address"].c_str());
        json_user["telephon"]=  QString::fromUtf8(infos["telephon"].c_str());
       
        QDate b((*it)->account()->getInfo()->getBirthday());
        json_user["birthday"]=  b.toString("yyyy.MM.dd");
        json_user["avatarPath"] = QString::fromUtf8((*it)->account()->getAvatar().c_str());
        json_user["accountType"] = (*it)->account()->getType();

        //aggiungo tutte le skills, languages and interests
        std::list<string> temp_list= (*it)->account()->getInfo()->getSkills();
        QJsonArray tmp_skills;
        for(std::list<string>::const_iterator tmp_it = temp_list.begin(); tmp_it != temp_list.end(); ++tmp_it){
            tmp_skills.push_back(QJsonValue(QString::fromUtf8((*tmp_it).c_str())));
        }
        json_user["skills"] = tmp_skills;
        temp_list = (*it)->account()->getInfo()->getLanguages();
        QJsonArray tmp_languages;
        for(std::list<string>::const_iterator tmp_it = temp_list.begin(); tmp_it != temp_list.end(); ++tmp_it){
            tmp_languages.push_back(QJsonValue(QString::fromUtf8((*tmp_it).c_str())));
        }
        json_user["languages"] = tmp_languages;
        temp_list = (*it)->account()->getInfo()->getInterests();
        QJsonArray tmp_interests;
        for(std::list<string>::const_iterator tmp_it = temp_list.begin(); tmp_it != temp_list.end(); ++tmp_it){
            tmp_interests.push_back(QJsonValue(QString::fromUtf8((*tmp_it).c_str())));
        }
        json_user["interests"] = tmp_interests;
        std::list<Experience> temp_exp=(*it)->account()->getInfo()->getExperiences();
        QJsonArray tmp_exp;
        for(std::list<Experience>::const_iterator tmp_it = temp_exp.begin(); tmp_it != temp_exp.end(); ++tmp_it){
            QJsonObject ex;
            ex["location"]=QJsonValue(QString::fromUtf8((tmp_it->getLocation()).c_str()));
            ex["role"]=QJsonValue(QString::fromUtf8(((tmp_it)->getRole()).c_str()));
            ex["from"]=QJsonValue((tmp_it)->getFrom().toString("yyyy.MM.dd"));
            ex["to"]=QJsonValue((tmp_it)->getTo().toString("yyyy.MM.dd"));
            tmp_exp.push_back(ex);
        }
        json_user["experiences"] = tmp_exp;


        //adding the friends net
        QJsonArray j_friends;
        std::list<SmartUser> friends = (*it)->getNet()->getUsers();
        for(std::list<SmartUser>::const_iterator f_it = friends.begin(); f_it != friends.end(); ++f_it){
//QTextStream(stdout)<<"saving friends of "<<tmp<<": ";
//QTextStream(stdout)<<QString::fromStdString(f_it->getLogin())<<"\n";
            j_friends.append(QString::fromStdString((*f_it)->account()->username().getLogin()));
        }
        json_user["friends"] = j_friends;
        json_users.push_back(json_user);
    }
    users_wrapper["users"]=json_users;

    //aggiungo l'admin
    QJsonObject admin;
    admin["username"] = QString("admin");
    admin["password"] = QString("password");
    users_wrapper["admin"]= admin;
    QJsonDocument doc(users_wrapper);
    QByteArray users_save = doc.toJson();
    stream << users_save;
    db.close();
}
Example #24
0
void cOverworld :: Save( void )
{
	pAudio->Play_Sound( "editor/save.ogg" );

	std::string save_dir = pResource_Manager->user_data_dir + USER_WORLD_DIR + "/" + m_description->m_path;
	// Create directory if new world
	if( !Dir_Exists( save_dir ) )
	{
		Create_Directory( save_dir );
	}

	std::string filename = save_dir + "/world.xml";

// fixme : Check if there is a more portable way f.e. with imbue()
#ifdef _WIN32
	ofstream file( utf8_to_ucs2( filename ).c_str(), ios::out | ios::trunc );
#else
	ofstream file( filename.c_str(), ios::out | ios::trunc );
#endif


	if( !file )
	{
		printf( "Error : Couldn't open world file for saving. Is the file read-only ?" );
		pHud_Debug->Set_Text( _("Couldn't save world ") + filename, speedfactor_fps * 5.0f );
		return;
	}

	CEGUI::XMLSerializer stream( file );


	// begin
	stream.openTag( "overworld" );

	// begin
	stream.openTag( "information" );
		// game version
		Write_Property( stream, "game_version", int_to_string(SMC_VERSION_MAJOR) + "." + int_to_string(SMC_VERSION_MINOR) + "." + int_to_string(SMC_VERSION_PATCH) );
		// engine version
		Write_Property( stream, "engine_version", world_engine_version );
		// time ( seconds since 1970 )
		Write_Property( stream, "save_time", static_cast<Uint64>( time( NULL ) ) );
	// end information
	stream.closeTag();

	// begin
	stream.openTag( "settings" );
		// music
		Write_Property( stream, "music", m_musicfile );
	// end settings
	stream.closeTag();

	// begin
	stream.openTag( "background" );
		// color
		Write_Property( stream, "color_red", static_cast<int>(m_background_color.red) );
		Write_Property( stream, "color_green", static_cast<int>(m_background_color.green) );
		Write_Property( stream, "color_blue", static_cast<int>(m_background_color.blue) );
	// end background
	stream.closeTag();

	// begin
	stream.openTag( "player" );
		// start waypoint
		Write_Property( stream, "waypoint", m_player_start_waypoint );
		// moving state
		Write_Property( stream, "moving_state", static_cast<int>(m_player_moving_state) );
	// end player
	stream.closeTag();

	// objects
	for( cSprite_List::iterator itr = m_sprite_manager->objects.begin(); itr != m_sprite_manager->objects.end(); ++itr )
	{
		cSprite *obj = (*itr);

		// skip spawned and destroyed objects
		if( obj->m_spawned || obj->m_auto_destroy )
		{
			continue;
		}

		// save to file stream
		obj->Save_To_XML( stream );
	}

	// end overworld
	stream.closeTag();

	file.close();

	// save layer
	m_layer->Save( save_dir + "/layer.xml" );
	// save description
	m_description->Save();

	// show info
	pHud_Debug->Set_Text( _("World ") + m_description->m_name + _(" saved") );
}
Example #25
0
GTEST_TEST(MemoryReadStream, size) {
	static const byte data[3] = { 0 };
	Common::MemoryReadStream stream(data);

	EXPECT_EQ(stream.size(), 3);
}
Example #26
0
PlaylistBrowserModel::PlaylistBrowserModel(PlaylistModel *playlistModel_,
	Playlist *temporaryPlaylist, QObject *parent) : QAbstractListModel(parent),
	playlistModel(playlistModel_), currentPlaylist(-1)
{
	playlists.append(temporaryPlaylist);

	QFile file(KStandardDirs::locateLocal("appdata", QLatin1String("playlistsK4")));

	if (!file.open(QIODevice::ReadOnly)) {
		file.setFileName(KStandardDirs::locateLocal("appdata", QLatin1String("playlists")));

		if (!file.open(QIODevice::ReadOnly)) {
			Log("PlaylistBrowserModel::PlaylistBrowserModel: cannot open file") <<
				file.fileName();
			return;
		}
	}

	QDataStream stream(&file);
	stream.setVersion(QDataStream::Qt_4_4);

	unsigned int version;
	stream >> version;
	bool hasMetadata = true;
	bool hasSubtitles = true;

	if (version == 0xc39637a1) {
		// compatibility code
		hasMetadata = false;
		hasSubtitles = false;
	} else if (version == 0x2e00f3ea) {
		// compatibility code
		hasSubtitles = false;
	} else if (version != 0x361c4a3c) {
		Log("PlaylistBrowserModel::PlaylistBrowserModel: cannot read file") <<
			file.fileName();
		return;
	}

	while (!stream.atEnd()) {
		Playlist *playlist = new Playlist();
		stream >> playlist->title;
		QString urlString;
		stream >> urlString;
		playlist->url = urlString;
		int count;
		stream >> count;

		for (int i = 0; (i < count) && !stream.atEnd(); ++i) {
			PlaylistTrack track;
			stream >> urlString;
			track.url = urlString;

			if (hasMetadata) {
				stream >> track.title;
				stream >> track.artist;
				stream >> track.album;
				stream >> track.trackNumber;
				stream >> track.length;
			} else {
				track.title = track.url.fileName();
			}

			if (hasSubtitles) {
				QStringList subtitleStrings;
				stream >> subtitleStrings;

				foreach (const QString &subtitleString, subtitleStrings) {
					track.subtitles.append(subtitleString);
				}

				stream >> track.currentSubtitle;
			}

			playlist->tracks.append(track);
		}
Example #27
0
int tool_main(int argc, char** argv) {
    SkCommandLineFlags::SetUsage("Prints information about an skp file");
    SkCommandLineFlags::Parse(argc, argv);

    if (FLAGS_input.count() != 1) {
        if (!FLAGS_quiet) {
            SkDebugf("Missing input file\n");
        }
        return kMissingInput;
    }

    SkFILEStream stream(FLAGS_input[0]);
    if (!stream.isValid()) {
        if (!FLAGS_quiet) {
            SkDebugf("Couldn't open file\n");
        }
        return kIOError;
    }

    size_t totStreamSize = stream.getLength();

    SkPictInfo info;
    if (!SkPicture::InternalOnly_StreamIsSKP(&stream, &info)) {
        return kNotAnSKP;
    }

    if (FLAGS_version && !FLAGS_quiet) {
        SkDebugf("Version: %d\n", info.fVersion);
    }
    if (FLAGS_width && !FLAGS_quiet) {
        SkDebugf("Width: %d\n", info.fWidth);
    }
    if (FLAGS_height && !FLAGS_quiet) {
        SkDebugf("Height: %d\n", info.fHeight);
    }
    if (FLAGS_flags && !FLAGS_quiet) {
        SkDebugf("Flags: 0x%x\n", info.fFlags);
    }

    if (!stream.readBool()) {
        // If we read true there's a picture playback object flattened
        // in the file; if false, there isn't a playback, so we're done
        // reading the file.
        return kSuccess;
    }

    for (;;) {
        uint32_t tag = stream.readU32();
        if (SK_PICT_EOF_TAG == tag) {
            break;
        }

        uint32_t chunkSize = stream.readU32();
        size_t curPos = stream.getPosition();

        // "move" doesn't error out when seeking beyond the end of file
        // so we need a preemptive check here.
        if (curPos+chunkSize > totStreamSize) {
            if (!FLAGS_quiet) {
                SkDebugf("truncated file\n");
            }
            return kTruncatedFile;
        }

        // Not all the tags store the chunk size (in bytes). Three
        // of them store tag-specific size information (e.g., number of
        // fonts) instead. This forces us to early exit when those
        // chunks are encountered.
        switch (tag) {
        case SK_PICT_READER_TAG:
            if (FLAGS_tags && !FLAGS_quiet) {
                SkDebugf("SK_PICT_READER_TAG %d\n", chunkSize);
            }
            break;
        case SK_PICT_FACTORY_TAG:
            if (FLAGS_tags && !FLAGS_quiet) {
                SkDebugf("SK_PICT_FACTORY_TAG %d\n", chunkSize);
            }
            // Remove this code when v21 and below are no longer supported
#ifndef DISABLE_V21_COMPATIBILITY_CODE
            if (info.fVersion < 22) {
                if (!FLAGS_quiet) {
                    SkDebugf("Exiting early due to format limitations\n");
                }
                return kSuccess;       // TODO: need to store size in bytes
            }
#endif
            break;
        case SK_PICT_TYPEFACE_TAG:
            if (FLAGS_tags && !FLAGS_quiet) {
                SkDebugf("SK_PICT_TYPEFACE_TAG %d\n", chunkSize);
                SkDebugf("Exiting early due to format limitations\n");
            }
            return kSuccess;       // TODO: need to store size in bytes
            break;
        case SK_PICT_PICTURE_TAG:
            if (FLAGS_tags && !FLAGS_quiet) {
                SkDebugf("SK_PICT_PICTURE_TAG %d\n", chunkSize);
                SkDebugf("Exiting early due to format limitations\n");
            }
            return kSuccess;       // TODO: need to store size in bytes
            break;
        case SK_PICT_BUFFER_SIZE_TAG:
            if (FLAGS_tags && !FLAGS_quiet) {
                SkDebugf("SK_PICT_BUFFER_SIZE_TAG %d\n", chunkSize);
            }
            break;
        default:
            if (!FLAGS_quiet) {
                SkDebugf("Unknown tag %d\n", chunkSize);
            }
            return kInvalidTag;
        }

        if (!stream.move(chunkSize)) {
            if (!FLAGS_quiet) {
                SkDebugf("seek error\n");
            }
            return kTruncatedFile;
        }
    }

    return kSuccess;
}
Example #28
0
void MainWindow::tableview_generations_clicked(QModelIndex index)
{
    QStandardItem *item = _modelGenerations->itemFromIndex(index);
    item->column();
    qDebug() << "clicked signal";
    qDebug() << item->text();

    QDomDocument doc;
    QString filename = _strLogDir + "/" + item->text();
    QFile file(filename);
    if (!file.open(QIODevice::ReadOnly))
    {   qDebug() << "Fail to open file...";
        return;
    }
    if (!doc.setContent(&file)) {
        qDebug() << "Fail to populize domdocument...";
        file.close();
        return;
    }
    file.close();

    // clear old model
    _modelIndividuals->clear();
    _genos.clear();

    // initialize view header
    QStringList strList;
    strList.append("Fitness");
    strList.append("Size");
    strList.append("Depth");
    //strList.append("Genotype");
    _modelIndividuals->setHorizontalHeaderLabels(strList);

    // get individuals
    QDomNodeList individuals = doc.elementsByTagName("Individual");

    // for each individual get fitness value and genotype
    for(int i = 0; i < individuals.size(); i++)
    {
        QDomElement individual = individuals.at(i).toElement();
        int indi_size = individual.attribute("size").toInt();

        QDomElement elem = individual.firstChildElement();
        QString fitness = elem.text();

        for (int j = 0; j < indi_size; j++)
        {
            elem = elem.nextSiblingElement();
            // add individual index
            QList<QStandardItem *> items;
            items.append(new QStandardItem( fitness ));
            items.append(new QStandardItem( elem.attribute("size") ));
            items.append(new QStandardItem( elem.attribute("depth") ));
            QString str;
            QTextStream stream(&str);
            stream << elem.firstChildElement();
            stream.flush();

            //items.append(new QStandardItem( str.trimmed() ));
            _genos.append(str);
            _modelIndividuals->appendRow(items);
        }

    }
    ui->tableView_Individuals->resizeColumnsToContents();
    ui->tableView_Individuals->sortByColumn(0);
}
Example #29
0
void OrcFile::write(const std::string &filename)
{
	std::ofstream stream(filename.c_str(), std::ios_base::out | std::ios_base::binary);
	write(stream);
}
Example #30
0
// ============================================================================
void DataOnDemandSvc::dump
( const MSG::Level level ,
  const bool       mode  )  const
{
  if ( m_algs.empty()  &&  m_nodes.empty() ) { return ; }

  typedef std::pair<std::string,std::string> Pair ;
  typedef std::map<std::string,Pair>         PMap ;

  PMap _m ;
  for ( AlgMap::const_iterator alg = m_algs.begin() ;
        m_algs.end() != alg ; ++alg )
  {
    PMap::const_iterator check = _m.find(alg->first) ;
    if ( _m.end() != check )
    {
      stream()
        << MSG::WARNING
        << " The data item is activated for '"
        << check->first << "' as '" << check->second.first << "'" << endmsg ;
    }
    const Leaf& l = alg->second ;
    std::string nam = ( l.name == l.type ? l.type  : (l.type+"/"+l.name) ) ;
    //
    if ( !mode && 0 == l.num ) { continue ; }
    //
    std::string val ;
    if ( mode ) { val = ( 0 == l.algorithm ) ? "F" : "T" ; }
    else { val = boost::lexical_cast<std::string>( l.num ) ; }
    //
    _m[ no_prefix ( alg->first , m_prefix ) ] = std::make_pair ( nam , val ) ;
  }
  // nodes:
  for ( NodeMap::const_iterator node = m_nodes.begin() ;
        m_nodes.end() != node ; ++node )
  {
    PMap::const_iterator check = _m.find(node->first) ;
    if ( _m.end() != check )
    {
      stream()
        << MSG::WARNING
        << " The data item is already activated for '"
        << check->first << "' as '" << check->second.first << "'" << endmsg ;
    }
    const Node& n = node->second ;
    std::string nam = "'" + n.name + "'"  ;
    //
    std::string val ;

    if ( !mode && 0 == n.num ) { continue ; }

    if ( mode ) { val = ( 0 == n.clazz ) ? "F" : "T" ; }
    else { val = boost::lexical_cast<std::string>( n.num ) ; }
    //
    _m[ no_prefix ( node->first , m_prefix ) ] = std::make_pair ( nam , val ) ;
  }
  //
  if ( _m.empty() ) { return ; }

  // find the correct formats
  size_t n1 = 0 ;
  size_t n2 = 0 ;
  size_t n3 = 0 ;
  for  ( PMap::const_iterator it = _m.begin() ; _m.end() != it ; ++it )
  {
    n1 = std::max ( n1 , it->first.size()         ) ;
    n2 = std::max ( n2 , it->second.first.size()  ) ;
    n3 = std::max ( n3 , it->second.second.size() ) ;
  }
  if ( 10 > n1 ) { n1 = 10 ; }
  if ( 10 > n2 ) { n2 = 10 ; }
  if ( 60 < n1 ) { n1 = 60 ; }
  if ( 60 < n2 ) { n2 = 60 ; }
  //

  const std::string _f = " | %%1$-%1%.%1%s | %%2$-%2%.%2%s | %%3$%3%.%3%s |" ;
  boost::format _ff ( _f ) ;
  _ff % n1 % n2 % n3 ;

  const std::string _format  = _ff.str() ;

  MsgStream& msg = stream() << level ;

  if ( mode ) { msg << "Data-On-Demand Actions enabled for:"       ; }
  else        { msg << "Data-On-Demand Actions has been used for:" ; }

  boost::format fmt1( _format)  ;
  fmt1 % "Address" % "Creator" % ( mode ? "S" : "#" ) ;
  //
  const std::string header = fmt1.str() ;
  std::string line = std::string( header.size() , '-' ) ;
  line[0] = ' ' ;

  msg << std::endl << line
      << std::endl << header
      << std::endl << line ;

  // make the actual printout:
  for ( PMap::const_iterator item = _m.begin() ;
        _m.end() != item ; ++item )
  {
    boost::format fmt( _format)  ;
    msg << std::endl <<
      ( fmt % item->first % item->second.first % item->second.second ) ;
  }

  msg << std::endl << line << endmsg ;

}