示例#1
0
int main(){

#ifdef DEBUG 
    UnitTests();
#endif

  std::ifstream fIn("fact4.in");;
  std::ofstream fOut("fact4.out");
  if (!fIn.is_open() || !fOut.is_open()) {
      std::cerr << "Failed to open file";
      goto Return;
  }

  int nInput;
  fIn >> nInput;
  
  fOut << SpecialFactorial(nInput, NumberOfFives(nInput)) << std::endl;

Return:
  if (fIn.is_open()){
      fIn.close();
  }
  if (fOut.is_open()){
      fOut.close();
  }
  fOut.close();
  
  return 0;
}
示例#2
0
文件: main.cpp 项目: nutti/GameEngine
int main( int argc, char** argv )
{
	if( argc != 3 ){
		std::cout << "Usage : ScriptCompiler.exe source_file out_file" << std::endl;
		return -1;
	}
	Compiler compiler;
	VM::Data data;
	compiler.Compile( argv[ 1 ], data );
	std::string str = argv[ 2 ];
	char s[ 4 ];
	std::fstream fOut( str.c_str(), std::ios::binary | std::ios::out );
	MAPIL::TransformInt32IntoChar( data.m_CommandSize, s, MAPIL::BYTE_ORDER_LITTLE );
	fOut.write( s, sizeof( s ) );
	fOut.write( reinterpret_cast < char* > ( data.m_Command ), sizeof( char ) * data.m_CommandSize );
	MAPIL::TransformInt32IntoChar( data.m_EntryPoint, s, MAPIL::BYTE_ORDER_LITTLE );
	fOut.write( s, sizeof( s ) );
	MAPIL::TransformInt32IntoChar( data.m_TextSize, s, MAPIL::BYTE_ORDER_LITTLE );
	fOut.write( s, sizeof( s ) );
	fOut.write( data.m_TextBuffer, sizeof( char ) * data.m_TextSize );
	MAPIL::TransformInt32IntoChar( data.m_ValueSize, s, MAPIL::BYTE_ORDER_LITTLE );
	fOut.write( s, sizeof( s ) );
	fOut.close();

	return 0;
}
void modCalcEquinox::processLines( QTextStream &istream ) {
    QFile fOut( OutputFileBatch->url().toLocalFile() );
    fOut.open(QIODevice::WriteOnly);
    QTextStream ostream(&fOut);
    int originalYear = Year->value();

    //Write header to output file
    ostream << i18n("# Timing of Equinoxes and Solstices\n")
    << i18n("# computed by KStars\n#\n")
    << i18n("# Vernal Equinox\t\tSummer Solstice\t\t\tAutumnal Equinox\t\tWinter Solstice\n#\n");

    while ( ! istream.atEnd() ) {
        QString line = istream.readLine();
        bool ok = false;
        int year = line.toInt( &ok );

        //for now I will simply change the value of the Year widget to trigger
        //computation of the Equinoxes and Solstices.
        if ( ok ) {
            //triggers slotCompute(), which sets values of dSpring et al.:
            Year->setValue( year );

            //Write to output file
            ostream << 
                KGlobal::locale()->formatDate( dSpring.date(), KLocale::LongDate ) << "\t"
            << KGlobal::locale()->formatDate( dSummer.date(), KLocale::LongDate ) << "\t"
            << KGlobal::locale()->formatDate( dAutumn.date(), KLocale::LongDate ) << "\t"
            << KGlobal::locale()->formatDate( dWinter.date(), KLocale::LongDate ) << endl;
        }
    }

    if ( Year->value() != originalYear )
        Year->setValue( originalYear );
}
示例#4
0
文件: Archiver.cpp 项目: nutti/MAPIL
	MapilVoid Archiver::Save( const MapilChar* pFileName )
	{
		Open( pFileName, FILE_OPEN_WRITE_MODE );

		std::basic_ofstream < MapilChar > fOut( m_ArchiveName.c_str(), std::ios::binary | std::ios::out );
		MapilInt32 offset = 0;

		for( MapilInt32 i = 0; i < m_FileTotal; ++i ){
			std::basic_ifstream < MapilChar > fIn( m_FileName[ i ], std::ios::binary | std::ios::in );
			m_FileSize.push_back( GetDataSize( &fIn ) );
			m_FilePos.push_back( offset );
			offset += m_FileSize[ i ];
			MapilChar* pData = new MapilChar [ m_FileSize[ i ] ];
			fIn.read( pData, m_FileSize[ i ] );
			// Copy data.
			fOut.write( pData, m_FileSize[ i ] );
			SafeDeleteArray( pData );
			fIn.close();
		}

		// Setup the file information.
		SaveInt( &fOut, m_FileTotal );
		for( MapilInt32 i = 0; i < m_FileTotal; ++i ){
			SaveInt( &fOut, m_FilePos[ i ] );
			SaveInt( &fOut, strlen( m_FileName[ i ] ) );
			fOut.write( m_FileName[ i ], strlen( m_FileName[ i ] ) );
			SaveInt( &fOut, m_FileSize[ i ] );
		}
		SaveInt( &fOut, offset );

		fOut.close();
	}
示例#5
0
/*
Saves matrix to file

@param filename filename for the txt output
@param mat matrix to be outputted
*/
void	saveMatrix(const std::string filename, const Matrix& mat){
	std::ofstream	fOut(filename);
	if (!fOut) {
		std::cout << "Error opening file: " << filename << std::endl;
		exit(EXIT_FAILURE);
	}

	if(!(fOut << mat.getDimM() << " " << mat.getDimN() << std::endl))
	{
		std::cout << "Error in writing matrix entries!" << std::endl;
		exit(EXIT_FAILURE);
	}

	for (int m = 0; m < mat.getDimM(); m++) {
		for (int n = 0; n < mat.getDimN(); n++) {
			if(!(fOut << mat(m, n) << std::endl))
			{
				std::cout << "Error in writing matrix entries!" << std::endl;
				exit(EXIT_FAILURE);
			}
		}
	}

	fOut.close();
}
示例#6
0
void modCalcDayLength::processLines( QTextStream &istream ) {
    QFile fOut( OutputFileBatch->url().toLocalFile() );
    fOut.open(QIODevice::WriteOnly);
    QTextStream ostream(&fOut);

    //Write header
    ostream << "# " << i18nc("%1 is a location on earth", "Almanac for %1", geoBatch->fullName())
    << QString("  [%1, %2]").arg(geoBatch->lng()->toDMSString()).arg(geoBatch->lat()->toDMSString()) << endl
    << "# " << i18n("computed by KStars") << endl
    << "#" << endl
    << "# Date      SRise  STran  SSet     SRiseAz      STranAlt      SSetAz     DayLen    MRise  MTran  MSet      MRiseAz      MTranAlt      MSetAz     LunarPhase" << endl
    << "#" << endl;

    QString line;
    QDate d;

    while ( ! istream.atEnd() ) {
        line = istream.readLine();
        line = line.trimmed();

        //Parse the line as a date, then compute Almanac values
        d = QDate::fromString( line );
        if ( d.isValid() ) {
            updateAlmanac( d, geoBatch );
            ostream << d.toString( Qt::ISODate ) << "  "
            << srTimeString << "  " << stTimeString << "  " << ssTimeString << "  "
            << srAzString << "  " << stAltString << "  " << ssAzString << "  "
            << daylengthString << "    "
            << mrTimeString << "  " << mtTimeString << "  " << msTimeString << "  "
            << mrAzString << "  " << mtAltString << "  " << msAzString << "  "
            << lunarphaseString << endl;
        }
    }
}
示例#7
0
	void ConfigDataHolder::Impl::Save( const std::string& fileName )
	{
		if( !FileExist( "config" ) ){
			CreateDirectory( "config" );
		}

		std::fstream fOut( fileName, std::ios::out );
		if( !fOut ){
			return;
		}

		fOut << "BGM=" << m_ConfigFileData.m_ConfigData.m_BGMVolume << std::endl;
		fOut << "SE=" << m_ConfigFileData.m_ConfigData.m_SEVolume << std::endl;
		std::string strings[ 7 ] = { "1/4", "1/3", "1/2", "x1", "x2", "x3", "x4" };
		fOut << "PLAY_SPEED=" << strings[ m_ConfigFileData.m_ConfigData.m_PlaySpeed ] << std::endl;

		char* pCapsStr[ GENERAL_BUTTON_TOTAL ] = {	"MOVE_UP",
													"MOVE_DOWN",
													"MOVE_RIGHT",
													"MOVE_LEFT",
													"SHOT",
													"BOMB",
													"GREEN",
													"BLUE",
													"RED" };

		for( int i = 0; i < GENERAL_BUTTON_TOTAL; ++i ){
			std::string s = "KEYBOARD_";
			s += pCapsStr[ i ];
			s += "=";
			fOut << s << GetStringFromButton( m_ConfigFileData.m_ConfigData.m_KeyboardCaps[ i ] ) << std::endl;
		}

		fOut.close();
	}
示例#8
0
// TODO: fix alternate cohesion crap
void OnCompressOrDecompress(HWND sheet, bool compress)
{
	int size, ret;
	char path[_MAX_PATH];

	if (!GetOpenFileNameA(sheet, path, sizeof(path)))
		return;

	size = fsize(path);
	std::vector<unsigned char> buffer(size);

	AutoFile fIn(path, "rb");
	fread(&buffer[0], sizeof(char), size, fIn.get()); // contiguous
	fIn.close();

	path[0] = '\0';   // don't pre-fill path
	if (!GetSaveFileNameA(sheet, path, sizeof(path)))
		return;

	AutoFile fOut(path, "wb");

	if (compress)
		ret = deflate_file(&buffer[0], size, fOut.get());
	else
		ret = inflate_file(&buffer[0], size, fOut.get());

	fOut.close();

	if (ret >= 0)
		MessageBox(sheet, "Operation completed successfully.",
		"Raw Compression/Decompression", MB_OK);
	else
		MessageBox(sheet, "Operation failed.",
		"Raw Compression/Decompression", MB_ICONWARNING);
}
bool DecompressorUMX::decompress(const PPSystemString& outFileName, Hints hint)
{
	// If client requests something else than a module we can't deal we that
	if (hint != HintAll &&
		hint != HintModules)
		return false;

	XMFile f(fileName);	

	int i;
	pp_uint8 *buf, *b;
	int len, offset = -1;

	if ((b = buf = new pp_uint8[0x10000]) == NULL)
		return false;

	f.read(buf, 1, TEST_SIZE);
	for (i = 0; i < TEST_SIZE; i++, b++) {
		pp_uint32 id;

		id = BigEndian::GET_DWORD(b);

		if (!memcmp(b, "Extended Module:", 16)) {
			offset = i;
			break;
		}
		if (id == MAGIC_IMPM) { 
			offset = i;
			break;
		}
		if (i > 44 && id == MAGIC_SCRM) { 
			offset = i - 44;
			break;
		}
		if (i > 1080 && id == MAGIC_M_K_) { 
			offset = i - 1080;
			break;
		}
	}
	
	if (offset < 0) {
		delete[] buf;
		return false;
	}

	f.seek(offset);
	
	XMFile fOut(outFileName, true);

	do {
		len = f.read(buf, 1, 0x10000);
		fOut.write(buf, 1, len);
	} while (len == 0x10000);

	delete[] buf;

	return true;
}
示例#10
0
文件: subfam.cpp 项目: Wyss/mauve-py
void AlignSubFam(SeqVect &vAll, const Tree &GuideTree, unsigned uNodeIndex,
  MSA &msaOut)
	{
	const unsigned uSeqCount = vAll.GetSeqCount();

	const char *InTmp = "asf_in.tmp";
	const char *OutTmp = "asf_out.tmp";

	unsigned *Leaves = new unsigned[uSeqCount];
	unsigned uLeafCount;
	GetLeaves(GuideTree, uNodeIndex, Leaves, &uLeafCount);

	SeqVect v;
	for (unsigned i = 0; i < uLeafCount; ++i)
		{
		unsigned uLeafNodeIndex = Leaves[i];
		unsigned uId = GuideTree.GetLeafId(uLeafNodeIndex);
		Seq &s = vAll.GetSeqById(uId);
		v.AppendSeq(s);
		}

#if	TRACE
	{
	Log("Align subfam[node=%d, size=%d] ", uNodeIndex, uLeafCount);
	for (unsigned i = 0; i < uLeafCount; ++i)
		Log(" %s", v.GetSeqName(i));
	Log("\n");
	}
#endif

	TextFile fIn(InTmp, true);

	v.ToFASTAFile(fIn);
	fIn.Close();

	char CmdLine[4096];
	sprintf(CmdLine, "probcons %s > %s 2> /dev/null", InTmp, OutTmp);
//	sprintf(CmdLine, "muscle -in %s -out %s -maxiters 1", InTmp, OutTmp);
	system(CmdLine);

	TextFile fOut(OutTmp);
	msaOut.FromFile(fOut);

	for (unsigned uSeqIndex = 0; uSeqIndex < uLeafCount; ++uSeqIndex)
		{
		const char *Name = msaOut.GetSeqName(uSeqIndex);
		unsigned uId = vAll.GetSeqIdFromName(Name);
		msaOut.SetSeqId(uSeqIndex, uId);
		}

	unlink(InTmp);
	unlink(OutTmp);

	delete[] Leaves;
	}
示例#11
0
void modCalcEquinox::slotViewBatch() {
    QFile fOut( OutputFileBatch->url().toLocalFile() );
    fOut.open(QIODevice::ReadOnly);
    QTextStream istream(&fOut);
    QStringList text;

    while ( ! istream.atEnd() )
        text.append( istream.readLine() );

    fOut.close();

    KMessageBox::informationList( 0, i18n("Results of Sidereal time calculation"), text, OutputFileBatch->url().toLocalFile() );
}
示例#12
0
bufsize_t AbstractFileBuffer::dump(QString path, AbstractByteBuffer &bBuf, bool allowExceptions)
{
    BYTE* buf = bBuf.getContent();
    bufsize_t bufSize  = bBuf.getContentSize();
    if (buf == NULL) {
        if (allowExceptions) throw FileBufferException("Buffer is empty");
        return 0;
    }
    QFile fOut(path);
    if (fOut.open(QFile::WriteOnly) == false) {
        if (allowExceptions) throw FileBufferException("Cannot open the file: " + path + " for writing");
        return 0;
    }
    bufsize_t wrote = static_cast<bufsize_t> (fOut.write((char*)buf, bufSize));
    fOut.close();
    return wrote;
}
示例#13
0
// Saves this matrix to file
// Returns +1 if an error occurs, 0 otherwise.
int fMatrix::toFile(QString filename) {
    QFile fOut(filename);

    // Check if we can even write to a file.
    if (! fOut.open(QFile :: WriteOnly)) {
        qDebug() << "Unable to open file for writing!";
        return 1;
    }

    // Write the matrix dimensions to file.
    fOut.write((char *) &num_rows, sizeof(int));
    fOut.write((char *) &num_cols, sizeof(int));

    // Write each entry to file.
    for (int i = 0; i < num_rows; i++)
        for (int j = 0; j < num_cols; j++) {
            float result = this->getEntry(i, j);
            fOut.write((char *) &result, sizeof(float));
        }
    fOut.flush();
    fOut.close();
    return 0;
}
示例#14
0
void CEphTable::on_pushButton_3_clicked()
/////////////////////////////////////////
{
  QString name = QFileDialog::getSaveFileName(this, tr("Save File"),
                                             "untitled.csv",
                                             tr("CSV Files (*.csv)"));
  if (name.isEmpty())
    return;

  const int rowCount = ui->tableView->model()->rowCount();
  const int columnCount = ui->tableView->model()->columnCount();

  SkFile fOut(name);
  if (fOut.open(SkFile::WriteOnly | SkFile::Text))
  {
    QTextStream s(&fOut);

    for (int column = 0; column < columnCount; column++)
    {
      s << ui->tableView->model()->headerData(column, Qt::Horizontal).toString();
      s << ";";
    }

    s << "\n";

    for (int row = 0; row < rowCount; row++)
    {
      for (int column = 0; column < columnCount; column++)
      {
        QString data = ui->tableView->model()->data(ui->tableView->model()->index(row, column)).toString().simplified();
        s << data + ";";
      }
      s << "\n";
    }
  }
  fOut.close();
}
示例#15
0
/*---------------------------------------------------------------------------
* Daten im CSV-Format speichern
*---------------------------------------------------------------------------*/
void MainWindow::on_actionCSVSpeichern_triggered()
{
   // Daten vorhanden?
   if(data.isEmpty())
   {
      QMessageBox::warning( this,
                            tr("keine Daten"),
                            tr("Z.Z. sind keine Daten vorhanden!<br>Deshalb kann auch nichts gespeichert werden!"));
      return;
   }

   // Dateinamen abfragen
   QString fileName = QFileDialog::getSaveFileName( this,
                                                    tr("Daten speichern"),
                                                    ".",
                                                    tr("CSV-Dateien (*.csv);;Alle Dateien (*.*)"));
   if( fileName == "") return;

   // Separator wechseln, wenn "," schon Decimal-Separator ist
   QChar separator = ',';
   if( QLocale::system().decimalPoint() == ',') separator = ';';

   // Ausgabedatei oeffnen
   QFile fOut(fileName);
   if (!fOut.open(QIODevice::WriteOnly | QIODevice::Text))
   {
      QMessageBox::critical( this,
                             tr("Fehler"),
                             tr("FEHLER: beim öffnen der CSV-Datei '%1'!").arg(fileName));
      return;
   }
   QTextStream out(&fOut);

   setCursor(Qt::WaitCursor);
   QCoreApplication::processEvents();

   // Kopfzeile
   out << tr("Datum/Uhrzeit") << separator << tr("Zeitstempel");
   for( int i=0; i<DataFile::fieldCount(); i++)
      out << separator << DataFile::fieldInfo(i).prettyName;
   out << endl;

   // Daten schreiben
   DataMap::const_iterator iterator = data.constBegin();
   do
   {
      QDateTime timestamp = QDateTime::fromTime_t(iterator.key());
      DataFieldValues values = iterator.value();

      // Datum + Zeitstempel
      out << timestamp.toString("yyyy-MM-dd hh:mm:ss")
          << separator
          << iterator.key();
      // Felder
      for( int i=0; i<values.size(); i++)
         out << separator << QLocale::system().toString(values[i]);
      out << endl;

      // naechster Datensatz
      iterator++;
   } while( iterator != data.constEnd());

   // Ausgabedatei schliessen
   fOut.close();

   setCursor(Qt::ArrowCursor);
}
示例#16
0
void modCalcEquinox::processLines( QTextStream &istream ) {

	// we open the output file

//	QTextStream istream(&fIn);
	QString outputFileName;
	outputFileName = OutputLineEditBatch->text();
	QFile fOut( outputFileName );
	fOut.open(IO_WriteOnly);
	QTextStream ostream(&fOut);

	QString line;
	QString space = " ";
	int yearB;
	int i = 0;
	long double jdsp = 0., jdsu = 0., jdau = 0., jdwin = 0., jdsp1 = 0.;
	KStarsData *kd = (KStarsData*) parent()->parent()->parent();
	KSSun *Sun = new KSSun(kd);

	while ( ! istream.eof() ) {
		line = istream.readLine();
		line.stripWhiteSpace();

		//Go through the line, looking for parameters

		QStringList fields = QStringList::split( " ", line );

		i = 0;

		// Read year and write in ostream if corresponds

		if(yearCheckBatch->isChecked() ) {
			yearB = fields[i].toInt();
			i++;
		} else
			yearB = yearEditBatch->text().toInt();

		if ( allRadioBatch->isChecked() )
			ostream << yearB << space;
		else
			if(yearCheckBatch->isChecked() )
				ostream << yearB << space;

		jdsp = Sun->springEquinox(yearB);
		jdsu = Sun->summerSolstice(yearB);
		jdau = Sun->autumnEquinox(yearB);
		jdwin = Sun->winterSolstice(yearB);
		jdsp1 = Sun->springEquinox(yearB+1);

		KStarsDateTime dts( jdsp );
		KStarsDateTime dtu( jdsu );
		KStarsDateTime dta( jdau );
		KStarsDateTime dtw( jdwin );

		ostream << dts.toString(Qt::ISODate) << space << (float)(jdsu - jdsp) << space 
						<< dtu.toString(Qt::ISODate) << space << (float)(jdau - jdsu) << space 
						<< dta.toString(Qt::ISODate) << space << (float)(jdwin - jdau) << space 
						<< dtw.toString(Qt::ISODate) << space << (float)(jdsp1 - jdwin) << endl;
	}


	fOut.close();
}
示例#17
0
ShapeParser::ShapeParseResult ShapeParser::serialized(const XMLNode& node, ParserState& S)
{
	auto filename = S.map_asset_filepath(S.def_storage.prop_string(node, "filename"));
	int submesh_index = S.def_storage.prop_int(node, "shapeIndex");
	bool flipNormals = S.def_storage.prop_bool(node, "flipNormals", false);
	bool faceNormals = S.def_storage.prop_bool(node, "faceNormals", false);
	float maxSmoothAngle = S.def_storage.prop_float(node, "maxSmoothAngle", 0.0f);

	auto name = boost::filesystem::path(filename).stem().string();
	auto compiled_tar_folder = S.scene.getFileManager()->getCompiledMeshPath("") + name + "/";

	auto get_compiled_submesh_filename = [&](size_t i)
	{
		return compiled_tar_folder + std::to_string(i) + ".xmsh";
	};

	if (!boost::filesystem::exists(compiled_tar_folder) || !boost::filesystem::exists(get_compiled_submesh_filename(0)))
	{
		boost::filesystem::create_directory(compiled_tar_folder);

		enum DataPresentFlag : uint32_t
		{
			VertexNormals = 0x0001,
			TextureCoords = 0x0002,
			VertexColors = 0x0008,
			UseFaceNormals = 0x0010,
			SinglePrecision = 0x1000,
			DoublePrecision = 0x2000,
		};

		struct inflateStream
		{
			std::ifstream& m_childStream;
			size_t str_length;
			z_stream m_inflateStream;
			uint8_t m_inflateBuffer[32768];
			inflateStream(std::ifstream& str)
				:m_childStream(str)
			{
				size_t pos = m_childStream.tellg();
				m_childStream.seekg(0, m_childStream.end);
				str_length = m_childStream.tellg();
				m_childStream.seekg(pos, m_childStream.beg);

				m_inflateStream.zalloc = Z_NULL;
				m_inflateStream.zfree = Z_NULL;
				m_inflateStream.opaque = Z_NULL;
				m_inflateStream.avail_in = 0;
				m_inflateStream.next_in = Z_NULL;

				int windowBits = 15;
				auto retval = inflateInit2(&m_inflateStream, windowBits);
				if (retval != Z_OK)
					std::cout << "erro, ret : " << retval << std::endl;
			}

			void read(void *ptr, size_t size)
			{
				uint8_t *targetPtr = (uint8_t *)ptr;
				while (size > 0) {
					if (m_inflateStream.avail_in == 0) {
						size_t remaining = str_length - m_childStream.tellg();
						m_inflateStream.next_in = m_inflateBuffer;
						m_inflateStream.avail_in = (uInt)std::min(remaining, sizeof(m_inflateBuffer));
						if (m_inflateStream.avail_in == 0)
							std::cout << "more bytes req : " << size << std::endl;
						m_childStream.read((char*)m_inflateBuffer, m_inflateStream.avail_in);
					}

					m_inflateStream.avail_out = (uInt)size;
					m_inflateStream.next_out = targetPtr;

					int retval = inflate(&m_inflateStream, Z_NO_FLUSH);
					switch (retval) {
					case Z_STREAM_ERROR:
						throw std::runtime_error("inflate(): stream error!");
					case Z_NEED_DICT:
						throw std::runtime_error("inflate(): need dictionary!");
					case Z_DATA_ERROR:
						throw std::runtime_error("inflate(): data error!");
					case Z_MEM_ERROR:
						throw std::runtime_error("inflate(): memory error!");
					};

					size_t outputSize = size - (size_t)m_inflateStream.avail_out;
					targetPtr += outputSize;
					size -= outputSize;

					if (size > 0 && retval == Z_STREAM_END)
						throw std::runtime_error("inflate(): attempting to read past the end of the stream!");
				}
			}
		};

		std::ifstream ser_str(filename, std::ios::binary);

		uint16_t magic_maj, version_maj;
		ser_str.read((char*)&magic_maj, 2);
		if (magic_maj != 1052)
			throw std::runtime_error("corrupt file");
		ser_str.read((char*)&version_maj, 2);

		ser_str.seekg(-4, ser_str.end);
		uint32_t n_meshes;
		ser_str.read((char*)&n_meshes, sizeof(n_meshes));
		ser_str.seekg(-(sizeof(uint32_t) + (version_maj == 4 ? sizeof(uint64_t) : sizeof(uint32_t)) * n_meshes), ser_str.end);
		std::vector<uint64_t> mesh_offsets(n_meshes);
		if (version_maj == 4)
			ser_str.read((char*)mesh_offsets.data(), n_meshes * sizeof(uint64_t));
		else
		{
			auto q = std::vector<uint32_t>(n_meshes);
			ser_str.read((char*)q.data(), n_meshes * sizeof(uint32_t));
			for (size_t i = 0; i < n_meshes; i++)
				mesh_offsets[i] = q[i];
		}

		for (size_t num_submesh = 0; num_submesh < n_meshes; num_submesh++)
		{
			ser_str.seekg(mesh_offsets[num_submesh], ser_str.beg);
			uint16_t magic, version;
			ser_str.read((char*)&magic, 2);
			if (magic == 0)
				break;
			ser_str.read((char*)&version, 2);
			if (version != 3 && version != 4)
				throw std::runtime_error("invalid version in serialized mesh file");

			inflateStream comp_str(ser_str);
			DataPresentFlag flag;
			comp_str.read(&flag, sizeof(flag));
			std::string name = "default";
			if (version == 4)
			{
				name = "";
				char last_read;
				do
				{
					comp_str.read(&last_read, sizeof(last_read));
					name += last_read;
				} while (last_read != 0);
			}
			uint64_t nVertices, nTriangles;
			comp_str.read(&nVertices, sizeof(nVertices));
			comp_str.read(&nTriangles, sizeof(nTriangles));

			std::vector<Vec3f> positions(nVertices), normals(nVertices), colors(nVertices);
			std::vector<Vec2f> uvcoords(nVertices);
			std::vector<uint32_t> indices(nTriangles * 3);

			bool isSingle = true;

			auto read_n_vector = [&](int dim, float* buffer)
			{
				if (isSingle)
					comp_str.read((char*)buffer, sizeof(float) * dim * nVertices);
				else
				{
					double* double_storage = (double*)alloca(dim * sizeof(double));
					for (size_t i = 0; i < nVertices; i++)
					{
						comp_str.read((char*)double_storage, dim * sizeof(double));
						for (int j = 0; j < dim; j++)
							buffer[i * dim + j] = float(double_storage[j]);
					}
				}
			};

			read_n_vector(3, (float*)positions.data());
			if ((flag & DataPresentFlag::VertexNormals) == DataPresentFlag::VertexNormals)
				read_n_vector(3, (float*)normals.data());
			if ((flag & DataPresentFlag::TextureCoords) == DataPresentFlag::TextureCoords)
				read_n_vector(2, (float*)uvcoords.data());
			else std::fill(uvcoords.begin(), uvcoords.end(), Vec2f(0.0f));
			if ((flag & DataPresentFlag::VertexColors) == DataPresentFlag::VertexColors)
				read_n_vector(3, (float*)colors.data());

			comp_str.read((char*)indices.data(), sizeof(uint32_t) * nTriangles * 3);
			for (size_t i = 0; i < nTriangles * 3; i += 3)
				std::swap(indices[i + 0], indices[i + 2]);

			auto compiled_submesh_filename = get_compiled_submesh_filename(num_submesh);
			FileOutputStream fOut(compiled_submesh_filename);
			fOut << (unsigned int)MeshCompileType::Static;
			auto mat = Material(name.size() > 60 ? name.substr(0, 60) : name);
			mat.bsdf = CreateAggregate<BSDFALL>(diffuse());
			Mesh::CompileMesh(positions.data(), (int)positions.size(), normals.data(), uvcoords.data(), indices.data(), (int)indices.size(), mat, 0.0f, fOut, flipNormals, faceNormals, maxSmoothAngle);
			fOut.Close();
		}
		ser_str.close();
	}

	auto obj = S.scene.CreateNode(get_compiled_submesh_filename(submesh_index));
	parseGeneric(obj, node, S);
	return obj;
}
示例#18
0
void modCalcVlsr::processLines( QTextStream &istream ) {

    // we open the output file

    //	QTextStream istream(&fIn);
    QString outputFileName;
    outputFileName = OutputFileBoxBatch->url().toLocalFile();
    QFile fOut( outputFileName );
    fOut.open(QIODevice::WriteOnly);
    QTextStream ostream(&fOut);

    QString line;
    QChar space = ' ';
    int i = 0;
    long double jd0;
    SkyPoint spB;
    double sra, cra, sdc, cdc;
    dms raB, decB, latB, longB;
    QString epoch0B;
    double vhB, vgB, vtB, vlsrB, heightB;
    double vtopo[3];
    QTime utB;
    QDate dtB;
    KStarsDateTime dt0B;

    while ( ! istream.atEnd() ) {
        line = istream.readLine();
        line.trimmed();

        //Go through the line, looking for parameters

        QStringList fields = line.split( ' ' );

        i = 0;

        // Read Ut and write in ostream if corresponds

        if(UTCheckBatch->isChecked() ) {
            utB = QTime::fromString( fields[i] );
            i++;
        } else
            utB = UTBoxBatch->time();

        if ( AllRadioBatch->isChecked() )
            ostream << KGlobal::locale()->formatTime( utB ) << space;
        else
            if(UTCheckBatch->isChecked() )
                ostream << KGlobal::locale()->formatTime( utB ) << space;

        // Read date and write in ostream if corresponds

        if(DateCheckBatch->isChecked() ) {
            dtB = QDate::fromString( fields[i] );
            i++;
        } else
            dtB = DateBoxBatch->date();
        if ( AllRadioBatch->isChecked() )
            ostream << KGlobal::locale()->formatDate( dtB, KLocale::LongDate ).append(space);
        else
            if(DateCheckBatch->isChecked() )
                ostream << KGlobal::locale()->formatDate( dtB, KLocale::LongDate ).append(space);

        // Read RA and write in ostream if corresponds

        if(RACheckBatch->isChecked() ) {
            raB = dms::fromString( fields[i],false);
            i++;
        } else
            raB = RABoxBatch->createDms(false);

        if ( AllRadioBatch->isChecked() )
            ostream << raB.toHMSString() << space;
        else
            if(RACheckBatch->isChecked() )
                ostream << raB.toHMSString() << space;

        // Read DEC and write in ostream if corresponds

        if(DecCheckBatch->isChecked() ) {
            decB = dms::fromString( fields[i], true);
            i++;
        } else
            decB = DecBoxBatch->createDms();

        if ( AllRadioBatch->isChecked() )
            ostream << decB.toDMSString() << space;
        else
            if(DecCheckBatch->isChecked() )
                ostream << decB.toDMSString() << space;

        // Read Epoch and write in ostream if corresponds

        if(EpochCheckBatch->isChecked() ) {
            epoch0B = fields[i];
            i++;
        } else
            epoch0B = EpochBoxBatch->text();

        if ( AllRadioBatch->isChecked() )
            ostream << epoch0B << space;
        else
            if(EpochCheckBatch->isChecked() )
                ostream << epoch0B << space;

        // Read vlsr and write in ostream if corresponds

        if(InputVelocityCheckBatch->isChecked() ) {
            vlsrB = fields[i].toDouble();
            i++;
        } else
            vlsrB = InputVelocityComboBatch->currentText().toDouble();

        if ( AllRadioBatch->isChecked() )
            ostream << vlsrB << space;
        else
            if(InputVelocityCheckBatch->isChecked() )
                ostream << vlsrB << space;

        // Read Longitude and write in ostream if corresponds

        if (LongCheckBatch->isChecked() ) {
            longB = dms::fromString( fields[i],true);
            i++;
        } else
            longB = LongitudeBoxBatch->createDms(true);

        if ( AllRadioBatch->isChecked() )
            ostream << longB.toDMSString() << space;
        else
            if (LongCheckBatch->isChecked() )
                ostream << longB.toDMSString() << space;

        // Read Latitude


        if (LatCheckBatch->isChecked() ) {
            latB = dms::fromString( fields[i], true);
            i++;
        } else
            latB = LatitudeBoxBatch->createDms(true);
        if ( AllRadioBatch->isChecked() )
            ostream << latB.toDMSString() << space;
        else
            if (LatCheckBatch->isChecked() )
                ostream << latB.toDMSString() << space;

        // Read height and write in ostream if corresponds

        if(ElevationCheckBatch->isChecked() ) {
            heightB = fields[i].toDouble();
            i++;
        } else
            heightB = ElevationBoxBatch->text().toDouble();

        if ( AllRadioBatch->isChecked() )
            ostream << heightB << space;
        else
            if(ElevationCheckBatch->isChecked() )
                ostream << heightB << space;

        // We make the first calculations

        spB = SkyPoint (raB, decB);
        dt0B.setFromEpoch(epoch0B);
        vhB = spB.vHeliocentric(vlsrB, dt0B.djd());
        jd0 = KStarsDateTime(dtB,utB).djd();
        vgB = spB.vGeocentric(vlsrB, jd0);
        geoPlace->setLong( longB );
        geoPlace->setLat(  latB );
        geoPlace->setHeight( heightB );
        dms gsidt = KStarsDateTime(dtB,utB).gst();
        geoPlace->TopocentricVelocity(vtopo, gsidt);
        spB.ra().SinCos(sra, cra);
        spB.dec().SinCos(sdc, cdc);
        vtB = vgB - (vtopo[0]*cdc*cra + vtopo[1]*cdc*sra + vtopo[2]*sdc);

        ostream << vhB << space << vgB << space << vtB << endl;

    }


    fOut.close();
}
示例#19
0
void RefineW(const MSA &msaIn, MSA &msaOut)
	{
	const unsigned uSeqCount = msaIn.GetSeqCount();
	const unsigned uColCount = msaIn.GetColCount();

// Reserve same nr seqs, 20% more cols
	const unsigned uReserveColCount = (uColCount*120)/100;
	msaOut.SetSize(uSeqCount, uReserveColCount);

	for (unsigned uSeqIndex = 0; uSeqIndex < uSeqCount; ++uSeqIndex)
		{
		msaOut.SetSeqName(uSeqIndex, msaIn.GetSeqName(uSeqIndex));
		msaOut.SetSeqId(uSeqIndex, msaIn.GetSeqId(uSeqIndex));
		}

	const unsigned uWindowCount = (uColCount + g_uRefineWindow - 1)/g_uRefineWindow;
	if (0 == g_uWindowTo)
		g_uWindowTo = uWindowCount - 1;

#if	MEMDEBUG
	_CrtSetBreakAlloc(1560);
#endif

	if (g_uWindowOffset > 0)
		{
		MSA msaTmp;
		MSAFromColRange(msaIn, 0, g_uWindowOffset, msaOut);
		}

	fprintf(stderr, "\n");
	for (unsigned uWindowIndex = g_uWindowFrom; uWindowIndex <= g_uWindowTo; ++uWindowIndex)
		{
		fprintf(stderr, "Window %d of %d    \r", uWindowIndex, uWindowCount);
		const unsigned uColFrom = g_uWindowOffset + uWindowIndex*g_uRefineWindow;
		unsigned uColTo = uColFrom + g_uRefineWindow - 1;
		if (uColTo >= uColCount)
			uColTo = uColCount - 1;
		assert(uColTo >= uColFrom);

		SeqVect v;
		SeqVectFromMSACols(msaIn, uColFrom, uColTo, v);

#if	MEMDEBUG
		_CrtMemState s1;
		_CrtMemCheckpoint(&s1);
#endif

		MSA msaTmp;
		MUSCLE(v, msaTmp);
		AppendMSA(msaOut, msaTmp);
		if (uWindowIndex == g_uSaveWindow)
			{
			MSA msaInTmp;
			unsigned uOutCols = msaOut.GetColCount();
			unsigned un = uColTo - uColFrom + 1;
			MSAFromColRange(msaIn, uColFrom, un, msaInTmp);

			char fn[256];
			sprintf(fn, "win%d_inaln.tmp", uWindowIndex);
			TextFile fIn(fn, true);
			msaInTmp.ToFile(fIn);

			sprintf(fn, "win%d_inseqs.tmp", uWindowIndex);
			TextFile fv(fn, true);
			v.ToFile(fv);

			sprintf(fn, "win%d_outaln.tmp", uWindowIndex);
			TextFile fOut(fn, true);
			msaTmp.ToFile(fOut);
			}

#if	MEMDEBUG
		void FreeDPMemSPN();
		FreeDPMemSPN();

		_CrtMemState s2;
		_CrtMemCheckpoint(&s2);

		_CrtMemState s;
		_CrtMemDifference(&s, &s1, &s2);

		_CrtMemDumpStatistics(&s);
		_CrtMemDumpAllObjectsSince(&s1);
		exit(1);
#endif
//#if	DEBUG
//		AssertMSAEqIgnoreCaseAndGaps(msaInTmp, msaTmp);
//#endif
		}
	fprintf(stderr, "\n");

//	AssertMSAEqIgnoreCaseAndGaps(msaIn, msaOut);//@@uncomment!
	}
示例#20
0
/*
 * Create a denumerator table used for computing conditional probability, such as P(B|AC) = P(ABC)/[sum_all_B{P(ABC)}]
 **/
QVector< QVector<int> > getAssignmentDenum(const QVector< QVector<int> > &A, int excludedVarPos, bool validate, bool *ok, QString denumFile, bool showDebugInfo)
{
    bool OK = true;
    QVector< QVector<int> > denumTable;
    bool createNew = false;
    bool saveToFile = false;
    QString line;
    int cnt;

    if(!denumFile.isEmpty() || !denumFile.isNull())
    {
        QStringList items;
        QFile fid(denumFile);
        int cntr = 0;
        if(fid.exists())
        {
            fid.open(QIODevice::ReadOnly | QIODevice::Text);
            while(!fid.atEnd())
            {
                line = fid.readLine();
                items = line.split(',');
                if(items.count()>0)
                {
                    cntr++;
                    denumTable.resize(cntr);
                    for(int i=0; i<items.count(); i++)
                        denumTable[cntr-1].append(items.at(i).toInt());
                }
            }
            fid.close();
            /* if denumTable from file doesn't match the length of assignment table A, then create new */
            if(A.count()!=denumTable.count())
            {
                qDebug() << "DenumTable from file doesn't match assignment table A. Hence a new denumTable will be created!";
                createNew = true;
            }
        }
        else
        {
            createNew = true; //if denumFile is specified but doesn't exist
            saveToFile = true; //then we will create it and save it to a file
        }
    }
    else createNew = true;

    if(createNew)
    {
        cnt = A.count();            //how many rows of A?
        denumTable.resize(cnt);

        QVector<int> checkA, epochA;
        for(int i=0; i<cnt; i++)
        {
            if(showDebugInfo)
            {
                qDebug() << QString("Processing index %1 out of %2 (%3%%)").arg(i).arg(cnt).arg(i*100/cnt);
            }
            if(denumTable.at(i).isEmpty())
            {
                checkA = A.at(i);
                checkA.remove(excludedVarPos,1);
                for(int j=0; j<cnt; j++)
                {
                    epochA = A.at(j);
                    epochA.remove(excludedVarPos,1);
                    if(checkA == epochA)
                    {
                        denumTable[i].append(j);
                    }
                }
                /* then copy the resulted denumTable[i] to all equivalent position to save time */
                for(int k=0; k<cnt; k++)
                {
                    if(denumTable.at(i).indexOf(k)!=-1 && denumTable.at(k).isEmpty())
                        for(int l=0; l<denumTable[i].count(); l++)
                            denumTable[k].append(denumTable[i].at(l));
                }
            }
        }
        if(saveToFile)
        {
            QFile fid(denumFile);
            QTextStream fOut(&fid);
            fid.open(QIODevice::WriteOnly | QIODevice::Text);
            for(int i=0; i<denumTable.count(); i++)
            {
                line.clear();
                for(int j=0; j<denumTable[i].count(); j++)
                    line.append(QString("%1,").arg(denumTable.at(i).at(j)));
                line.remove(line.length()-1,1); //remove the last comma
                fOut << QString("%1\n").arg(line);
            }
            fid.close();
        }
    }

    if(validate)
        for(int i=1; i<cnt; i++)
            if(denumTable.at(i).count()!=denumTable.at(i-1).count())
            {
                OK = false;
                qFatal("Found mismatch!");
            }

    if(ok!=0) *ok = OK;
    return denumTable;
}
示例#21
0
void modCalcSidTime::processLines( QTextStream &istream ) {
    QFile fOut( OutputFileBatch->url().toLocalFile() );
    fOut.open(QIODevice::WriteOnly);
    QTextStream ostream(&fOut);

    QString line;
    dms LST;
    QTime inTime, outTime;
    QDate dt;

    if ( ! DateCheckBatch->isChecked() )
        dt = DateBatch->date();

    while ( ! istream.atEnd() ) {
        line = istream.readLine();
        line = line.trimmed();

        QStringList fields = line.split( ' ', QString::SkipEmptyParts );

        //Find and parse the location string
        if (LocationCheckBatch->isChecked() ) {
            //First, look for a pair of quotation marks, and parse the string between them
            QChar q = '\"';
            if ( line.indexOf(q) == -1 ) q = '\'';
            if ( line.count(q)==2  ) {
                int iStart = line.indexOf(q);
                int iEnd = line.indexOf(q, iStart+1);
                QString locationString = line.mid(iStart, iEnd-iStart+1);
                line.remove( locationString );
                fields = line.split( ' ', QString::SkipEmptyParts );
                locationString.remove( q );

                QStringList locationFields = locationString.split( ',', QString::SkipEmptyParts );
                for (int i=0; i<locationFields.size(); i++)
                    locationFields[i] = locationFields[i].trimmed();

                if ( locationFields.size() == 1 ) locationFields.insert( 1, "" );
                if ( locationFields.size() == 2 ) locationFields.insert( 1, "" );
                if ( locationFields.size() != 3 ) {
                    qDebug() << "Error: could not parse location string: " << locationString;
                    continue;
                }

                geoBatch = KStarsData::Instance()->locationNamed( locationFields[0], locationFields[1], locationFields[2] );
                if ( ! geoBatch ) {
                    qDebug() << "Error: location not found in database: " << locationString;
                    continue;
                }
            }
        }

        if ( DateCheckBatch->isChecked() ) {
            //Parse one of the fields as the date
            foreach ( const QString &s, fields ) {
                dt = QDate::fromString( s );
                if ( dt.isValid() ) break;
            }
            if ( ! dt.isValid() ) {
                qDebug() << "Error: did not find a valid date string in: " << line;
                continue;
            }
        }
示例#22
0
/*
###############################*/
int main(int argc, char* argv[]) 
{
	const int imagecount = 60;	//total number of images

	for (int i = 0; i < imagecount; ++i)
	{
		std::ofstream fOut("zurendern/scene" + std::to_string(i) + ".txt"); //SDF-Datei

		//BASIC SCENE GEN:
		

		int objects=500; //total number of objects per scene 

		for(int j=0;j<objects; j++) //SET UP: SPHERERS
		{
			//generate Coordinates:
			std::tuple<float, float, float> coordinate=generateCoord();

			//generate Radius:
			float r=generateRadius();

			//generate Material:
			fOut
			<<"define material num"<<std::to_string(j)<<" "<<generateMat(coordinate)<< std::endl;

			fOut//WRITE SPHERE
				<<"define shape sphere num"+std::to_string(j)+" "

				+std::to_string(std::get<0>(coordinate))+" "
				+std::to_string(std::get<1>(coordinate))+" "
				+std::to_string(std::get<2>(coordinate))+" "

				+std::to_string(r)+" "

				+"num"+std::to_string(j) << std::endl;
		}
			
			//Box
		
		fOut
		<<"define material eye 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0 0.0 0 40"<<std::endl
		<<"define material nana 0.1 0.1 0.1 0.1 0.1 0.1 0.1 0.1 0.1 1 0 0 40"<<std::endl;


		fOut
			<<"define shape box nana1  -50 -50 49 50 50 50   nana" << std::endl
			<<"define shape box eye2  -3 1 -27 -2 2 -26   eye" << std::endl
			<<"define shape box eye1  2 1 -27 3 2 -26   eye" << std::endl
			<<"define shape box nana2  -50 -50 -50 50 50 -49   nana" << std::endl;
			/*
			<<"define shape box num2   7  -6  -93    17 -16  -83   mat_blue" << std::endl
			<<"define shape box num3 -29   5  -93   -19  -5  -83   red" << std::endl
			<<"define shape box num4  -5   5  -93     5  -5  -83   red" << std::endl
			<<"define shape box num5  19   5  -93    29  -5  -83   mat_lblue" << std::endl
			<<"define shape box num6  -1  -1   -1     1   1    1   mat_red" << std::endl
			<<"define shape box num7   7  16  -93    17   6  -83   mat_orange" << std::endl
			*/	
		
			//SET UP: COMPOSITE!
			fOut
			<<"define shape composite root ";
			for(int j=0;j<objects; j++)
			{
				fOut
				<<"num"+std::to_string(j)+" ";
			}
			fOut
			<<"nana1 nana2 eye1 eye2"<<std::endl;
			

			//fOut
			//<<"transform nana scale 2" << std::endl
			//<<"transform nana translate 0 0 0" << std::endl;
			//<<"transform num6 rotate " << to_string(anglex)<< " 1 1 0"<< endl

			/*
			<<"transform num14 scale "<< " 1 " << std::to_string(z) << " 1 "<< std::endl
			<<"transform num9 scale " << std::to_string(z)<< " 1 1"<< std::endl
			<<"transform num4 scale " << std::to_string(z)<< " " << std::to_string(x) <<"  1"<< std::endl
			
			
			
			
			<<"transform num1 scale 5 5 5" << std::endl 
			<<"transform num2 scale 1 1 1" << std::endl 
			<<"transform num3 scale 1 1 1" << std::endl 
			<<"transform num4 scale 1 1 1" << std::endl 
			<<"transform num5 scale 1 1 1" << std::endl 
			<<"transform num6 scale 5 5 5" << std::endl 
			<<"transform num7 scale 1 1 1" << std::endl 


			<<"transform num6 translate -10 11 -88" << std::endl 
			<<"transform num1 translate -10 -11 -88" << std::endl 
			//<<"define shape box num1 -17  -6  -93    -7 -16  -83   mat_orange" << endl
			//<<"define shape box num6 -17  16  -93    -7   6  -83   mat_red" << endl
			
			

			<<"#transform num2 translate 0 -1 0"<< std::endl
			<<"#transform num2 scale 100 0 1000"<< std::endl
			<<"#transform num3 scale " << std::to_string(z) << " 1 2" << std::endl
			*/

			//Lights
			
			fOut
			<<"define light diffuse sun1 15 5 -15 0.1 0.1 0.7" << std::endl
			<<"define light diffuse sun2 -15 -5 -15 0.0 0.7 0.1" << std::endl
			<<"define light ambient ambient 0.0 0.0 0.0" << std::endl;

			//Camera
			float posx=0+15*std::sin(2*M_PI*i/60);
			float posy=0;
			float posz=-30+15*std::cos(2*M_PI*i/60);

			float dirx=0-posx;
			float diry=0-posy;
			float dirz=-30-posz;
			fOut
			<<"define camera guck 50 "
			+std::to_string(posx)+" "+std::to_string(posy)+" "+std::to_string(posz)+" "
			+std::to_string(dirx)+" "+std::to_string(diry)+" "+std::to_string(dirz)+" 0 1 0" << std::endl;
			//<< cameraCmd << endl
		fOut.close();

	}

	return 0;
}
示例#23
0
void modCalcAzel::processLines( QTextStream &istream ) {

	// we open the output file

//	QTextStream istream(&fIn);
	QString outputFileName;
	outputFileName = OutputLineEditBatch->text();
	QFile fOut( outputFileName );
	fOut.open(IO_WriteOnly);
	QTextStream ostream(&fOut);

	QString line;
	QString space = " ";
	int i = 0;
	long double jd0, jdf;
	dms LST;
	SkyPoint sp;
	dms raB, decB, latB, longB, azB, elB;
	double epoch0B;
	QTime utB;
	ExtDate dtB;

	while ( ! istream.eof() ) {
		line = istream.readLine();
		line.stripWhiteSpace();

		//Go through the line, looking for parameters

		QStringList fields = QStringList::split( " ", line );

		i = 0;

		// Read Ut and write in ostream if corresponds
		
		if(utCheckBatch->isChecked() ) {
			utB = QTime::fromString( fields[i] );
			i++;
		} else
			utB = utBoxBatch->time();
		
		if ( allRadioBatch->isChecked() )
			ostream << utB.toString() << space;
		else
			if(utCheckBatch->isChecked() )
				ostream << utB.toString() << space;
			
		// Read date and write in ostream if corresponds
		
		if(dateCheckBatch->isChecked() ) {
			 dtB = ExtDate::fromString( fields[i] );
			 i++;
		} else
			dtB = dateBoxBatch->date();
		if ( allRadioBatch->isChecked() )
			ostream << dtB.toString().append(space);
		else
			if(dateCheckBatch->isChecked() )
			 	ostream << dtB.toString().append(space);
		
		// Read Longitude and write in ostream if corresponds
		
		if (longCheckBatch->isChecked() ) {
			longB = dms::fromString( fields[i],TRUE);
			i++;
		} else
			longB = longBoxBatch->createDms(TRUE);
		
		if ( allRadioBatch->isChecked() )
			ostream << longB.toDMSString() << space;
		else
			if (longCheckBatch->isChecked() )
				ostream << longB.toDMSString() << space;
		
		// Read Latitude


		if (latCheckBatch->isChecked() ) {
			latB = dms::fromString( fields[i], TRUE);
			i++;
		} else
			latB = latBoxBatch->createDms(TRUE);
		if ( allRadioBatch->isChecked() )
			ostream << latB.toDMSString() << space;
		else
			if (latCheckBatch->isChecked() )
				ostream << latB.toDMSString() << space;
		
		// Read Epoch and write in ostream if corresponds
	
		if(epochCheckBatch->isChecked() ) {
			epoch0B = fields[i].toDouble();
			i++;
		} else
			epoch0B = getEpoch( epochBoxBatch->text() );

		if ( allRadioBatch->isChecked() )
			ostream << epoch0B << space;
		else
			if(epochCheckBatch->isChecked() )
				ostream << epoch0B << space;

		// We make the first calculations
		KStarsDateTime dt;
		dt.setFromEpoch( epoch0B );
		jdf = KStarsDateTime(dtB,utB).djd();
		jd0 = dt.djd();

		LST = KStarsDateTime(dtB,utB).gst().Degrees() + longB.Degrees();
		
		// Equatorial coordinates are the input coords.
		if (!horInputCoords) {
		// Read RA and write in ostream if corresponds

			if(raCheckBatch->isChecked() ) {
				raB = dms::fromString( fields[i],FALSE);
				i++;
			} else
				raB = raBoxBatch->createDms(FALSE);

			if ( allRadioBatch->isChecked() )
				ostream << raB.toHMSString() << space;
			else
				if(raCheckBatch->isChecked() )
					ostream << raB.toHMSString() << space;

			// Read DEC and write in ostream if corresponds

			if(decCheckBatch->isChecked() ) {
				decB = dms::fromString( fields[i], TRUE);
				i++;
			} else
				decB = decBoxBatch->createDms();

			if ( allRadioBatch->isChecked() )
				ostream << decB.toDMSString() << space;
			else
				if(decCheckBatch->isChecked() )
					ostream << decB.toDMSString() << space;

			sp = SkyPoint (raB, decB);
			sp.apparentCoord(jd0, jdf);
			sp.EquatorialToHorizontal( &LST, &latB );
			ostream << sp.az()->toDMSString() << space << sp.alt()->toDMSString() << endl;

		// Input coords are horizontal coordinates
		
		} else {
			if(azCheckBatch->isChecked() ) {
				azB = dms::fromString( fields[i],FALSE);
				i++;
			} else
				azB = azBoxBatch->createDms();

			if ( allRadioBatch->isChecked() )
				ostream << azB.toHMSString() << space;
			else
				if(raCheckBatch->isChecked() )
					ostream << azB.toHMSString() << space;

			// Read DEC and write in ostream if corresponds

			if(elCheckBatch->isChecked() ) {
				elB = dms::fromString( fields[i], TRUE);
				i++;
			} else
				elB = decBoxBatch->createDms();

			if ( allRadioBatch->isChecked() )
				ostream << elB.toDMSString() << space;
			else
				if(elCheckBatch->isChecked() )
					ostream << elB.toDMSString() << space;

			sp.setAz(azB);
			sp.setAlt(elB);
			sp.HorizontalToEquatorial( &LST, &latB );
			ostream << sp.ra()->toHMSString() << space << sp.dec()->toDMSString() << endl;
		}

	}


	fOut.close();
}
示例#24
0
文件: refinew.cpp 项目: Wyss/mauve-py
void RefineW(const MSA &msaIn, MSA &msaOut)
	{
	const unsigned uSeqCount = msaIn.GetSeqCount();
	const unsigned uColCount = msaIn.GetColCount();

// Reserve same nr seqs, 20% more cols
	const unsigned uReserveColCount = (uColCount*120)/100;
	msaOut.SetSize(uSeqCount, uReserveColCount);

	for (unsigned uSeqIndex = 0; uSeqIndex < uSeqCount; ++uSeqIndex)
		{
		msaOut.SetSeqName(uSeqIndex, msaIn.GetSeqName(uSeqIndex));
		msaOut.SetSeqId(uSeqIndex, msaIn.GetSeqId(uSeqIndex));
		}

	const unsigned uWindowCount = (uColCount + g_uRefineWindow.get() - 1)/g_uRefineWindow.get();
	if (0 == g_uWindowTo.get())
		g_uWindowTo.get() = uWindowCount - 1;

#if	MEMDEBUG
	_CrtSetBreakAlloc(1560);
#endif

	if (g_uWindowOffset.get() > 0)
		{
		MSA msaTmp;
		MSAFromColRange(msaIn, 0, g_uWindowOffset.get(), msaOut);
		}

	if (!g_bQuiet.get())
		fprintf(stderr, "\n");
	for (unsigned uWindowIndex = g_uWindowFrom.get(); uWindowIndex <= g_uWindowTo.get(); ++uWindowIndex)
		{
		if (!g_bQuiet.get())
			fprintf(stderr, "Window %d of %d    \r", uWindowIndex, uWindowCount);
		const unsigned uColFrom = g_uWindowOffset.get() + uWindowIndex*g_uRefineWindow.get();
		unsigned uColTo = uColFrom + g_uRefineWindow.get() - 1;
		if (uColTo >= uColCount)
			uColTo = uColCount - 1;
		assert(uColTo >= uColFrom);

		SeqVect v;
		SeqVectFromMSACols(msaIn, uColFrom, uColTo, v);

#if	MEMDEBUG
		_CrtMemState s1;
		_CrtMemCheckpoint(&s1);
#endif
		// Begin AED 5/20/06
		// remove any empty seqs in this window
		std::vector< size_t > empty_seqs;
		SeqVect vr;
		for( size_t seqI = 0; seqI < v.size(); ++seqI )
		{
			if( v[seqI]->size() == 0 )
				empty_seqs.push_back(seqI);
			else
				vr.push_back(v[seqI]);
		}
		std::vector< unsigned > seqid_map( vr.size() );
		for( size_t seqI = 0; seqI < vr.size(); ++seqI )
		{
			seqid_map[seqI] = vr[seqI]->GetId();
			vr[seqI]->SetId(seqI);
		}

		MSA msaTmp;
		if( vr.size() > 1 )
			MUSCLE(vr, msaTmp);

		// remap the seqids to their original state
		for( size_t seqI = 0; seqI < vr.size(); ++seqI )
			vr[seqI]->SetId(seqid_map[seqI]);

		// merge empty seqs back in
		{
			const unsigned uSeqCount = msaOut.GetSeqCount();

			const unsigned uColCount1 = msaOut.GetColCount();
			const unsigned uColCount2 = vr.size() > 1 ? msaTmp.GetColCount() : vr[0]->size();
			const unsigned uColCountCat = uColCount1 + uColCount2;
			for( unsigned seqI = 0; seqI < vr.size(); ++seqI )
			{
				unsigned uSeqIndex = msaOut.GetSeqIndex(seqid_map[seqI]);
				if( vr.size() > 1 )
				{
					unsigned uSeqIndex2 = msaTmp.GetSeqIndex(seqI);
					for (unsigned uColIndex = 0; uColIndex < uColCount2; ++uColIndex)
					{
						const char c = msaTmp.GetChar(uSeqIndex2, uColIndex);
						msaOut.SetChar(uSeqIndex, uColCount1 + uColIndex, c);
					}
				}else{
					for (unsigned uColIndex = 0; uColIndex < uColCount2; ++uColIndex)
					{
						const char c = vr[0]->GetChar(uColIndex);
						msaOut.SetChar(uSeqIndex, uColCount1 + uColIndex, c);
					}
				}
			}
			for( unsigned seqI = 0; seqI < empty_seqs.size(); ++seqI )
			{
				unsigned uSeqId2 = v[empty_seqs[seqI]]->GetId();
				unsigned uSeqIndex = msaOut.GetSeqIndex(uSeqId2);
				for (unsigned uColIndex = 0; uColIndex < uColCount2; ++uColIndex)
				{
					msaOut.SetChar(uSeqIndex, uColCount1 + uColIndex, '-');
				}
			}
			vr.clear();
		}
//		AppendMSA(msaOut, msaTmp);
		// end AED 5/20/06

		if (uWindowIndex == g_uSaveWindow.get())
			{
			MSA msaInTmp;
			unsigned uOutCols = msaOut.GetColCount();
			unsigned un = uColTo - uColFrom + 1;
			MSAFromColRange(msaIn, uColFrom, un, msaInTmp);

			char fn[256];
			sprintf(fn, "win%d_inaln.tmp", uWindowIndex);
			TextFile fIn(fn, true);
			msaInTmp.ToFile(fIn);

			sprintf(fn, "win%d_inseqs.tmp", uWindowIndex);
			TextFile fv(fn, true);
			v.ToFile(fv);

			sprintf(fn, "win%d_outaln.tmp", uWindowIndex);
			TextFile fOut(fn, true);
			msaTmp.ToFile(fOut);
			}

#if	MEMDEBUG
		void FreeDPMemSPN();
		FreeDPMemSPN();

		_CrtMemState s2;
		_CrtMemCheckpoint(&s2);

		_CrtMemState s;
		_CrtMemDifference(&s, &s1, &s2);

		_CrtMemDumpStatistics(&s);
		_CrtMemDumpAllObjectsSince(&s1);
		exit(1);
#endif
//#if	DEBUG
//		AssertMSAEqIgnoreCaseAndGaps(msaInTmp, msaTmp);
//#endif
		}
	if (!g_bQuiet.get())
		fprintf(stderr, "\n");

//	AssertMSAEqIgnoreCaseAndGaps(msaIn, msaOut);//@@uncomment!
	}
示例#25
0
	void GameDataHolder::Impl::Flush()
	{
		if( !FileExist( "save" ) ){
			CreateDirectory( "save" );
		}

		UpdatePlayTime();

		std::vector < char > data;
		data.reserve( 30000 );

		std::ofstream fOut( m_SaveDataFileName, std::ios::binary | std::ios::out );
		if( !fOut ){
			return;
		}

		CopyInt( &data, m_GameFileData.m_PlayTime );
		CopyInt( &data, m_GameFileData.m_Progress );
		for( int i = 0; i < GAME_DIFFICULTY_TOTAL; ++i ){
			// 通常プレイの統計情報の保存
			CopyInt( &data, m_GameFileData.m_Difficulty[ i ].m_NormalPlayStat.m_Play );
			CopyInt( &data, m_GameFileData.m_Difficulty[ i ].m_NormalPlayStat.m_AllClear );
			CopyInt( &data, m_GameFileData.m_Difficulty[ i ].m_NormalPlayStat.m_PlayTime );
			CopyInt( &data, m_GameFileData.m_Difficulty[ i ].m_NormalPlayStat.m_Progress );
			for( int j = 0; j < STAGE_TOTAL; ++j ){
				// 敵情報の保存
				const StageStat& stage = m_GameFileData.m_Difficulty[ i ].m_NormalPlayStat.m_StageStat[ j ];
				StageStat::EnemyStatMap::const_iterator it = stage.m_EnemyStat.begin();
				// エントリ数の保存
				CopyInt( &data, stage.m_EnemyStat.size() );
				for( ; it != stage.m_EnemyStat.end(); ++it ){
					// 敵の名前の長さ保存
					CopyInt( &data, it->first.size() );
					// 敵の名前の保存
					CopyArray( &data, it->first.c_str(), it->first.size() );
					// 情報の保存
					CopyInt( &data, it->second.m_Destroy );
					CopyInt( &data, it->second.m_Damaged );
					CopyInt( &data, it->second.m_KO );
				}
			}

			// ステージ選択プレイの統計情報の保存
			CopyInt( &data, m_GameFileData.m_Difficulty[ i ].m_StageSelectionPlayStat.m_Play );
			CopyInt( &data, m_GameFileData.m_Difficulty[ i ].m_StageSelectionPlayStat.m_Clear );
			CopyInt( &data, m_GameFileData.m_Difficulty[ i ].m_StageSelectionPlayStat.m_PlayTime );
			for( int j = 0; j < STAGE_TOTAL; ++j ){
				// 敵情報の保存
				const StageStat& stage = m_GameFileData.m_Difficulty[ i ].m_StageSelectionPlayStat.m_StageStat[ j ];
				StageStat::EnemyStatMap::const_iterator it = stage.m_EnemyStat.begin();
				// エントリ数の保存
				CopyInt( &data, stage.m_EnemyStat.size() );
				for( ; it != stage.m_EnemyStat.end(); ++it ){
					// 敵の名前の長さ保存
					CopyInt( &data, it->first.size() );
					// 敵の名前の保存
					CopyArray( &data, it->first.c_str(), it->first.size() );
					// 情報の保存
					CopyInt( &data, it->second.m_Destroy );
					CopyInt( &data, it->second.m_Damaged );
					CopyInt( &data, it->second.m_KO );
				}
			}

			// スコアの保存
			for( int j = 0; j < MAX_SCORE_ENTRY; ++j ){
				SaveDataRecord record = m_GameFileData.m_Difficulty[ i ].m_Record[ j ];
				CopyArray( &data, record.m_Name, sizeof( record.m_Name ) );
				CopyInt( &data, record.m_Date.m_Year );
				data.push_back( record.m_Date.m_Month );
				data.push_back( record.m_Date.m_Day );
				data.push_back( record.m_Date.m_Hour );
				data.push_back( record.m_Date.m_Min );
				data.push_back( record.m_Date.m_Sec );
				for( int k = 0; k < STAGE_TOTAL; ++k ){
					SaveDataRecord::StageData stage = record.m_StageData[ k ];
					CopyInt( &data, stage.m_Score );
					CopyInt( &data, stage.m_Killed );
					CopyInt( &data, stage.m_Crystal );
					CopyInt( &data, stage.m_CrystalUsed );
					CopyInt( &data, stage.m_Progress );
				}
				CopyInt( &data, record.m_Score );
				CopyInt( &data, record.m_Progress );
				CopyInt( &data, record.m_Killed );
				CopyInt( &data, record.m_Crystal );
				CopyInt( &data, record.m_CrystalUsed );
			}
		}

		// 圧縮
		char* pBuf = new char [ data.size() * 2 ];
		int compSize = 0;
		MAPIL::LZ lz( 200, 3 );
		lz.Compress( &data[ 0 ], data.size(), &pBuf, data.size() * 2, &compSize );
		// シーザ暗号化
		MAPIL::Caesar caesar( 10 );
		caesar.Encrypt( pBuf, compSize );
		// XOR暗号化
		MAPIL::XOR xor( 60 );
		xor.Encrypt( pBuf, compSize );
		fOut.write( pBuf, compSize );
		fOut.close();
		MAPIL::SafeDeleteArray( pBuf );
	}
示例#26
0
文件: subfam.cpp 项目: Wyss/mauve-py
void ProgAlignSubFams()
	{
	MSA msaOut;

	SetOutputFileName(g_pstrOutFileName.get());
	SetInputFileName(g_pstrInFileName.get());

	SetMaxIters(g_uMaxIters.get());
	SetSeqWeightMethod(g_SeqWeight1.get());

	TextFile fileIn(g_pstrInFileName.get());
	SeqVect v;
	v.FromFASTAFile(fileIn);
	const unsigned uSeqCount = v.Length();

	if (0 == uSeqCount)
		Quit("No sequences in input file");

	ALPHA Alpha = ALPHA_Undefined;
	switch (g_SeqType.get())
		{
	case SEQTYPE_Auto:
		Alpha = v.GuessAlpha();
		break;

	case SEQTYPE_Protein:
		Alpha = ALPHA_Amino;
		break;

	case SEQTYPE_DNA:
		Alpha = ALPHA_DNA;
		break;

	case SEQTYPE_RNA:
		Alpha = ALPHA_RNA;
		break;

	default:
		Quit("Invalid seq type");
		}
	SetAlpha(Alpha);
	v.FixAlpha();

	PTR_SCOREMATRIX UserMatrix = 0;
	if (0 != g_pstrMatrixFileName.get())
		{
		const char *FileName = g_pstrMatrixFileName.get();
		const char *Path = getenv("MUSCLE_MXPATH");
		if (Path != 0)
			{
			size_t n = strlen(Path) + 1 + strlen(FileName) + 1;
			char *NewFileName = new char[n];
			sprintf(NewFileName, "%s/%s", Path, FileName);
			FileName = NewFileName;
			}
		TextFile File(FileName);
		UserMatrix = ReadMx(File);
		g_Alpha = ALPHA_Amino;
		g_PPScore = PPSCORE_SP;
		}

	SetPPScore();

	if (0 != UserMatrix)
		g_ptrScoreMatrix = UserMatrix;

	if (ALPHA_DNA == Alpha || ALPHA_RNA == Alpha)
		{
		SetPPScore(PPSCORE_SPN);
		g_Distance1.get() = DISTANCE_Kmer4_6;
		}

	unsigned uMaxL = 0;
	unsigned uTotL = 0;
	for (unsigned uSeqIndex = 0; uSeqIndex < uSeqCount; ++uSeqIndex)
		{
		unsigned L = v.GetSeq(uSeqIndex).Length();
		uTotL += L;
		if (L > uMaxL)
			uMaxL = L;
		}

	SetIter(1);
	g_bDiags.get() = g_bDiags1.get();
	SetSeqStats(uSeqCount, uMaxL, uTotL/uSeqCount);

	SetMuscleSeqVect(v);

	MSA::SetIdCount(uSeqCount);

// Initialize sequence ids.
// From this point on, ids must somehow propogate from here.
	for (unsigned uSeqIndex = 0; uSeqIndex < uSeqCount; ++uSeqIndex)
		v.SetSeqId(uSeqIndex, uSeqIndex);

	if (uSeqCount > 1)
		MHackStart(v);

	if (0 == uSeqCount)
		{
		msaOut.Clear();
		return;
		}

	if (1 == uSeqCount && ALPHA_Amino == Alpha)
		{
		const Seq &s = v.GetSeq(0);
		msaOut.FromSeq(s);
		return;
		}

	Tree GuideTree;
	TreeFromSeqVect(v, GuideTree, g_Cluster1.get(), g_Distance1.get(), g_Root1.get());
	SetMuscleTree(GuideTree);

	MSA msa;
	if (g_bLow.get())
		{
		ProgNode *ProgNodes = 0;
		ProgNodes = ProgressiveAlignE(v, GuideTree, msa);
		delete[] ProgNodes;
		}
	else
		ProgressiveAlign(v, GuideTree, msa);
	SetCurrentAlignment(msa);
	TreeFromMSA(msa, GuideTree, g_Cluster2.get(), g_Distance2.get(), g_Root2.get());
	SetMuscleTree(GuideTree);

	unsigned *SubFams = new unsigned[uSeqCount];
	unsigned uSubFamCount;
	SubFam(GuideTree, g_uMaxSubFamCount.get(), SubFams, &uSubFamCount);

	SetProgressDesc("Align node");
	const unsigned uNodeCount = 2*uSeqCount - 1;

	ProgNode *ProgNodes = new ProgNode[uNodeCount];
	bool *NodeIsSubFam = new bool[uNodeCount];
	bool *NodeInSubFam = new bool[uNodeCount];

	for (unsigned i = 0; i < uNodeCount; ++i)
		{
		NodeIsSubFam[i] = false;
		NodeInSubFam[i] = false;
		}

	for (unsigned i = 0; i < uSubFamCount; ++i)
		{
		unsigned uNodeIndex = SubFams[i];
		assert(uNodeIndex < uNodeCount);
		NodeIsSubFam[uNodeIndex] = true;
		SetInFam(GuideTree, uNodeIndex, NodeInSubFam);
		}

	unsigned uJoin = 0;
	unsigned uTreeNodeIndex = GuideTree.FirstDepthFirstNode();
	do
		{
		if (NodeIsSubFam[uTreeNodeIndex])
			{
#if	TRACE
			Log("Node %d: align subfam\n", uTreeNodeIndex);
#endif
			ProgNode &Node = ProgNodes[uTreeNodeIndex];
			AlignSubFam(v, GuideTree, uTreeNodeIndex, Node.m_MSA);
			Node.m_uLength = Node.m_MSA.GetColCount();
			}
		else if (!NodeInSubFam[uTreeNodeIndex])
			{
#if	TRACE
			Log("Node %d: align two subfams\n", uTreeNodeIndex);
#endif
			Progress(uJoin, uSubFamCount - 1);
			++uJoin;

			const unsigned uMergeNodeIndex = uTreeNodeIndex;
			ProgNode &Parent = ProgNodes[uMergeNodeIndex];

			const unsigned uLeft = GuideTree.GetLeft(uTreeNodeIndex);
			const unsigned uRight = GuideTree.GetRight(uTreeNodeIndex);

			ProgNode &Node1 = ProgNodes[uLeft];
			ProgNode &Node2 = ProgNodes[uRight];

			PWPath Path;
			AlignTwoMSAs(Node1.m_MSA, Node2.m_MSA, Parent.m_MSA, Path);
			Parent.m_uLength = Parent.m_MSA.GetColCount();

			Node1.m_MSA.Clear();
			Node2.m_MSA.Clear();
			}
		else
			{
#if	TRACE
			Log("Node %d: in subfam\n", uTreeNodeIndex);
#endif
			;
			}
		uTreeNodeIndex = GuideTree.NextDepthFirstNode(uTreeNodeIndex);
		}
	while (NULL_NEIGHBOR != uTreeNodeIndex);
	ProgressStepsDone();

	unsigned uRootNodeIndex = GuideTree.GetRootNodeIndex();
	ProgNode &RootProgNode = ProgNodes[uRootNodeIndex];

	TextFile fOut(g_pstrOutFileName.get(), true);
	MHackEnd(RootProgNode.m_MSA);
	RootProgNode.m_MSA.ToFile(fOut);

	delete[] NodeInSubFam;
	delete[] NodeIsSubFam;
	delete[] ProgNodes;
	delete[] SubFams;

	ProgNodes = 0;
	NodeInSubFam = 0;
	NodeIsSubFam = 0;
	SubFams = 0;
	}
示例#27
0
//void modCalcAngDist::processLines( const QFile * fIn ) {
void modCalcAngDist::processLines( QTextStream &istream ) {

	// we open the output file

//	QTextStream istream(&fIn);
	QString outputFileName;
	outputFileName = OutputLineEditBatch->text();
	QFile fOut( outputFileName );
	fOut.open(IO_WriteOnly);
	QTextStream ostream(&fOut);

	QString line;
	QString space = " ";
	int i = 0;
	SkyPoint sp0, sp1;
	dms ra0B, dec0B, ra1B, dec1B, dist;

	while ( ! istream.eof() ) {
		line = istream.readLine();
		line.stripWhiteSpace();

		//Go through the line, looking for parameters

		QStringList fields = QStringList::split( " ", line );

		i = 0;

		// Read RA and write in ostream if corresponds

		if(ra0CheckBatch->isChecked() ) {
			ra0B = dms::fromString( fields[i],FALSE);
			i++;
		} else
			ra0B = ra0BoxBatch->createDms(FALSE);

		if ( allRadioBatch->isChecked() )
			ostream << ra0B.toHMSString() << space;
		else
			if(ra0CheckBatch->isChecked() )
				ostream << ra0B.toHMSString() << space;

		// Read DEC and write in ostream if corresponds

		if(dec0CheckBatch->isChecked() ) {
			dec0B = dms::fromString( fields[i], TRUE);
			i++;
		} else
			dec0B = dec0BoxBatch->createDms();

		if ( allRadioBatch->isChecked() )
			ostream << dec0B.toDMSString() << space;
		else
			if(dec0CheckBatch->isChecked() )
				ostream << dec0B.toDMSString() << space;
		
		// Read RA and write in ostream if corresponds

		if(ra1CheckBatch->isChecked() ) {
			ra1B = dms::fromString( fields[i],FALSE);
			i++;
		} else
			ra1B = ra1BoxBatch->createDms(FALSE);

		if ( allRadioBatch->isChecked() )
			ostream << ra1B.toHMSString() << space;
		else
			if(ra1CheckBatch->isChecked() )
				ostream << ra1B.toHMSString() << space;

		// Read DEC and write in ostream if corresponds

		if(dec1CheckBatch->isChecked() ) {
			dec1B = dms::fromString( fields[i], TRUE);
			i++;
		} else
			dec1B = dec1BoxBatch->createDms();

		if ( allRadioBatch->isChecked() )
			ostream << dec1B.toDMSString() << space;
		else
			if(dec1CheckBatch->isChecked() )
				ostream << dec1B.toDMSString() << space;

		sp0 = SkyPoint (ra0B, dec0B);
		sp1 = SkyPoint (ra1B, dec1B);
		dist = sp0.angularDistanceTo(&sp1);

		ostream << dist.toDMSString() << endl;
	}

	fOut.close();
}
void modCalcJD::processLines( QTextStream &istream, int inputData ) {
    QFile fOut( OutputFileBatch->url().toLocalFile() );
    fOut.open(QIODevice::WriteOnly);
    QTextStream ostream(&fOut);

    QString line;
    long double jd(0);
    double mjd(0);
    KStarsDateTime dt;

    while ( ! istream.atEnd() ) {
        line = istream.readLine();
        line = line.trimmed();
        QStringList data = line.split( ' ', QString::SkipEmptyParts );

        if ( inputData == 0 ) { //Parse date & time
            //Is the first field parseable as a date or date&time?
            if ( data[0].length() > 10 )
                dt = KStarsDateTime::fromString( data[0] );
            else
                dt = KStarsDateTime( QDate::fromString( data[0] ), QTime(0,0,0) );

            //DEBUG
            kDebug() << data[0];
            if ( dt.isValid() ) kDebug() << dt.toString();

            if ( dt.isValid() ) {
                //Try to parse the second field as a time
                if ( data.size() > 1 ) {
                    QString s = data[1];
                    if ( s.length() == 4 ) s = '0'+s;
                    QTime t = QTime::fromString( s );
                    if ( t.isValid() ) dt.setTime( t );
                }

            } else { //Did not parse the first field as a date; try it as a time
                QTime t = QTime::fromString( data[0] );
                if ( t.isValid() ) {
                    dt.setTime( t );
                    //Now try the second field as a date
                    if ( data.size() > 1 ) {
                        QDate d = QDate::fromString( data[1] );
                        if ( d.isValid() ) dt.setDate( d );
                        else dt.setDate( QDate::currentDate() );
                    }
                }
            }

            if ( dt.isValid() ) {
                //Compute JD and MJD
                jd = dt.djd();
                mjd = jd - MJD0;
            }

        } else if ( inputData == 1 ) {//Parse Julian day
            bool ok(false);
            jd = data[0].toDouble(&ok);
            if ( ok ) {
                dt.setDJD( jd );
                mjd = jd - MJD0;
            }
        } else if ( inputData == 2 ) {//Parse Modified Julian day
            bool ok(false);
            mjd = data[0].toDouble(&ok);
            if ( ok ) {
                jd = mjd + MJD0;
                dt.setDJD( jd );
            }
        }

        //Write to output file
        ostream << KGlobal::locale()->formatDateTime( dt, KLocale::LongDate ) << "  "
                << QString::number( jd, 'f', 2 ) << "  "
                << QString::number( mjd, 'f', 2 ) << endl;

    }

    fOut.close();
}
示例#29
0
void modCalcGalCoord::processLines( QTextStream &istream ) {

    // we open the output file

    //	QTextStream istream(&fIn);
    const QString outputFileName = OutputFileBoxBatch->url().toLocalFile();
    QFile fOut( outputFileName );
    fOut.open(QIODevice::WriteOnly);
    QTextStream ostream(&fOut);

    QString line;
    QChar space = ' ';
    int i = 0;
    SkyPoint sp;
    dms raB, decB, galLatB, galLongB;
    QString epoch0B;

    while ( ! istream.atEnd() ) {
        line = istream.readLine();
        line.trimmed();

        //Go through the line, looking for parameters

        QStringList fields = line.split( ' ' );

        i = 0;

        // Input coords are galactic coordinates:

        if (galInputCoords) {

            // Read Galactic Longitude and write in ostream if corresponds

            if(galLongCheckBatch->isChecked() ) {
                galLongB = dms::fromString( fields[i], true);
                i++;
            } else
                galLongB = galLongBoxBatch->createDms(true);

            if ( allRadioBatch->isChecked() )
                ostream << galLongB.toDMSString() << space;
            else
                if(galLongCheckBatch->isChecked() )
                    ostream << galLongB.toDMSString() << space;

            // Read Galactic Latitude and write in ostream if corresponds

            if(galLatCheckBatch->isChecked() ) {
                galLatB = dms::fromString( fields[i], true);
                i++;
            } else
                galLatB = galLatBoxBatch->createDms(true);

            if ( allRadioBatch->isChecked() )
                ostream << galLatB.toDMSString() << space;
            else
                if(galLatCheckBatch->isChecked() )
                    ostream << galLatB.toDMSString() << space;

            sp = SkyPoint ();
            sp.GalacticToEquatorial1950(&galLongB, &galLatB);
            ostream << sp.ra().toHMSString() << space << sp.dec().toDMSString() << epoch0B << endl;
            // Input coords. are equatorial coordinates:

        } else {

            // Read RA and write in ostream if corresponds

            if(raCheckBatch->isChecked() ) {
                raB = dms::fromString( fields[i],false);
                i++;
            } else
                raB = raBoxBatch->createDms(false);

            if ( allRadioBatch->isChecked() )
                ostream << raB.toHMSString() << space;
            else
                if(raCheckBatch->isChecked() )
                    ostream << raB.toHMSString() << space;

            // Read DEC and write in ostream if corresponds

            if(decCheckBatch->isChecked() ) {
                decB = dms::fromString( fields[i], true);
                i++;
            } else
                decB = decBoxBatch->createDms();

            if ( allRadioBatch->isChecked() )
                ostream << decB.toDMSString() << space;
            else
                if(decCheckBatch->isChecked() )
                    ostream << decB.toDMSString() << space;

            // Read Epoch and write in ostream if corresponds

            if(epochCheckBatch->isChecked() ) {
                epoch0B = fields[i];
                i++;
            } else
                epoch0B = epochBoxBatch->text();

            if ( allRadioBatch->isChecked() )
                ostream << epoch0B << space;
            else
                if(epochCheckBatch->isChecked() )
                    ostream << epoch0B << space;

            sp = SkyPoint (raB, decB);
            sp.J2000ToB1950();
            sp.Equatorial1950ToGalactic(galLongB, galLatB);
            ostream << galLongB.toDMSString() << space << galLatB.toDMSString() << endl;

        }

    }


    fOut.close();
}