这篇教程C++ stream函数代码示例写得很实用,希望能帮到您。
本文整理汇总了C++中stream函数的典型用法代码示例。如果您正苦于以下问题:C++ stream函数的具体用法?C++ stream怎么用?C++ stream使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。 在下文中一共展示了stream函数的26个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的C++代码示例。 示例1: streamvoid LocalHTTPServer::respondToClient(QTcpSocket * socket){ QTextStream stream(socket); stream << "HTTP/1.0 200 Ok/r/n"; socket->close();}
开发者ID:Globidev,项目名称:ClipboardOne,代码行数:6,
示例2: GTEST_TESTGTEST_TEST(MemoryReadStream, getData) { static const byte data[3] = { 0 }; Common::MemoryReadStream stream(data); EXPECT_EQ(stream.getData(), data);}
开发者ID:Supermanu,项目名称:xoreos,代码行数:6,
示例3: streamOrcFile::OrcFile(const std::string &filename){ std::ifstream stream(filename.c_str(), std::ios_base::in | std::ios_base::binary); read(stream);}
开发者ID:mattfischer,项目名称:compiler,代码行数:5,
示例4: fileCC_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);//.........这里部分代码省略.........
开发者ID:3660628,项目名称:trunk,代码行数:101,
示例5: QStringListQMenu* 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;}
开发者ID:Absolight,项目名称:mirall,代码行数:93,
示例6: filevoid 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();}
开发者ID:georgemoralis,项目名称:pspudb,代码行数:67,
示例7: copy//.........这里部分代码省略......... 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}
开发者ID:chenzhongde,项目名称:BHumanCodeRelease,代码行数:101,
示例8: fvoid 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);}
开发者ID:husninazer,项目名称:qt,代码行数:63,
示例9: switchQString 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);//.........这里部分代码省略.........
开发者ID:wpbest,项目名称:copperspice,代码行数:101,
示例10: streambool 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;}
开发者ID:qtproject,项目名称:qt-creator,代码行数:84,
示例11: xvoid 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; }
开发者ID:qdnguyen,项目名称:PotreeConvertor4Itowns,代码行数:71,
示例12: GetLastResultvoidGDBGetStack::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);}
开发者ID:raorn,项目名称:jx_application_framework,代码行数:82,
示例13: streambool 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"; }//.........这里部分代码省略.........
开发者ID:Opioid,项目名称:Substitute,代码行数:101,
示例14: fi_configshort 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;//.........这里部分代码省略.........
开发者ID:kthxbyte,项目名称:KDE1-Linaro,代码行数:101,
示例15: SkMin32bool 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);}
开发者ID:0omega,项目名称:platform_external_skia,代码行数:6,
示例16: qWarningbool 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;}
开发者ID:lit-uriy,项目名称:QAdvancedItemViews,代码行数:76,
示例17: Q_CHECK_PTRvoid 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;}
开发者ID:CGenie,项目名称:kmymoney,代码行数:93,
示例18: main/*----------------------------------------------------------------------| main+---------------------------------------------------------------------*/intmain(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;}
开发者ID:Castlecard,项目名称:plex,代码行数:90,
示例19: streamvoid 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());}
开发者ID:pombreda,项目名称:graal,代码行数:6,
示例20: encodeTry<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()) {//.........这里部分代码省略.........
开发者ID:TheTao,项目名称:mesos,代码行数:101,
示例21: dbvoid 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();}
开发者ID:albertodeago,项目名称:Pao-LinkedIn,代码行数:94,
示例22: Savevoid 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") );}
开发者ID:120pulsations,项目名称:SMC,代码行数:98,
示例23: QAbstractListModelPlaylistBrowserModel::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); }
开发者ID:Brandhand,项目名称:kaffeine-vlc,代码行数:76,
示例24: tool_mainint 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"); }//.........这里部分代码省略.........
开发者ID:venkatarajasekhar,项目名称:Qt,代码行数:101,
示例25: qDebugvoid 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);}
开发者ID:idaohang,项目名称:GPSeg,代码行数:67,
示例26: stream// ============================================================================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() ;//.........这里部分代码省略.........
开发者ID:atlas-org,项目名称:gaudi,代码行数:101,
注:本文中的stream函数示例整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。 C++ stream_Delete函数代码示例 C++ strdupa函数代码示例 |