Example #1
0
unsigned int MDCSurface_read(Surface& surface, const byte* buffer)
{
  mdcSurface_t mdcSurface;
  {
    PointerInputStream inputStream(buffer);
    istream_read_mdcSurface(inputStream, mdcSurface);
  }

  {
    surface.vertices().reserve(mdcSurface.numVerts);

    PointerInputStream xyzStream(buffer + mdcSurface.ofsXyzNormals);
    PointerInputStream stStream(buffer + mdcSurface.ofsSt);
    // read verts into vertex array - xyz, st, normal
    for(std::size_t i = 0; i < mdcSurface.numVerts; i++)
	  {
      mdcXyzNormal_t mdcXyzNormal;
      istream_read_mdcXyzNormal(xyzStream, mdcXyzNormal);
      mdcSt_t mdcSt;
      istream_read_mdcSt(stStream, mdcSt);

      surface.vertices().push_back(
        ArbitraryMeshVertex(
          Vertex3f( mdcXyzNormal.xyz[0] * MDC_XYZ_SCALE, mdcXyzNormal.xyz[1] * MDC_XYZ_SCALE, mdcXyzNormal.xyz[2] * MDC_XYZ_SCALE),
          DecodeNormal(reinterpret_cast<byte*>(&mdcXyzNormal.normal)),
          TexCoord2f(mdcSt.st[0], mdcSt.st[1])
        )
      );
    }
  }

  {
 	  surface.indices().reserve(mdcSurface.numTriangles * 3);

    PointerInputStream triangleStream(buffer + mdcSurface.ofsTriangles);

    for(std::size_t i = 0; i < mdcSurface.numTriangles; i++)
    {
      mdcTriangle_t triangle;
      istream_read_mdcTriangle(triangleStream, triangle);
      surface.indices().insert(triangle.indexes[0]);
      surface.indices().insert(triangle.indexes[1]);
      surface.indices().insert(triangle.indexes[2]);
    }
  }

  {
    mdcShader_t shader;
    PointerInputStream inputStream(buffer + mdcSurface.ofsShaders);
    istream_read_mdcShader(inputStream, shader);
    surface.setShader(shader.name);
  }
	
	surface.updateAABB();

  return mdcSurface.ofsEnd;
}
Example #2
0
void PGMBildRepo::bild_lesen(PGMBild *bild, string ifs_file_name) {

    ifstream inputStream(ifs_file_name);

    if (!inputStream) {

        cout << "Datei" << ifs_file_name << " konnte nicht eingelesen werden";
        inputStream.close();
        return;
    }

    this->parse_bild_informationen(inputStream,bild);

    if(!this->istPGMBild(bild)) {

        cout << "Es handelt sich nicht um ein PGMBild";
        inputStream.close();
        return;
    }

    for (int row = 0; row < bild->ny; row++) {

        for (int column = 0; column < bild->nx; column++) {

            double pixelWert = 0;

            inputStream >> pixelWert;

            bild->bild[row][column] = (int)pixelWert;
        }
    }

    inputStream.close();
}
Example #3
0
static void serialize_and_compare_typeface(sk_sp<SkTypeface> typeface, const char* text,
                                           skiatest::Reporter* reporter)
{
    // Create a paint with the typeface.
    SkPaint paint;
    paint.setColor(SK_ColorGRAY);
    paint.setTextSize(SkIntToScalar(30));
    paint.setTypeface(std::move(typeface));

    // Paint some text.
    SkPictureRecorder recorder;
    SkIRect canvasRect = SkIRect::MakeWH(kBitmapSize, kBitmapSize);
    SkCanvas* canvas = recorder.beginRecording(SkIntToScalar(canvasRect.width()),
                                               SkIntToScalar(canvasRect.height()),
                                               nullptr, 0);
    canvas->drawColor(SK_ColorWHITE);
    canvas->drawText(text, 2, 24, 32, paint);
    sk_sp<SkPicture> picture(recorder.finishRecordingAsPicture());

    // Serlialize picture and create its clone from stream.
    SkDynamicMemoryWStream stream;
    picture->serialize(&stream);
    std::unique_ptr<SkStream> inputStream(stream.detachAsStream());
    sk_sp<SkPicture> loadedPicture(SkPicture::MakeFromStream(inputStream.get()));

    // Draw both original and clone picture and compare bitmaps -- they should be identical.
    SkBitmap origBitmap = draw_picture(*picture);
    SkBitmap destBitmap = draw_picture(*loadedPicture);
    compare_bitmaps(reporter, origBitmap, destBitmap);
}
        void TextureResourceLoader::loadFileIntoBuffer(Core::File const& file, std::vector<unsigned char>& buffer, Endianness fileEndianness)
        {
            if(isFileValid(file))
            {
                if(!buffer.empty())
                {
                    OcularLogger->warning("Provided buffer is not empty; Emptying it", OCULAR_INTERNAL_LOG("TextureResourceLoader", "loadBuffer"));
                    buffer.clear();
                }

                std::ifstream inputStream(file.getFullPath(), std::ios_base::binary);

                if(inputStream.is_open())
                {
                    buffer = std::vector<unsigned char>(std::istreambuf_iterator<char>(inputStream), std::istreambuf_iterator<char>());
                    inputStream.close();

                    // Ensure all the retrieved data is in the proper endianness

                    for(unsigned i = 0; i < buffer.size(); i++)
                    {
                        Utils::EndianOps::convert(fileEndianness, Endianness::Native, buffer[i]);
                    }
                }
                else
                {
                    OcularEngine.Logger()->error("Failed to open file for reading '", file.getFullPath(), "'", OCULAR_INTERNAL_LOG("TextureResourceLoader", "loadBuffer"));
                }
            }
            else 
            {
                OcularEngine.Logger()->error("Resource '", file.getFullPath(), "' is not a valid file", OCULAR_INTERNAL_LOG("TextureResourceLoader_BMP", "readFile"));
            }
        }
void ConfigurationVector::openFromFile(QString _filePath)
{

    QString inputStr;
    QString currentLine;

    QFile inputFile(_filePath);

    inputFile.open(QFile::ReadOnly | QFile::Text);

    QTextStream inputStream(&inputFile);

    inputStr = "";   

    while(!inputStream.atEnd())
    {
        currentLine = inputStream.readLine();
        inputStr.append(currentLine);
    }

    this->reset();
    this->readInput(inputStr);

    inputFile.close();

}
void PersistableGNATCollectionImpl<T>::load(std::string fileName) {
	//Open file in binary write mode
	std::ifstream inputStream(fileName, std::ifstream::in | std::ifstream::binary);

	if(inputStream.is_open()) {
		//Self-emptize
		GNATCollectionImpl<T>::purge();

		std::vector<GNATCollectionReadBlock<T>* > blocks;

		//Read blocks from input stream
		readCollectionBlocks(blocks, m_pReader, inputStream);

		//Close input stream soon after reading blocks
		inputStream.close();

		loadGNATCollection(1, blocks);

		//Release read blocks
		releasePointerVector(blocks);
	}
	else {
		throw std::runtime_error("Can't open file to load collection");
	}

	//Closing file output stream is not really necessary as it is called by destructor automatically
}
Example #7
0
Image* LoadM32Buff(byte* buffer)
{
  PointerInputStream inputStream(buffer);

  inputStream.seek(4 // version
    + M32_NAME_LENGTH // name
    + M32_NAME_LENGTH // altname
    + M32_NAME_LENGTH // animname
    + M32_NAME_LENGTH); // damagename
  int w = istream_read_uint32_le(inputStream);
  inputStream.seek(4 * (M32_MIPMAP_COUNT - 1)); // remaining widths
  int h = istream_read_uint32_le(inputStream);
  inputStream.seek(4 * (M32_MIPMAP_COUNT - 1)); // remaining heights
  int offset = istream_read_uint32_le(inputStream);
  inputStream.seek(4 * (M32_MIPMAP_COUNT - 1)); // remaining offsets
  int flags = istream_read_uint32_le(inputStream);
  int contents = istream_read_uint32_le(inputStream);
  int value = istream_read_uint32_le(inputStream);

  RGBAImageFlags* image = new RGBAImageFlags(w, h, flags, contents, value);

  const byte* source = buffer + offset;
  std::copy(source, source + (w * h * 4), image->getRGBAPixels());

  return image;
}
Example #8
0
        /**
         *  Finds a particular fasta header in a fasta file and returns the associated sequence
         **/
        static int getEntryFromFasta(const path& fasta_path, const string& header, string& sequence)
        {
            // Setup stream to sequence file and check all is well
            std::ifstream inputStream (fasta_path.c_str());

            if (!inputStream.is_open())
            {
                std::cerr << "ERROR: Could not open the sequence file: " << fasta_path << endl;
                return 0;
            }

            string id;
            string seq;

            // Read a record
            while(inputStream.good() && readRecord(inputStream, id, seq) == 0)
            {
                stringstream ssHeader;
                ssHeader << id;

                if (header.compare(ssHeader.str()) == 0)
                {
                    inputStream.close();
                    sequence = seq;

                    return 0;
                }
                seq.clear();
            }

            inputStream.close();
            return -1;
        }
Example #9
0
        /**
         *  Finds the nth entry from the fasta file and returns the associated sequence
         **/
        static int getEntryFromFasta(const path& fasta_path, uint32_t n, string& header, string& sequence)
        {
            // Setup stream to sequence file and check all is well
            std::ifstream inputStream (fasta_path.c_str());

            if (!inputStream.is_open())
            {
                std::cerr << "ERROR: Could not open the sequence file: " << fasta_path << endl;
                return 0;
            }


            std::string id;
            std::string seq;
            uint32_t i = 1;

            // Read a record
            while(inputStream.good() && readRecord(inputStream, id, seq) == 0)
            {
                if (i == n)
                {
                    inputStream.close();

                    header.swap(id);
                    sequence = seq;
                    return 0;
                }

                seq.clear();
                i++;
            }

            inputStream.close();
            return -1;
        }
  void CandidateMapReader::Read(const boost::filesystem::path& mapPath){
      
    std::ifstream inputStream(mapPath.string(), std::ios::binary);
    cereal::BinaryInputArchive inputArchive(inputStream);
    inputArchive(candidatesMap);

  }
Example #11
0
void Config::resurrect()
{
  std::stringstream ss;
  if (path.empty())
    ss << name << ".cfg";
  else
    ss << path << "/" << name << ".cfg";
  std::string input(ss.str());
  std::ifstream inputStream(input.c_str());
  if (inputStream.is_open())
  {
    std::string str;
    while (getline(inputStream, str))
    {
      if (str.length())
      {
        unsigned int npos = str.find_first_of("#");
        if ((npos == std::string::npos) && (npos > str.size()))
        { // str is not a comment
          std::vector<std::string> tokens;
          configSplit(str, '=', tokens);
          assert(tokens.size() == 2); // Only name=value pairs
          values.insert(std::make_pair(tokens[0], tokens[1]));
        }
      }
    }
    inputStream.close();
    std::cout << "INFO! config=" << input << " resurrected!" << std::endl;
  }
  else
  {
    std::cout << "INFO! config=" << input << " empty!" << std::endl;
  }
}
Example #12
0
void Instance::LoadModList()
{
	if (GetModListFile().FileExists())
	{
		wxFileInputStream inputStream(GetModListFile().GetFullPath());
		wxStringList modListFile = ReadAllLines(inputStream);
		
		for (wxStringList::iterator iter = modListFile.begin(); iter != modListFile.end(); iter++)
		{
			// Normalize the path to the instMods dir.
			wxFileName modFile(*iter);
			modFile.Normalize(wxPATH_NORM_ALL, GetInstModsDir().GetFullPath());
			modFile.MakeRelativeTo();
			
			if (!Any(modList.begin(), modList.end(), [&modFile] (Mod mod) -> bool
				{ return mod.GetFileName().SameAs(wxFileName(modFile)); }))
			{
				//SetNeedsRebuild();
				modList.push_back(Mod(modFile));
			}
		}
	}
	
	for (size_t i = 0; i < modList.size(); i++)
	{
		if (!modList[i].GetFileName().FileExists())
		{
			SetNeedsRebuild();
			modList.erase(modList.begin() + i);
			i--;
		}
	}
	
	LoadModListFromDir(GetInstModsDir());
}
Example #13
0
void FileServer::readResFileFinfo()
{
    std::string filecfg = _writePath + "/fileinfo_debug.json";
    FILE * pFile = fopen (filecfg.c_str() , "r");
    if(pFile)
    {
        rapidjson::FileStream inputStream(pFile);
        _filecfgjson.ParseStream<0>(inputStream);
        fclose(pFile);
    }
    if(! _filecfgjson.IsObject()){
        _filecfgjson.SetObject();
    }
    
    //save file info to disk every five second
    Director::getInstance()->getScheduler()->schedule([&](float){
        rapidjson::StringBuffer buffer;
        rapidjson::Writer< rapidjson::StringBuffer > writer(buffer);
        _filecfgjson.Accept(writer);
        const char* str = buffer.GetString();
        std::string filecfg = _writePath + "/fileinfo_debug.json";
        FILE * pFile = fopen(filecfg.c_str(), "w");
        if (!pFile) return ;
        fwrite(str, sizeof(char), strlen(str), pFile);
        fclose(pFile);
    },this, 5.0f, false, "fileinfo");
}
Example #14
0
Configuration* ConfigurationLoader::loadFromFile(char *path) {
    FILE* filePointer = fopen(path, "r");

    if(filePointer == NULL) {
        LOG(ERROR) << "Cant't open main configuration file " << path << ". Using defaults.";
        return new Configuration();
    }

    char buffer[65536];
    rapidjson::FileReadStream inputStream(filePointer, buffer, sizeof(buffer));

    rapidjson::Document document;
    document.ParseStream(inputStream);

    fclose(filePointer);

    Configuration* config = new Configuration();
    for(rapidjson::Value::ConstMemberIterator itr = document.MemberBegin(); itr != document.MemberEnd(); ++itr) {
        if(strcmp(itr->name.GetString(), "server.port") == 0) {
            config->serverPort = itr->value.GetInt();
        } else if(strcmp(itr->name.GetString(), "data.path") == 0) {
            config->dataPath = itr->value.GetString();
        } else if(strcmp(itr->name.GetString(), "deviceTypes.path") == 0) {
            config->deviceTypesPath = itr->value.GetString();
        } else if(strcmp(itr->name.GetString(), "devices.path") == 0) {
            config->devicesPath = itr->value.GetString();
        } else if(strcmp(itr->name.GetString(), "interfaces.path") == 0) {
            config->interfacesPath = itr->value.GetString();
        } else if(strcmp(itr->name.GetString(), "scenes.path") == 0) {
            config->scenesPath = itr->value.GetString();
        }
    }

    return config;
}
Example #15
0
void Oven::cook(QString inputContents, QString scriptContents) {
  QTemporaryFile file;
  QProcess process;
  
  if (file.open()) {
    QString filename = file.fileName();
    
    file.write(scriptContents.toUtf8());
    if (!file.error()) {
      file.close();
      
      process.setProcessChannelMode(QProcess::ForwardedChannels);
      process.start("bash", QStringList() << filename);
      
      QTextStream inputStream(&process);
      inputStream << inputContents;
      inputStream.flush();
      process.closeWriteChannel();
      
      if (process.waitForStarted() && process.waitForFinished()) {
        // success!
        return;
      }
    }
  }
  
  if (file.error() != QTemporaryFile::NoError) {
    emit error(file.errorString());
  } else {
    emit error(process.errorString());
  }
  
  // error.
  return;
}
Example #16
0
DragWidget::DragWidget(QWidget *parent)
    : QWidget(parent)
{
    QFile dictionaryFile(":/dictionary/words.txt");
    dictionaryFile.open(QIODevice::ReadOnly);
    QTextStream inputStream(&dictionaryFile);

    int x = 5;
    int y = 5;

    while (!inputStream.atEnd()) {
        QString word;
        inputStream >> word;
        if (!word.isEmpty()) {
            DragLabel *wordLabel = new DragLabel(word, this);
            wordLabel->move(x, y);
            wordLabel->show();
            wordLabel->setAttribute(Qt::WA_DeleteOnClose);
            x += wordLabel->width() + 2;
            if (x >= 195) {
                x = 5;
                y += wordLabel->height() + 2;
            }
        }
    }

    QPalette newPalette = palette();
    newPalette.setColor(QPalette::Window, Qt::white);
    setPalette(newPalette);

    setAcceptDrops(true);
    setMinimumSize(400, qMax(200, y));
    setWindowTitle(tr("Draggable Text"));
}
Example #17
0
void MultyBuffer::DoWork(const int i)
{
	const std::string num_part = boost::str(boost::format("%03u.txt") % i);
	const std::string inputFile = BINARY_DIR + std::string("/input_") + num_part;
	std::ifstream inputStream(inputFile , std::ios::binary);

	Statistic statistic;
	Sizes sizes;

	if(!inputStream.good())
	{
		std::cout << "Incorrect file path: " << inputFile << std::endl;
		return;
	}

	const std::string outputFile = BINARY_DIR + std::string("/output_") + num_part;
	std::ofstream outputStream(outputFile, std::ios::out | std::ios::binary);

	const boost::uint32_t treshold = 2048;
	boost::uint32_t currentTime = -1;
	int currentSize = 0;
	
	while (true)
	{
		binary_reader::market_message message(inputStream);

		if(inputStream.eof())
			break;

		const boost::uint32_t type = message.type();
		if (sizes.find(type) == sizes.end())
			sizes[type] = 0;

		const boost::uint32_t messageSize = GetMessageSize(message);

		if (message.time() == currentTime && ((sizes[type] + messageSize) <= treshold))
		{
			sizes[type] += messageSize;

			const bool incr_sec = std::find(curentTypes.begin(), curentTypes.end(), type) == curentTypes.end();
			StatisticUp(type, incr_sec, statistic);

		}
		else if ((sizes[type] + messageSize) <= treshold)
		{
			curentTypes.clear();
			currentTime = message.time();
			sizes[type] = messageSize;
			StatisticUp(type, true, statistic);
		}
		else
			continue;

		curentTypes.push_back(type);
	}

	inputStream.close();
	ShowStatictics(statistic, outputStream);
	outputStream.close();
}
Example #18
0
const shared_ptr<std::string> ZLStreamImage::stringData() const {
	shared_ptr<ZLInputStream> stream = inputStream();
	AppLog("проверка удалось ли что-то открыть?");
	if (stream.isNull() || !stream->open()) {
		AppLog("нифига");
		return 0;
	}
	AppLog("о что-то есть");
	if (mySize == 0) {
		mySize = stream->sizeOfOpened();
		if (mySize == 0) {
			AppLog("а размер-то нулевой");
			return 0;
		}
		AppLog("mySize = %d",mySize);
	}

	shared_ptr<std::string> imageData = new std::string();

	stream->seek(myOffset, false);
	char *buffer = new char[mySize];
	stream->read(buffer, mySize);
	imageData->append(buffer, mySize);
	delete[] buffer;

	return imageData;
}
Example #19
0
std::shared_ptr<SlidePart> SlidePartBuilder::buildSlideFromTemplate(std::string templatePath) {
  std::ifstream inputStream(templatePath, std::ios_base::in);
  std::stringstream buffer;
  buffer << inputStream.rdbuf();
  inputStream.close();
  return std::make_shared<SlidePart>(buffer.str());
}
Example #20
0
bool Language::gunzip(wxString file_target, wxString file_source)
{
	#ifdef DEBUG
		wxPuts("Start GUNZIP");
	#endif
	
	char buffer[1024];
	wxTempFile target(file_target);
	bool write = false;
	wxFileInputStream source(file_source);
	wxZlibInputStream inputStream(source);

	while (!inputStream.Eof()) {
			inputStream.Read(buffer, sizeof(buffer));
			if (inputStream.LastRead()) {
					target.Write(buffer, inputStream.LastRead());
			} else {
					break;
			}
	};
	write = inputStream.IsOk() || inputStream.Eof();

	if (write) {
			target.Commit();
	}
	#ifdef DEBUG
		wxPuts("Done GUNZIP");
	#endif
	
	return 1;
}
Example #21
0
// çalýþýyor
bool DataProcess::LoadRawData(char * filename)
{

  string line;
  char *pos;
  nItem=GetnItem(filename);
  ifstream inputStream(filename);
  if( !inputStream ) {
    cerr << "Error opening input stream" << endl;
    return false;
  }
  for(int i=0;i<nItem;i++)
    items.push_back(new DataItem());

  int i=1;
  while (getline(inputStream,line)){
    if( ReadLine(line)==-1){
       cout << "Error Line : " << i;
       break;
//       return false;
    }
    else
      cout << "Line : " << i << " Processed\n";
    i++;
  };
  nData=i-1;
  inputStream.close();
  return true;

}
void Lesson3::DoWork()
{
	std::ifstream inputStream(BINARY_DIR "/input.txt", std::ios::binary);
	if (!inputStream.good())
	{
		std::cout << "Incorrect file path: " << BINARY_DIR "/input.txt" << std::endl;
		return;
	}

	while (true)
	{
		binary_reader::stock_data stock_data(inputStream);

		if(inputStream.eof())
			break;

		const std::string file_name = BINARY_DIR + std::string("/output_") + std::string(stock_data.stock_name()) + std::string(".txt");
		const char* stock_name = stock_data.stock_name();

		if(stock_collection1.find(stock_name) == stock_collection1.end())
			stock_collection1[stock_name] = boost::make_shared<std::ofstream>(file_name, std::ios::out | std::ios::binary);

		stock_data.write(*stock_collection1[stock_name]);
	}
	inputStream.close();

	Close(stock_collection1);
}
Example #23
0
bool KEduVocCsvReader::readDoc( KEduVocDocument *doc )
{
    m_doc = doc;

    QString separator = m_doc->csvDelimiter();

    QTextStream inputStream( m_inputFile );
    inputStream.setCodec( "UTF-8" );
    inputStream.setAutoDetectUnicode( true );
    inputStream.seek( 0 );

    int languageCount = 0;

    KEduVocLesson* lesson = new KEduVocLesson( i18n("Vocabulary"), m_doc->lesson());
    m_doc->lesson()->appendChildContainer(lesson);

    while ( !inputStream.atEnd() ) {
        QString s = inputStream.readLine();

        if ( !s.simplified().isEmpty() ) {
            KEduVocExpression* expression = new KEduVocExpression( s.split(separator) );
            languageCount = qMax( languageCount,
                expression->translationIndices().count() );
            lesson->appendEntry( expression );
        }
    }

    for ( int j = 0; j < languageCount; j++ )
    {
        m_doc->appendIdentifier();
    }

    return true;
}
Example #24
0
bool Main::Config::ExecuteConfigCommands(Ui::Command & handler)
{
    static char const * const vimpcrcFile = "/.vimpcrc";
    static char const * const home        = "HOME";
    static bool configCommandsExecuted    = false;

    pcrecpp::RE const commentCheck("^\\s*\".*");

    if (configCommandsExecuted == false)
    {
        configCommandsExecuted = true;

        std::string configFile(getenv(home));
        configFile.append(vimpcrcFile);

        std::string   input;
        std::ifstream inputStream(configFile.c_str());

        if (inputStream)
        {
            while (!inputStream.eof())
            {
                std::getline(inputStream, input);

                if ((input != "") && (commentCheck.FullMatch(input.c_str()) == false))
                {
                    handler.ExecuteCommand(input);
                }
            }
        }
    }

    return true;
}
Example #25
0
//显示源文件中指定的行
void DisplaySourceLines(LPCTSTR sourceFile, int lineNum, unsigned int address, int after, int before) {

	std::wcout << std::endl;

	std::wifstream inputStream(sourceFile);

	if (inputStream.fail() == true) {

		std::wcout << TEXT("Open source file failed.") << std::endl 
				   << TEXT("Path: ") << sourceFile << std::endl;
		return;
	}

	inputStream.imbue(std::locale("chs", std::locale::ctype));

	int curLineNumber = 1;

	//计算从第几行开始输出
	int startLineNumber = lineNum - before;
	if (startLineNumber < 1) {
		startLineNumber = 1;
	}

	std::wstring line;

	//跳过不需要显示的行
	while (curLineNumber < startLineNumber) {

		std::getline(inputStream, line);
		++curLineNumber;
	}

	//输出开始行到当前行之间的行
	while (curLineNumber < lineNum) {

		std::getline(inputStream, line);
		DisplayLine(sourceFile, line, curLineNumber, FALSE);
		++curLineNumber;
	}

	//输出当前行
	getline(inputStream, line);
	DisplayLine(sourceFile, line, curLineNumber, TRUE);
	++curLineNumber;

	//输出当前行到最后行之间的行
	int lastLineNumber = lineNum + after;
	while (curLineNumber <= lastLineNumber) {

		if (!getline(inputStream, line)) {
			break;
		}

		DisplayLine(sourceFile, line, curLineNumber, FALSE);
		++curLineNumber;
	}

	inputStream.close();
}
void BlankenhainAudioProcessor::setStateInformation(const void* data, int sizeInBytes)
{
	// You should use this method to restore your parameters from this memory block,
	// whose contents will have been created by the getStateInformation() call.
	MemoryInputStream inputStream(data, sizeInBytes, false);
	var state = JSON::parse(inputStream);
	setState(state);
}
Example #27
0
	void Thread::run(int socket,RequestHandler * handler){
		InputStream inputStream(socket);
		OutputStream outputStream(socket);

		handler->onRequestArrived(inputStream,outputStream);
		::close(socket);
		delete this;
	}
TEST(SkipChars, SkipsCharacters)
{
    std::istringstream inputStream("This is a nice day.");
    cryptopals::skip_chars_streambuf charSkipper(inputStream, 2, 5);
    std::string result;
    std::getline(std::istream(&charSkipper), result);
    EXPECT_EQ("i cy", result);
}
Example #29
0
bool LogsDialog::cvsFileParse()
{
  QFile file(ui->FileName_LE->text());
  int errors=0;
  int lines=-1;

  if (!file.open(QIODevice::ReadOnly | QIODevice::Text)) { // reading HEX TEXT file
    return false;
  }
  else {
    csvlog.clear();
    logFilename.clear();
    QTextStream inputStream(&file);
    QString buffer = file.readLine();

    if (buffer.startsWith("Date,Time")) {
      file.reset();
    }
    else {
      return false;
    }

    int numfields=-1;
    while (!file.atEnd()) {
      QString line = file.readLine().trimmed();
      QStringList columns = line.split(',');
      if (numfields==-1) {
        numfields=columns.count();
      }
      if (columns.count()==numfields) {
        csvlog.append(columns);
      }
      else {
        errors++;
      }
      lines++;
    }

    logFilename = QFileInfo(file.fileName()).baseName();
  }

  file.close();
  if (errors > 1) {
    QMessageBox::warning(this, "Companion", tr("The selected logfile contains %1 invalid lines out of  %2 total lines").arg(errors).arg(lines));
  }

  int n = csvlog.count();
  if (n == 1) {
    csvlog.clear();
    return false;
  }

  plotLock = true;
  setFlightSessions();
  plotLock = false;

  return true;
}
Example #30
0
CubicSpline::CubicSpline(std::string filePath)
{
	std::ifstream inputStream(filePath, std::ios::in);
	std::string inputArguments;
	std::string inputResults;
	getline(inputStream, inputArguments);
	getline(inputStream, inputResults);
	inputStream.close();
	for (unsigned int argumentIterator = 0, splineIterator = 0; argumentIterator < inputArguments.length();)
	{
		if (argumentIterator == inputArguments.length() - 1)
		{
			splines_.push_back(emptySpline());
			splines_[splineIterator].argumentValue = stringToNumber(inputArguments);
			splineIterator++;
		}	
		if (inputArguments[argumentIterator] == ' ')
		{
			splines_.push_back(emptySpline());
			splines_[splineIterator].argumentValue = stringToNumber(inputArguments.substr(0, argumentIterator));
			splineIterator++;
			inputArguments = inputArguments.substr(argumentIterator + 1);
			argumentIterator = 0;
		}
		else
			argumentIterator++;
	}
	for (unsigned int resultIterator = 0, splineIterator = 0; resultIterator < inputResults.length();)
	{
		if (resultIterator == inputResults.length() - 1)
		{
			splines_[splineIterator].freeMember = stringToNumber(inputResults);
			splineIterator++;
		}
			
		if (inputResults[resultIterator] == ' ')
		{
			splines_[splineIterator].freeMember = stringToNumber(inputResults.substr(0, resultIterator));
			splineIterator++;
			inputResults = inputResults.substr(resultIterator + 1);
			resultIterator = 0;
		}
		else
			resultIterator++;
	}
	splines_[0].secondFactor = 0;

	tridiagonalMatrixAlgorithm();

	for (unsigned int iterator = splines_.size() - 1; iterator > 0; iterator--)
	{
		splines_[iterator].thirdFactor = (splines_[iterator].secondFactor - splines_[iterator - 1].secondFactor) / argumentDifference(iterator);

		splines_[iterator].firstFactor = argumentDifference(iterator) * (2 * splines_[iterator].secondFactor + splines_[iterator - 1].secondFactor) / 6 + 
										(splines_[iterator].freeMember - splines_[iterator - 1].freeMember) / argumentDifference(iterator);
	}

}