MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent), ui(new Ui::MainWindow) { ui->setupUi(this); ping = new QProcess(); iperf = new QProcess(); timer = new QTimer(); timer->setSingleShot(true); numTests = 0; ui->udpBandwidthField->hide(); connect(ping,SIGNAL(readyReadStandardOutput()),this,SLOT(readPingOutput())); connect(iperf,SIGNAL(readyReadStandardOutput()),this,SLOT(readIperfOutput())); connect(ping,SIGNAL(readyReadStandardError()),this,SLOT(readError())); connect(iperf,SIGNAL(readyReadStandardError()),this,SLOT(readError())); connect(ping,SIGNAL(started()),this,SLOT(processStarted())); connect(iperf,SIGNAL(started()),this,SLOT(processStarted())); connect(ping,SIGNAL(finished(int,QProcess::ExitStatus)),this,SLOT(pingFinished(int,QProcess::ExitStatus))); connect(iperf,SIGNAL(finished(int,QProcess::ExitStatus)),this,SLOT(iperfFinished(int,QProcess::ExitStatus))); connect(ping,SIGNAL(error(QProcess::ProcessError)),this,SLOT(error(QProcess::ProcessError))); connect(iperf,SIGNAL(error(QProcess::ProcessError)),this,SLOT(error(QProcess::ProcessError))); connect(timer,SIGNAL(timeout()),this,SLOT(startPing())); initPlot(); }
bool KviPackageReader::unpackInternal(const QString & szLocalFileName, const QString & szUnpackPath, kvi_u32_t uUnpackFlags) { KviFile f(szLocalFileName); if(!f.open(QFile::ReadOnly)) { setLastError(__tr2qs("Can't open file for reading")); return false; } kvi_file_offset_t size = f.size(); if(!(uUnpackFlags & NoProgressDialog)) { showProgressDialog(__tr2qs("Reading package..."), size); updateProgress(0, __tr2qs("Reading package header")); } if(!readHeaderInternal(&f, szLocalFileName)) return false; if(!updateProgress(f.pos(), __tr2qs("Reading package data"))) return false; // aborted while(!f.atEnd()) { // DataFieldType kvi_u32_t uDataFieldType; if(!f.load(uDataFieldType)) return readError(); // DataFieldLen kvi_u32_t uDataFieldLen; if(!f.load(uDataFieldLen)) return readError(); switch(uDataFieldType) { case KVI_PACKAGE_DATAFIELD_TYPE_FILE: if(!unpackFile(&f, szUnpackPath)) return false; break; default: setLastError(__tr2qs("Invalid data field: the package is probably corrupt")); return false; break; } } return true; }
/** * Calls readData() in a loop until commanded to disconnect and possibly * shut down the thread. */ void CUXInterface::runServiceLoop() { ReadResult res = ReadResult_NoStatement; bool connected = c14cux_isConnected(&m_cuxinfo); while (!m_stopPolling && !m_shutdownThread && connected) { res = readData(); if (res == ReadResult_Success) { emit readSuccess(); emit dataReady(); } else if (res == ReadResult_Failure) { emit readError(); } QCoreApplication::processEvents(); } if (connected) { c14cux_disconnect(&m_cuxinfo); } emit disconnected(); clearFlagsAndData(); if (m_shutdownThread) { QThread::currentThread()->quit(); } }
static Boln readRlePixel (Tcl_Interp *interp, tkimg_MFile *handle, UByte **pixBufPtr, Int *countPtr, Int stop, Int n, TGAFILE *tf) { Int i, count, nchan; UByte localBuf[4]; nchan = NCHAN(tf->th.pixsize); if (nchan != tkimg_Read (handle, (char *)localBuf, nchan)) return readError (interp); count = *countPtr; for (i=0; i<n; i++) { #if defined (DEBUG_LOCAL) tf->total++; #endif (*pixBufPtr)[0] = localBuf[2]; (*pixBufPtr)[1] = localBuf[1]; (*pixBufPtr)[2] = localBuf[0]; if (nchan == 4) (*pixBufPtr)[3] = localBuf[3]; (*pixBufPtr) += nchan; count++; if (count == stop) { /* Scanline is filled with pixel values. Determine the number of pixels to keep for next scanline. */ tf->scanrest = n - i - 1; *countPtr = count; return TRUE; } } *countPtr = count; return TRUE; }
void CardReader::disconnect() { errorCode = 0; if (connected) { errorCode = ::CloseCardReader(); errorString = readError(); connected = false; } }
Graph readGraph(FILE *in) { Graph g; char line[100]; // get #vertices and create graph int nV = 0; if (fgets(line,100,in) == NULL) readError(); if (sscanf(line,"%d",&nV) != 1) readError(); if (nV < 2) readError(); g = newGraph(nV); // read edge data and add edges Vertex v, w; while (fgets(line,100,in) != NULL) { sscanf(line,"%d-%d",&v,&w); insertE(g, mkEdge(g,v,w)); } return g; }
void KVirtual::startVirtual() { uint id = getID(); KVirtualProcess * process = new KVirtualProcess( id, KVirtualProcess::HOST ); QStringList vswitch; QString buffer; process->setProgram( Settings::kvm_exe(), m_options->getArgs() ); process->setOutputChannelMode( KProcess::SeparateChannels ); connect( process, SIGNAL( readyReadStandardOutput( uint ) ), SLOT( readData( uint ) ) ); connect( process, SIGNAL( readyReadStandardError( uint ) ), SLOT( readError( uint ) ) ); connect( process, SIGNAL( finished( uint, int, QProcess::ExitStatus ) ), SLOT( closeProcess( uint, int, QProcess::ExitStatus ) ) ); connect( process, SIGNAL( started( uint ) ), SLOT( readStarted( uint ) ) ); vswitch = m_options->getNeededVirtualSwitch(); for ( QStringList::Iterator it = vswitch.begin() ; it != vswitch.end() ; ++it ) { m_view->addOutput( "Need a virtual switch: " + *it ); startVde( *it ); } m_view->addOutput( process->program().join( " " ) ); process->start(); m_processes[id] = process; if ( process->error() == QProcess::FailedToStart || process->state() == QProcess::NotRunning ) { buffer.setNum( id ); buffer.prepend( "Process" ); buffer.append( " failed to start" ); m_view->addError( buffer ); QString img = KStandardDirs::locate( "appdata", m_options->getDistrib() + ".png" ); QPixmap pixmap; pixmap.load( img ); KNotification *notification= new KNotification ( "startFailed", this ); notification->setText( i18n( "The virtual host <i>%1</i> is not started", m_options->getName() ) ); notification->setPixmap( pixmap ); notification->sendEvent(); } }
void CardReader::connect() { errorCode = 0; if (!connected) { errorCode = ::OpenCardReader(0, 2, 115200); errorString = readError(); errorString += ""; // RtlWerpReportException without connected = (0 == errorCode); } }
void MjpegPlayer::start(const QString &complete_url) { m_connStatus = Stream::Playing; m_finishedConnection = false; m_reply = m_manager->get(QNetworkRequest(QUrl(complete_url))); connect( m_reply, SIGNAL(readyRead()), this, SLOT(readImg()) ); connect( m_reply, SIGNAL(error(QNetworkReply::NetworkError)), this, SLOT(readError(QNetworkReply::NetworkError)) ); connect( m_reply, SIGNAL(finished()), this, SLOT(finishedConnection()) ); }
void MjpegPlayer::stop() { m_connStatus = Stream::Stopped; m_finishedConnection = true; if (m_reply) { disconnect( m_reply, SIGNAL(readyRead()), this, SLOT(readImg()) ); disconnect( m_reply, SIGNAL(error(QNetworkReply::NetworkError)), this, SLOT(readError(QNetworkReply::NetworkError)) ); disconnect( m_reply, SIGNAL(finished()), this, SLOT(finishedConnection()) ); } }
void ManagerConnection::read() { QString cmd = in.readLine(); if (cmd == "SESSIONS") readSessions(); else if (cmd == "ERROR") readError(); else if (cmd == "GET PASSWORD") askForPassword(false); else if (cmd == "GET CREDENTIALS") askForPassword(true); }
void TagReader::targetLost(QNearFieldTarget *target) { mDebug(__func__) << "Lost target (R). "; if (target == m_target) { disconnect(target, SIGNAL(ndefMessageRead(const QNdefMessage &)), this, SLOT(targetRead(const QNdefMessage &))); disconnect(target, SIGNAL(error(QNearFieldTarget::Error, QNearFieldTarget::RequestId)), this, SLOT(readError(QNearFieldTarget::Error, QNearFieldTarget::RequestId))); m_target = NULL; }
void KVirtual::startVde( const QString & vswitch ) { uint id = getID(); KVirtualProcess * process = new KVirtualProcess( id, KVirtualProcess::SWITCH ); QStringList args; QDir dir( vswitch ); QString buffer; if ( dir.exists() ) { m_view->addError( "Virtual switch is already exists but is not handled by me" ); return; } args << "-F" << "-sock" << vswitch; process->setProgram( Settings::vde_switch_exe(), args ); process->setOutputChannelMode( KProcess::SeparateChannels ); process->setDataDir( vswitch ); connect( process, SIGNAL( readyReadStandardOutput( uint ) ), SLOT( readData( uint ) ) ); connect( process, SIGNAL( readyReadStandardError( uint ) ), SLOT( readError( uint ) ) ); connect( process, SIGNAL( finished( uint, int, QProcess::ExitStatus ) ), SLOT( closeProcess( uint, int, QProcess::ExitStatus ) ) ); connect( process, SIGNAL( started( uint ) ), SLOT( readStarted( uint ) ) ); m_view->addOutput( process->program().join( " " ) ); process->start(); m_processes[id] = process; if ( process->error() == QProcess::FailedToStart || process->state() == QProcess::NotRunning ) { buffer.setNum( id ); buffer.prepend( "Process" ); buffer.append( " failed to start" ); m_view->addError( buffer ); } }
Person CardReader::read() { errorCode = 10000; if (connected) { wchar_t path[256]; personImagePath().toWCharArray(path); PERSONINFOW p; errorCode = ::GetPersonMsgW(&p, path); errorString = readError(); return Person(p); } return Person(); }
RedisProto::ParseState RedisProto::parse(char *s, int len, RedisProtoParseResult *result) { int ret = 0; switch (s[0]) { case '+': result->type = RedisProtoParseResult::Status; ret = readStatus(s, len, &(result->tokens[0])); break; case '-': result->type = RedisProtoParseResult::Error; ret = readError(s, len, &(result->tokens[0])); break; case ':': result->type = RedisProtoParseResult::Integer; ret = readInteger(s, len, &result->integer); break; case '$': result->type = RedisProtoParseResult::Bulk; ret = readBulk(s, len, &(result->tokens[0])); break; case '*': result->type = RedisProtoParseResult::MultiBulk; ret = readMultiBulk(s, len, result->tokens, &result->tokenCount); break; default: { int stringlen = 0; result->type = RedisProtoParseResult::Bulk; ret = readTextEndByCRLF(s, len, &stringlen); if (ret > 0) { result->tokens[0].s = s; result->tokens[0].len = stringlen; } } break; } switch (ret) { case READ_AGAIN: return ProtoIncomplete; case READ_ERROR: return ProtoError; default: result->protoBuff = s; result->protoBuffLen = ret; return ProtoOK; } }
/** reads the next non-empty non-comment line of a cnf file */ static SCIP_RETCODE readCnfLine( SCIP* scip, /**< SCIP data structure */ SCIP_FILE* file, /**< input file */ char* buffer, /**< buffer for storing the input line */ int size, /**< size of the buffer */ int* linecount /**< pointer to the line number counter */ ) { char* line; int linelen; assert(file != NULL); assert(buffer != NULL); assert(size >= 2); assert(linecount != NULL); do { (*linecount)++; line = SCIPfgets(buffer, size, file); if( line != NULL ) { linelen = (int)strlen(line); if( linelen == size-1 ) { char s[SCIP_MAXSTRLEN]; (void) SCIPsnprintf(s, SCIP_MAXSTRLEN, "line too long (exceeds %d characters)", size-2); readError(scip, *linecount, s); return SCIP_READERROR; } } else linelen = 0; } while( line != NULL && (*line == 'c' || *line == '\n') ); if( line != NULL && linelen >= 2 && line[linelen-2] == '\n' ) line[linelen-2] = '\0'; else if( linelen == 0 ) *buffer = '\0'; assert((line == NULL) == (*buffer == '\0')); return SCIP_OKAY; }
void FlickrPrivate::readErrorElement() { while(!_xmlStreamReader.atEnd()) { _xmlStreamReader.readNext(); if(_xmlStreamReader.isEndElement()) { break; } if(_xmlStreamReader.isStartElement()) { if(_xmlStreamReader.name() == "err") { readError(); } else { readUnknownElement(); } } } }
bool Terminal::initialize() { context->parentContext()->setContextProperty("Terminal",this); process=new QProcess(this); process->setProgram("bash"); process->setArguments(QStringList() << "-i" << "-s"); process->setWorkingDirectory(QDir::homePath()); //QStringList l=process->systemEnvironment(); //user=l.at(l.indexOf(QRegExp("^USER=.+"))); //user=user.mid(user.indexOf("=")+1); //process->setReadChannelMode(QProcess::MergedChannels); connect(process,SIGNAL(started()),this,SLOT(started())); connect(process,SIGNAL(finished(int,QProcess::ExitStatus)),this,SLOT(finished(int,QProcess::ExitStatus))); connect(process,SIGNAL(readyReadStandardOutput()),this,SLOT(readOutput())); connect(process,SIGNAL(readyReadStandardError()),this,SLOT(readError())); user="******"; return true; }
void TagReader::targetDetected(QNearFieldTarget *target) { mDebug(__func__) << "Saw target (R). "; m_target = target; if (m_started == false) { mDebug(__func__) << "Ignoring read target, for now. "; return; /* Not now dear */ } connect(target, SIGNAL(ndefMessageRead(const QNdefMessage &)), this, SLOT(targetRead(const QNdefMessage &))); connect(target, SIGNAL(error(QNearFieldTarget::Error, QNearFieldTarget::RequestId)), this, SLOT(readError(QNearFieldTarget::Error, QNearFieldTarget::RequestId))); m_target->readNdefMessages(); }
void KVirtual::createVDisk( const QString & file, const QString & type, const QString & size ) { uint id = getID(); KVirtualProcess * process = new KVirtualProcess( id, KVirtualProcess::CREATE_IMG ); QStringList opts; QString buffer; opts << "create"; opts << "-f" << type; opts << file; opts << size; process->setProgram( Settings::qemu_img_creator_exe(), opts ); process->setOutputChannelMode( KProcess::SeparateChannels ); connect( process, SIGNAL( readyReadStandardOutput( uint ) ), SLOT( readData( uint ) ) ); connect( process, SIGNAL( readyReadStandardError( uint ) ), SLOT( readError( uint ) ) ); connect( process, SIGNAL( finished( uint, int, QProcess::ExitStatus ) ), SLOT( closeProcess( uint, int, QProcess::ExitStatus ) ) ); connect( process, SIGNAL( started( uint ) ), SLOT( readStarted( uint ) ) ); m_view->addOutput( process->program().join( " " ) ); process->start(); m_processes[id] = process; if ( process->error() == QProcess::FailedToStart || process->state() == QProcess::NotRunning ) { buffer.setNum( id ); buffer.prepend( "Process" ); buffer.append( " failed to start" ); m_view->addError( buffer ); } }
void recurse(QXmlStreamReader & reader, QXmlStreamWriter & writer, char const * const path, Paths && ... paths) { std::size_t mud = 0u; while (!reader.atEnd()) { switch (reader.readNext()) { case QXmlStreamReader::Invalid: readError(reader); case QXmlStreamReader::StartElement: if (mud) { ++mud; PASS; } else if (reader.qualifiedName() == path) { PASS; recurse(reader, writer, paths...); } else { ++mud; PASS; } break; case QXmlStreamReader::EndElement: if (mud) { --mud; PASS; } else { PASS; return; } break; default: PASS; break; }; } }
int main(int argc, char const *argv[]) { if (2 != argc) { return printUsage(); } int depth; int scanned = sscanf(argv[1], "%d", &depth); if (EOF == scanned) { return readError(); } if (depth > 0) { pid_t parent = getpid(); Tree * procTree = mkTree(depth, parent); if (getpid() == parent) { printTree(procTree); } } return 0; }
/* Read SAT formula in "CNF File Format". * * The specification is taken from the * * Satisfiability Suggested Format * * Online available at http://www.intellektik.informatik.tu-darmstadt.de/SATLIB/Benchmarks/SAT/satformat.ps * * The method reads all files of CNF format. Other formats (SAT, SATX, SATE) are not supported. */ static SCIP_RETCODE readCnf( SCIP* scip, /**< SCIP data structure */ SCIP_FILE* file /**< input file */ ) { SCIP_RETCODE retcode; SCIP_VAR** vars; SCIP_VAR** clausevars; SCIP_CONS* cons; int* varsign; char* tok; char* nexttok; char line[MAXLINELEN]; char format[SCIP_MAXSTRLEN]; char varname[SCIP_MAXSTRLEN]; char s[SCIP_MAXSTRLEN]; SCIP_Bool dynamicconss; SCIP_Bool dynamiccols; SCIP_Bool dynamicrows; SCIP_Bool useobj; int linecount; int clauselen; int clausenum; int nvars; int nclauses; int varnum; int v; assert(scip != NULL); assert(file != NULL); retcode = SCIP_OKAY; linecount = 0; /* read header */ SCIP_CALL( readCnfLine(scip, file, line, (int) sizeof(line), &linecount) ); if( *line != 'p' ) { readError(scip, linecount, "problem declaration line expected"); return SCIP_READERROR; } if( sscanf(line, "p %8s %d %d", format, &nvars, &nclauses) != 3 ) { readError(scip, linecount, "invalid problem declaration (must be 'p cnf <nvars> <nclauses>')"); return SCIP_READERROR; } if( strcmp(format, "cnf") != 0 ) { (void) SCIPsnprintf(s, SCIP_MAXSTRLEN, "invalid format tag <%s> (must be 'cnf')", format); readError(scip, linecount, s); return SCIP_READERROR; } if( nvars <= 0 ) { (void) SCIPsnprintf(s, SCIP_MAXSTRLEN, "invalid number of variables <%d> (must be positive)", nvars); readError(scip, linecount, s); return SCIP_READERROR; } if( nclauses <= 0 ) { (void) SCIPsnprintf(s, SCIP_MAXSTRLEN, "invalid number of clauses <%d> (must be positive)", nclauses); readError(scip, linecount, s); return SCIP_READERROR; } /* get parameter values */ SCIP_CALL( SCIPgetBoolParam(scip, "reading/cnfreader/dynamicconss", &dynamicconss) ); SCIP_CALL( SCIPgetBoolParam(scip, "reading/cnfreader/dynamiccols", &dynamiccols) ); SCIP_CALL( SCIPgetBoolParam(scip, "reading/cnfreader/dynamicrows", &dynamicrows) ); SCIP_CALL( SCIPgetBoolParam(scip, "reading/cnfreader/useobj", &useobj) ); /* get temporary memory */ SCIP_CALL( SCIPallocBufferArray(scip, &vars, nvars) ); SCIP_CALL( SCIPallocBufferArray(scip, &clausevars, nvars) ); SCIP_CALL( SCIPallocBufferArray(scip, &varsign, nvars) ); /* create the variables */ for( v = 0; v < nvars; ++v ) { (void) SCIPsnprintf(varname, SCIP_MAXSTRLEN, "x%d", v+1); SCIP_CALL( SCIPcreateVar(scip, &vars[v], varname, 0.0, 1.0, 0.0, SCIP_VARTYPE_BINARY, !dynamiccols, dynamiccols, NULL, NULL, NULL, NULL, NULL) ); SCIP_CALL( SCIPaddVar(scip, vars[v]) ); varsign[v] = 0; } /* read clauses */ clausenum = 0; clauselen = 0; do { retcode = readCnfLine(scip, file, line, (int) sizeof(line), &linecount); if( retcode != SCIP_OKAY ) goto TERMINATE; if( *line != '\0' && *line != '%' ) { tok = SCIPstrtok(line, " \f\n\r\t", &nexttok); while( tok != NULL ) { /* parse literal and check for errors */ if( sscanf(tok, "%d", &v) != 1 ) { (void) SCIPsnprintf(s, SCIP_MAXSTRLEN, "invalid literal <%s>", tok); readError(scip, linecount, s); retcode = SCIP_READERROR; goto TERMINATE; } /* interpret literal number: v == 0: end of clause, v < 0: negated literal, v > 0: positive literal */ if( v == 0 ) { /* end of clause: construct clause and add it to SCIP */ if( clauselen == 0 ) readWarning(scip, linecount, "empty clause detected in line -- problem infeasible"); clausenum++; (void) SCIPsnprintf(s, SCIP_MAXSTRLEN, "c%d", clausenum); if( SCIPfindConshdlr(scip, "logicor") != NULL ) { /* if the constraint handler logicor exit create a logicor constraint */ SCIP_CALL( SCIPcreateConsLogicor(scip, &cons, s, clauselen, clausevars, !dynamicrows, TRUE, TRUE, TRUE, TRUE, FALSE, FALSE, dynamicconss, dynamicrows, FALSE) ); } else if( SCIPfindConshdlr(scip, "setppc") != NULL ) { /* if the constraint handler logicor does not exit but constraint * handler setppc create a setppc constraint */ SCIP_CALL( SCIPcreateConsSetcover(scip, &cons, s, clauselen, clausevars, !dynamicrows, TRUE, TRUE, TRUE, TRUE, FALSE, FALSE, dynamicconss, dynamicrows, FALSE) ); } else { /* if none of the previous constraint handler exits create a linear * constraint */ SCIP_Real* vals; int i; SCIP_CALL( SCIPallocBufferArray(scip, &vals, clauselen) ); for( i = 0; i < clauselen; ++i ) vals[i] = 1.0; SCIP_CALL( SCIPcreateConsLinear(scip, &cons, s, clauselen, clausevars, vals, 1.0, SCIPinfinity(scip), !dynamicrows, TRUE, TRUE, TRUE, TRUE, FALSE, FALSE, dynamicconss, dynamicrows, FALSE) ); SCIPfreeBufferArray(scip, &vals); } SCIP_CALL( SCIPaddCons(scip, cons) ); SCIP_CALL( SCIPreleaseCons(scip, &cons) ); clauselen = 0; } else if( v >= -nvars && v <= nvars ) { if( clauselen >= nvars ) { readError(scip, linecount, "too many literals in clause"); retcode = SCIP_READERROR; goto TERMINATE; } /* add literal to clause */ varnum = ABS(v)-1; if( v < 0 ) { SCIP_CALL( SCIPgetNegatedVar(scip, vars[varnum], &clausevars[clauselen]) ); varsign[varnum]--; } else { clausevars[clauselen] = vars[varnum]; varsign[varnum]++; } clauselen++; } else { (void) SCIPsnprintf(s, SCIP_MAXSTRLEN, "invalid variable number <%d>", ABS(v)); readError(scip, linecount, s); retcode = SCIP_READERROR; goto TERMINATE; } /* get next token */ tok = SCIPstrtok(NULL, " \f\n\r\t", &nexttok); } } } while( *line != '\0' && *line != '%' ); /* check for additional literals */ if( clauselen > 0 ) { SCIPwarningMessage(scip, "found %d additional literals after last clause\n", clauselen); } /* check number of clauses */ if( clausenum != nclauses ) { SCIPwarningMessage(scip, "expected %d clauses, but found %d\n", nclauses, clausenum); } TERMINATE: /* change objective values and release variables */ SCIP_CALL( SCIPsetObjsense(scip, SCIP_OBJSENSE_MAXIMIZE) ); if( useobj ) { for( v = 0; v < nvars; ++v ) { SCIP_CALL( SCIPchgVarObj(scip, vars[v], (SCIP_Real)varsign[v]) ); SCIP_CALL( SCIPreleaseVar(scip, &vars[v]) ); } } /* free temporary memory */ SCIPfreeBufferArray(scip, &varsign); SCIPfreeBufferArray(scip, &clausevars); SCIPfreeBufferArray(scip, &vars); return retcode; }
bool KviPackageReader::unpackFile(KviFile * pFile, const QString & szUnpackPath) { // Flags kvi_u32_t uFlags; if(!pFile->load(uFlags)) return readError(); #ifndef COMPILE_ZLIB_SUPPORT if(uFlags & KVI_PACKAGE_DATAFIELD_FLAG_FILE_DEFLATE) { setLastError(__tr2qs("The package contains compressed data but this executable does not support compression")); return false; } #endif // Path QString szPath; if(!pFile->load(szPath)) return readError(); QString szFileName = szUnpackPath; KviQString::ensureLastCharIs(szFileName, QChar(KVI_PATH_SEPARATOR_CHAR)); szFileName += szPath; // no attacks please :) szFileName.replace(QString("..\\"), QString("")); szFileName.replace(QString("../"), QString("")); KviFileUtils::adjustFilePath(szFileName); int idx = szFileName.lastIndexOf(QChar(KVI_PATH_SEPARATOR_CHAR)); if(idx != -1) { QString szPrefixPath = szFileName.left(idx); if(!KviFileUtils::makeDir(szPrefixPath)) { setLastError(__tr2qs("Failed to create the target directory")); return false; } } KviFile dest(szFileName); if(!dest.open(QFile::WriteOnly | QFile::Truncate)) { setLastError(__tr2qs("Failed to open a source file for reading")); return false; } QString szProgressText = QString(__tr2qs("Unpacking file %1")).arg(szFileName); if(!updateProgress(pFile->pos(), szProgressText)) return false; // aborted // Size kvi_u32_t uSize; if(!pFile->load(uSize)) return readError(); // FilePayload #ifdef COMPILE_ZLIB_SUPPORT if(uFlags & KVI_PACKAGE_DATAFIELD_FLAG_FILE_DEFLATE) { //qDebug ("loading compressed data"); int iRemainingSize = uSize; unsigned char ibuffer[BUFFER_SIZE]; unsigned char obuffer[BUFFER_SIZE]; int iToRead = iRemainingSize; if(iToRead > BUFFER_SIZE) iToRead = BUFFER_SIZE; int iReaded = pFile->read((char *)ibuffer, iToRead); iRemainingSize -= iReaded; z_stream zstr; zstr.zalloc = Z_NULL; zstr.zfree = Z_NULL; zstr.opaque = Z_NULL; zstr.next_in = ibuffer; zstr.avail_in = iReaded; zstr.next_out = obuffer; zstr.avail_out = BUFFER_SIZE; if(inflateInit(&zstr) != Z_OK) { setLastError(__tr2qs("Compression library initialization error")); return false; } while((iReaded > 0) && (iRemainingSize > 0)) { zstr.next_out = obuffer; zstr.avail_out = BUFFER_SIZE; if(inflate(&zstr, Z_NO_FLUSH) != Z_OK) { setLastError(__tr2qs("Compression library error")); return false; } if(zstr.avail_out < BUFFER_SIZE) { int iDecompressed = zstr.next_out - obuffer; if(dest.write((char *)obuffer, iDecompressed) != iDecompressed) { inflateEnd(&zstr); return writeError(); } } if(zstr.avail_in < BUFFER_SIZE) { int iDataToRead = BUFFER_SIZE - zstr.avail_in; if(iDataToRead < BUFFER_SIZE) { if(ibuffer != zstr.next_in) { // hum, there is still some data in the buffer to be readed // and it is not at the beginning...move it to the beginning of ibuffer memmove(ibuffer, zstr.next_in, zstr.avail_in); } } if(iDataToRead > iRemainingSize) iDataToRead = iRemainingSize; iReaded = pFile->read((char *)(ibuffer + zstr.avail_in), iDataToRead); if(iReaded < 0) { inflateEnd(&zstr); return readError(); } iRemainingSize -= iReaded; zstr.avail_in += iReaded; zstr.next_in = ibuffer; if((zstr.total_in % 2000000) == 0) { QString szTmp = QString(" (%1 of %2 bytes)").arg(zstr.total_in, uSize); QString szPrg = szProgressText + szTmp; if(!updateProgress(pFile->pos(), szPrg)) return false; // aborted } } } // flush pending output zstr.next_out = obuffer; zstr.avail_out = BUFFER_SIZE; int ret; do { ret = inflate(&zstr, Z_FINISH); if((ret == Z_OK) || (ret == Z_STREAM_END) || (ret == Z_BUF_ERROR)) { if(zstr.avail_out < BUFFER_SIZE) { int iDecompressed = zstr.next_out - obuffer; if(dest.write((char *)obuffer, iDecompressed) != iDecompressed) { inflateEnd(&zstr); return writeError(); } } else { //THIS HAPPENS FOR ZERO SIZE FILES qDebug("Hum... internal, rEWq (ret = %d) (avail_out = %d)", ret, zstr.avail_out); inflateEnd(&zstr); setLastError(__tr2qs("Compression library internal error")); return false; } zstr.next_out = obuffer; zstr.avail_out = BUFFER_SIZE; } } while((ret == Z_OK) || (ret == Z_BUF_ERROR)); inflateEnd(&zstr); if(ret != Z_STREAM_END) { setLastError(__tr2qs("Error in compressed file stream")); return false; } } else { #endif //qDebug("Load uncompressed data"); unsigned char buffer[BUFFER_SIZE]; int iTotalFileSize = 0; int iRemainingData = uSize; int iToRead = iRemainingData; if(iToRead > BUFFER_SIZE) iToRead = BUFFER_SIZE; int iReaded = 1; //qDebug("iReaded %i and iToRead %i and index %i",iReaded,iToRead,pFile->pos()); while((iReaded > 0) && (iToRead > 0)) { iReaded = pFile->read((char *)buffer, iToRead); if(iReaded > 0) { iTotalFileSize += iReaded; iRemainingData -= iReaded; if((iTotalFileSize % 3000000) == 0) { QString szTmp = QString(" (%1 of %2 bytes)").arg(iTotalFileSize).arg(uSize); QString szPrg = szProgressText + szTmp; if(!updateProgress(pFile->pos(), szPrg)) return false; // aborted } //qDebug("write file with size %i and name %s",iReaded,dest.fileName().toUtf8().data()); if(dest.write((char *)buffer, iReaded) != iReaded) return writeError(); } //qDebug("Remains %i", iRemainingData); iToRead = iRemainingData; if(iToRead > BUFFER_SIZE) iToRead = BUFFER_SIZE; } //qDebug("finish to read %i and index %i",iReaded,pFile->pos()); #ifdef COMPILE_ZLIB_SUPPORT } #endif dest.close(); return true; }
static Boln tgaReadScan (Tcl_Interp *interp, tkimg_MFile *handle, TGAFILE *tf, Int y) { Int nchan; Int count, stop; UByte localBuf[4]; UByte *pixBufPtr; count = 0; stop = tf->th.xsize; nchan = NCHAN(tf->th.pixsize); pixBufPtr = tf->pixbuf; #if defined (DEBUG_LOCAL) tf->total = 0; #endif if (IS_COMPRESSED (tf->th.imgtyp)) { Byte cbuf[1]; Int pix, numpix; /* While there are pixels left from the previous scanline, either fill the current scanline with the pixel value still stored in "pixbuf" (TGA_MODE_SAME) or read in the appropriate number of pixel values (TGA_MODE_DIFF). */ while (tf->scanrest) { if (tf->scanmode == TGA_MODE_DIFF) { if (nchan != tkimg_Read (handle, (char *)localBuf, nchan)) return readError (interp); } #if defined (DEBUG_LOCAL) tf->total++; #endif *pixBufPtr++ = localBuf[2]; *pixBufPtr++ = localBuf[1]; *pixBufPtr++ = localBuf[0]; if (nchan == 4) *pixBufPtr++ = localBuf[3]; count++; tf->scanrest--; /* If the image is small, the compression might go over several scanlines. */ if (count == stop) return TRUE; } /* Read the byte telling us the compression mode and the compression count. Then read the pixel values till a scanline is filled. */ do { if (1 != tkimg_Read (handle, cbuf, 1)) return readError (interp); numpix = (cbuf[0] & 0x7F) + 1; if ((cbuf[0] & 0x80) != 0x80) { tf->scanmode = TGA_MODE_DIFF; for (pix=0; pix<numpix; pix++) { if (!readRlePixel (interp, handle, &pixBufPtr, &count, stop, 1, tf)) return FALSE; if (count == stop) { tf->scanrest = numpix - pix - 1; break; } } } else { tf->scanmode = TGA_MODE_SAME; if (!readRlePixel (interp, handle, &pixBufPtr, &count, stop, numpix, tf)) return FALSE; } } while (count < stop); #if defined (DEBUG_LOCAL) printf ("\tScanline %d: Pixels: %d Rest: %d\n", y, tf->total, tf->scanrest); #endif } else { /* Read uncompressed pixel data. */ Int i, bytesPerLine; UByte curPix; bytesPerLine = nchan * tf->th.xsize; if (bytesPerLine != tkimg_Read (handle, (char *)tf->pixbuf, bytesPerLine)) return readError (interp); for (i=0; i<stop; i++) { curPix = pixBufPtr[2]; pixBufPtr[2] = pixBufPtr[0]; pixBufPtr[0] = curPix; pixBufPtr += nchan; } } return TRUE; }
bool KviPackageReader::readHeaderInternal(KviFile * pFile, const QString &) { // read the PackageHeader // Magic char magic[4]; if(pFile->read(magic, 4) != 4) return readError(); if((magic[0] != 'K') || (magic[1] != 'V') || (magic[2] != 'P') || (magic[3] != 'F')) { setLastError(__tr2qs("The file specified is not a valid KVIrc package")); return false; } // Version kvi_u32_t uVersion; if(!pFile->load(uVersion)) return readError(); if(uVersion != 0x1) { setLastError(__tr2qs("The package has an invalid version number, it might have been created by a newer KVIrc")); return false; } // Flags kvi_u32_t uFlags; if(!pFile->load(uFlags)) return readError(); // we ignore them at the moment // read PackageInfo // InfoFieldCount kvi_u32_t uCount; if(!pFile->load(uCount)) return writeError(); stringInfoFields()->clear(); binaryInfoFields()->clear(); kvi_u32_t uIdx = 0; while(uIdx < uCount) { QString szKey; if(!pFile->load(szKey)) return readError(); kvi_u32_t uFieldType; if(!pFile->load(uFieldType)) return readError(); switch(uFieldType) { case KVI_PACKAGE_INFOFIELD_TYPE_STRING: { QString szValue; if(!pFile->load(szValue)) return readError(); stringInfoFields()->replace(szKey, new QString(szValue)); } break; case KVI_PACKAGE_INFOFIELD_TYPE_BINARYBUFFER: { QByteArray * pbValue = new QByteArray(); if(!pFile->load(*pbValue)) { delete pbValue; return readError(); } binaryInfoFields()->replace(szKey, pbValue); } break; default: setLastError(__tr2qs("Invalid info field: the package is probably corrupt")); break; } uIdx++; } return true; }
bool KviPackageWriter::packFile(KviFile * pFile, KviPackageWriterDataField * pDataField) { QString szProgressText = QString(__tr2qs("Packaging file %1")).arg(pDataField->m_szFileLocalName); if(!updateProgress(m_p->iCurrentProgress, szProgressText)) return false; // aborted KviFile source(pDataField->m_szFileLocalName); if(!source.open(QFile::ReadOnly)) { setLastError(__tr2qs("Failed to open a source file for reading")); return false; } kvi_u32_t uSize = source.size(); // Flags #ifdef COMPILE_ZLIB_SUPPORT kvi_u32_t uFlags = pDataField->m_bFileAllowCompression ? (uSize > 64 ? KVI_PACKAGE_DATAFIELD_FLAG_FILE_DEFLATE : 0) : 0; #else kvi_u32_t uFlags = 0; #endif if(!pFile->save(uFlags)) return writeError(); QByteArray szTargetFileName = pDataField->m_szFileTargetName.toUtf8(); // Path if(!pFile->save(szTargetFileName)) return writeError(); kvi_file_offset_t savedSizeOffset = pFile->pos(); // Size : will update it if compression is requested if(!pFile->save(uSize)) return writeError(); pDataField->m_uWrittenFieldLength = 4 + 4 + 4 + szTargetFileName.length(); // sizeof(flags + uncompressed size + path len + path) // FilePayload #ifdef COMPILE_ZLIB_SUPPORT if(uFlags & KVI_PACKAGE_DATAFIELD_FLAG_FILE_DEFLATE) { unsigned char ibuffer[BUFFER_SIZE]; unsigned char obuffer[BUFFER_SIZE]; kvi_i32_t iReaded = source.read((char *)ibuffer, BUFFER_SIZE); if(iReaded < 0) return readError(); z_stream zstr; zstr.zalloc = Z_NULL; zstr.zfree = Z_NULL; zstr.opaque = Z_NULL; zstr.next_in = ibuffer; zstr.avail_in = iReaded; zstr.next_out = obuffer; zstr.avail_out = BUFFER_SIZE; if(deflateInit(&zstr, 9) != Z_OK) { setLastError(__tr2qs("Compression library initialization error")); return false; } while(iReaded > 0) { zstr.next_out = obuffer; zstr.avail_out = BUFFER_SIZE; if(deflate(&zstr, Z_NO_FLUSH) != Z_OK) { setLastError(__tr2qs("Compression library error")); return false; } if(zstr.avail_out < BUFFER_SIZE) { int iCompressed = zstr.next_out - obuffer; pDataField->m_uWrittenFieldLength += iCompressed; if(pFile->write((char *)obuffer, iCompressed) != iCompressed) { deflateEnd(&zstr); return writeError(); } } if(zstr.avail_in < BUFFER_SIZE) { int iDataToRead = BUFFER_SIZE - zstr.avail_in; if(iDataToRead < BUFFER_SIZE) { if(ibuffer != zstr.next_in) { // hum, there is still some data in the buffer to be readed // and it is not at the beginning...move it to the beginning of ibuffer memmove(ibuffer, zstr.next_in, zstr.avail_in); } } iReaded = source.read((char *)(ibuffer + zstr.avail_in), iDataToRead); if(iReaded < 0) { deflateEnd(&zstr); return readError(); } zstr.avail_in += iReaded; zstr.next_in = ibuffer; if((zstr.total_in % 2000000) == 0) { QString szTmp = QString(" (%1 of %2 bytes)").arg(zstr.total_in, uSize); QString szPrg = szProgressText + szTmp; if(!updateProgress(m_p->iCurrentProgress, szPrg)) return false; // aborted } } } // flush pending output zstr.next_out = obuffer; zstr.avail_out = BUFFER_SIZE; int ret; do { ret = deflate(&zstr, Z_FINISH); if((ret == Z_OK) || (ret == Z_STREAM_END)) { if(zstr.avail_out < BUFFER_SIZE) { int iCompressed = zstr.next_out - obuffer; pDataField->m_uWrittenFieldLength += iCompressed; if(pFile->write((char *)obuffer, iCompressed) != iCompressed) { deflateEnd(&zstr); return writeError(); } } else { deflateEnd(&zstr); setLastError(__tr2qs("Compression library internal error")); return false; } zstr.next_out = obuffer; zstr.avail_out = BUFFER_SIZE; } } while(ret == Z_OK); // store the compressed data size kvi_file_offset_t here = pFile->pos(); pFile->seek(savedSizeOffset); uSize = zstr.total_out; deflateEnd(&zstr); if(!pFile->save(uSize)) return writeError(); if(ret != Z_STREAM_END) { setLastError(__tr2qs("Error while compressing a file stream")); return false; } pFile->seek(here); } else { #endif unsigned char buffer[BUFFER_SIZE]; int iTotalFileSize = 0; kvi_i32_t iReaded = source.read((char *)buffer, BUFFER_SIZE); if(iReaded < 0) return readError(); while(iReaded > 0) { iTotalFileSize += iReaded; if((iTotalFileSize % 1000000) == 0) { QString szTmp = QString(" (%1 of %2 bytes)").arg(iTotalFileSize, uSize); QString szPrg = szProgressText + szTmp; if(!updateProgress(m_p->iCurrentProgress, szPrg)) return false; // aborted } pDataField->m_uWrittenFieldLength += iReaded; if(pFile->write((char *)buffer, iReaded) != iReaded) return writeError(); iReaded = source.read((char *)buffer, BUFFER_SIZE); } #ifdef COMPILE_ZLIB_SUPPORT } #endif source.close(); return true; }
void recurse(QXmlStreamReader & reader, QXmlStreamWriter & writer) { std::size_t mud = 0u; QString locationFilename; unsigned long long locationLine = 0u; QString source; while (!reader.atEnd()) { switch (reader.readNext()) { case QXmlStreamReader::Invalid: readError(reader); case QXmlStreamReader::StartElement: if (mud) { ++mud; PASS; } else { if (reader.qualifiedName() == "location") { auto const attrs(reader.attributes()); locationFilename = attrs.value("filename").toString(); locationLine = attrs.value("line").toULongLong(); ++mud; PASS; } else if (reader.qualifiedName() == "source") { PASS; QString source(reader.readElementText()); if (source.contains(hasPotentialUnicodeEscape)) { QString const oldSource(source); if (!checkUnicodeEscape(source, locationFilename, locationLine)) { std::cerr << inFilename << ": \"" << source.toStdString() << "\" (" << locationFilename.toStdString() << ':' << locationLine << ") not substituted!" << std::endl; assert(oldSource == source); } else { std::cerr << inFilename << ": \"" << oldSource.toStdString() << "\" -> \"" << source.toStdString() << "\" (" << locationFilename.toStdString() << ':' << locationLine << ") substituted." << std::endl; assert(oldSource != source); } } writer.writeCharacters(source); writer.writeEndElement(); } else { ++mud; PASS; } } break; case QXmlStreamReader::EndElement: if (mud) { --mud; PASS; break; } else { PASS; return; } default: PASS; break; }; } }
void Spectrum::initialize(sampleSizes s, PaSampleFormat b, int nr, QString dir) { nrig = nr; userDirectory = dir; sizes = s; sizeIQ = sizes.sample_length / 8; // 512 IQ phase/gain bins // initialize FFTW #ifdef Q_OS_WIN if (!fftwWinInit()) { return; } if (in) (fftw_freep) (in); if (out) (fftw_freep) (out); if (errfunc) (fftw_freep) (errfunc); if (plan) (fftw_destroy_planp) (plan); in = (fftw_complex *) (fftw_mallocp) (sizeof(fftw_complex) * sizes.sample_length); out = (fftw_complex *) (fftw_mallocp) (sizeof(fftw_complex) * sizes.sample_length); errfunc = (fftw_complex *) (fftw_mallocp) (sizeof(fftw_complex) * sizes.sample_length); plan = (fftw_plan_dft_1dp) (sizes.sample_length, in, out, FFTW_FORWARD, FFTW_MEASURE); #else if (in) fftw_free(in); if (out) fftw_free(out); if (errfunc) fftw_free(errfunc); if (plan) fftw_destroy_plan(plan); in = (fftw_complex *) fftw_malloc(sizeof(fftw_complex) * sizes.sample_length); out = (fftw_complex *) fftw_malloc(sizeof(fftw_complex) * sizes.sample_length); errfunc = (fftw_complex *) fftw_malloc(sizeof(fftw_complex) * sizes.sample_length); plan = fftw_plan_dft_1d(sizes.sample_length, in, out, FFTW_FORWARD, FFTW_MEASURE); #endif switch (b) { case paInt16: bits = 16; break; case paInt24: bits = 24; break; case paInt32: bits = 32; break; default: bits = 16; } if (output) delete [] output; output = new unsigned char[sizes.display_length]; for (int i = 0; i < SIG_N_AVG; i++) { if (peakAvg[i]) delete [] peakAvg[i]; peakAvg[i] = new double[sizes.spec_length]; } if (spec_smooth) delete [] spec_smooth; spec_smooth = new double[sizes.sample_length]; if (spec_tmp) delete [] spec_tmp; spec_tmp = new double[sizes.sample_length]; if (spec_tmp2) delete [] spec_tmp2; spec_tmp2 = new double[sizes.sample_length]; for (int i = 0; i < sizes.sample_length; i++) { spec_tmp[i] = 0.; spec_smooth[i] = 0.; spec_tmp2[i] = 0.; } if (tmp4) delete [] tmp4; tmp4 = new double[sizes.spec_length]; if (window) delete [] window; window = new double[sizes.sample_length]; makeWindow(); for (int i = 0; i < sizes.spec_length; i++) { tmp4[i] = 0.; } if (sigOnCnt) delete [] sigOnCnt; sigOnCnt = new int[sizes.sample_length]; if (sigOn) delete [] sigOn; sigOn = new bool[sizes.sample_length]; for (int i = 0; i < sizes.sample_length; i++) { sigOnCnt[i] = 2; sigOn[i] = false; } if (calibSigList) delete [] calibSigList; calibSigList = new CalibSignal[sizeIQ]; for (int i = 0; i < FIT_ORDER; i++) { aGain[i] = 0.; aPhase[i] = 0.; } addOffset=0; // intialize to unit gain and zero phase aGain[0] = 1.0; makeGainPhase(); readError(); calcError(true); }
likeClass::likeClass(const char *outfiles,argStruct *arguments,int inputtype){ postfix = ".glf.gz"; beaglepostfix = ".beagle.gz"; trim =0; GL=0; doGlf=0; errorFname = NULL; errorProbs = NULL; GL=0; minQ = MINQ;//<- general.h minInd=0; angsd_tmpdir = strdup("angsd_tmpdir"); if(arguments->argc==2){ if(!strcmp(arguments->argv[1],"-GL")){ printArg(stdout); exit(0); }else return; } getOptions(arguments); printArg(arguments->argumentFile); // if(GL==0) // return; if(GL==1) bam_likes_init(); else if(GL==2) gatk_init(); else if(GL==3){ soap.init(arguments->nInd,angsd_tmpdir); if(soap.doRecal) fprintf(stderr,"[%s] Will calculate recalibration matrices, please don't do any other analysis\n",__FILE__); else fprintf(stderr,"[%s] Will use precalculated calibration matrices\n",__FILE__); }else if(GL==4) { //default errormatrix double errorsDefault[4][4]={{0 ,0.00031 , 0.00373 , 0.000664}, {0.000737, 0 , 0.000576, 0.001702}, {0.001825,0.000386, 0 , 0.000653}, {0.00066 ,0.003648, 0.000321, 0 }, }; //allocate and plug in default values errors = new double *[4]; for(int i=0;i<4;i++){ errors[i] = new double[4]; for(int j=0;j<4;j++) errors[i][j] = errorsDefault[i][j]; } if(errorFname!=NULL) readError(errors,errorFname); errorProbs = error::generateErrorPointers(errors,3,4); } gzoutfile = Z_NULL; bufstr.s=NULL; bufstr.l=bufstr.m=0;// <- used for buffered output bufstr.l=0; if(doGlf){ if(doGlf!=2) gzoutfile = openFileGz(outfiles,postfix,GZOPT); else{ gzoutfile = openFileGz(outfiles,beaglepostfix,GZOPT); kputs("marker\tallele1\tallele2",&bufstr); for(int i=0;i<arguments->nInd;i++){ kputs("\tInd",&bufstr); kputw(i,&bufstr); kputs("\tInd",&bufstr); kputw(i,&bufstr); kputs("\tInd",&bufstr); kputw(i,&bufstr); } kputc('\n',&bufstr); gzwrite(gzoutfile,bufstr.s,bufstr.l); } } }