void LoadSegmentsGauge (CFile& cf) { loadOp = 0; loadIdx = 0; mineDataFile = &cf; ProgressBar (TXT_PREP_DESCENT, 0, LoadMineGaugeSize () + PagingGaugeSize () + SortLightsGaugeSize (), LoadSegmentsPoll); }
Wt::WWidget *FormWidgets::progressBar() { Wt::WTemplate *result = new TopicTemplate("forms-progressBar"); result->bindWidget("ProgressBar", ProgressBar()); return result; }
void GenericSolver::buildInteractionMatrix(ReactiveSet& R) { if(verbose) printf("Building interaction matrix for %i DF...\n", R.nDF()); ProgressBar pb = ProgressBar(R.nDF(),1,verbose); #ifdef WITH_LAPACKE the_ixn = mmat(R.nDF(),R.nDF()); #else the_GF = gsl_matrix_alloc(R.nDF(),R.nDF()); #endif R.startInteractionScan(); for(unsigned int DF=0; DF<R.nDF(); DF++) { R.setInteractionDF(DF,1.0); for(unsigned int phi=0; phi<R.nPhi; phi++) { mvec v = R.getReactionTo(&R,phi); assert(v.size() == R.nDF()/R.nPhi); for(unsigned int i=0; i<v.size(); i++) #ifdef WITH_LAPACKE the_ixn(i*R.nPhi+phi, DF) = v[i]; #else gsl_matrix_set(the_GF, i*R.nPhi+phi, DF, (i*R.nPhi+phi==DF) ? 1-v[i] : -v[i]); #endif } pb.update(DF); } R.setInteractionDF(R.nDF(),0); }
Ag* avaliaFitnessPop(Matriz *Treino, Matriz *Teste, Ag *Pop, int classificador){ int i=0; //printf("%sA avaliar Fitness da Populacao [0%s", bold, none); for(i=0;i<Pop->linhas;i++){ if(classificador==1 || classificador==0)//KNN classificador por defeito Pop->matriz[i][21]=Knn(Treino,Teste,Pop->matriz[i]); if(classificador==2) Pop->matriz[i][21]=NaiveBayes(Teste,Treino, Pop->matriz[i]); ProgressBar(" A avaliar Fitness da Populacao",i+1,Pop->linhas); } //printf("%s]%s\n", bold, none); return Pop; }
int CLightmapManager::Create (int nLevel) { if (!(gameStates.render.bUsePerPixelLighting)) return 0; if ((gameStates.render.bUsePerPixelLighting == 1) && !CreateLightmapShader (0)) return gameStates.render.bUsePerPixelLighting = 0; #if !DBG if (gameOpts->render.nLightmapQuality > 3) gameOpts->render.nLightmapQuality = 3; #endif Destroy (); int nLights = Init (0); if (nLights < 0) return 0; if (Load (nLevel)) return 1; if (gameStates.render.bPerPixelLighting && gameData.segs.nFaces) { if (nLights) { lightManager.Transform (1, 0); int nSaturation = gameOpts->render.color.nSaturation; gameOpts->render.color.nSaturation = 1; gameStates.render.bHaveLightmaps = 1; //gameData.render.fAttScale [0] = 2.0f; lightManager.Index (0)[0].nFirst = MAX_SHADER_LIGHTS; lightManager.Index (0)[0].nLast = 0; if (gameStates.app.bProgressBars && gameOpts->menus.nStyle) { nFace = 0; ProgressBar (TXT_CALC_LIGHTMAPS, 0, PROGRESS_STEPS (gameData.segs.nFaces), CreatePoll); } else { messageBox.Show (TXT_CALC_LIGHTMAPS); BuildAll (-1); messageBox.Clear (); } //gameData.render.fAttScale [0] = (gameStates.render.bPerPixelLighting == 2) ? 1.0f : 2.0f; gameStates.render.bHaveLightmaps = 0; gameStates.render.nState = 0; gameOpts->render.color.nSaturation = nSaturation; Realloc ((m_list.nLightmaps + LIGHTMAP_BUFSIZE - 1) / LIGHTMAP_BUFSIZE); } else { CreateSpecial (m_data.texColor, 0, 0); m_list.nLightmaps = 1; for (int i = 0; i < gameData.segs.nFaces; i++) FACES.faces [i].nLightmap = 0; } BindAll (); Save (nLevel); } return 1; }
void LoadLevelTextures (void) { nBitmaps = 0; if (gameStates.app.bProgressBars && gameOpts->menus.nStyle) { int i = LoadMineGaugeSize (); nTouchSeg = 0; nTouchWall = 0; nTouchWeapon = 0; nTouchPowerup1 = 0; nTouchPowerup2 = 0; nTouchGauge = 0; ProgressBar (TXT_PREP_DESCENT, i, i + PagingGaugeSize () + SortLightsGaugeSize (), LoadTexturesPoll); } else LoadAllTextures (); }
int main(int argc , char *argv[]){ gtk_init(&argc,&argv); vbox = gtk_vbox_new(FALSE,2); CreateWindow(); Buttons(); ConnectNodes = gtk_label_new("No Torrent Selected"); gtk_box_pack_start(GTK_BOX(vbox),HorizontalPanel(),FALSE,TRUE,2); gtk_box_pack_start(GTK_BOX(vbox),ConnectNodes,FALSE,TRUE,2); gtk_box_pack_start(GTK_BOX(vbox),ProgressBar(),FALSE,TRUE,2); gtk_container_add(GTK_CONTAINER(window), vbox); gtk_widget_show_all(window); gtk_widget_hide(progress); gtk_main(); return 0; }
void SymmetricSolver::buildInteractionMatrix(ReactiveSet& R) { if(verbose) printf("Building interaction matrix for %i = %i x %i DF...\n", R.nDF(), R.nDF()/R.nPhi, R.nPhi); ProgressBar pb = ProgressBar(R.nDF(), R.nPhi, verbose); the_ixn = BlockCMat(R.nDF()/R.nPhi, R.nDF()/R.nPhi, CMatrix(R.nPhi)); R.startInteractionScan(); for(unsigned int DF=0; DF<R.nDF(); DF++) { R.setInteractionDF(DF,1.0); mvec v = R.getReactionTo(&R); assert(v.size() == R.nDF()/R.nPhi); for(unsigned int i=0; i<v.size(); i++) the_ixn(i, DF/R.nPhi)[DF%R.nPhi] = v[i]; pb.update(DF); } R.setInteractionDF(R.nDF(),0); }
static int WriteFile_ToHDD(char *NameF, char *msg) //Запись файла на HDD рекордера { DWORD nb; if(OpenInFilePC(NameF) < 0) return -1; //Открыли входной файл для чтения с компьютера DWORD wSizeB = sCl_B; //Число байт чтения равно числу байт в кластере LONGLONG SizeToEnd = Size_inF.QuadPart; //Число байт которые осталось записать DWORD numCl = DWORD((Size_inF.QuadPart + sCl_B - 1) / sCl_B);//Число кластеров необходимое для размещения файла данного размера if(numCl > maxZapFAT1 - 1 - writeCl) return MaloMesta(numCl); //"Запись невозможна, на HDD LG нет свободного места."}, if(numCl > 0) InitProgressBar(numCl, msg); DWORD n, nCl = 1; //Номер последнего записанного кластера for(DWORD i=0; i<numCl; i++) //По числу кластеров { for(n=nCl+1; n<maxZapFAT1; n++) //Просмотр FAT для поиска первого свободного кластера if(*(c_FAT1 + n) == 0) break; if(n >= maxZapFAT1) return Error1((Lan+190)->msg); //"Запись невозможна, на HDD LG нет свободного места."}, if(wSizeB > SizeToEnd) { wSizeB = DWORD(SizeToEnd); //Размер остатка чтения меньше размера кластера ZeroMemory(bufIO, sCl_B); } if(ReadFile(inFile, bufIO, wSizeB, &nb, NULL) == false || nb != wSizeB) return ErrorSys1((Lan+87)->msg); //"Ошибка при чтении файла." #if !defined EMULATOR_HDD //НЕТ Режима эмулятора if(WriteClast1P(n, bufIO) < 0) return -1; //Запись кластера #endif if(nCl > 1) *(c_FAT1 + nCl) = n; //Ссылка на следубщий кластер в цепочке кластеров else nCl_1 = n; //Номер кластера начала файла nCl = n; //Последний записанный кластер SizeToEnd -= wSizeB; //Число байт которые осталось прочитать if(ProgressBar(wSizeB) < 0) return -1; //Оператор нажал кнопку Прервать } *(c_FAT1 + nCl) = 0x0FFFFFFF; //Признак конца цепочки CloseFile(&inFile); writeNewCl += numCl; //Число записанных кластеров return Change_Dir_For_File(NameF); //Изменение каталога (запись нового файла) }
int main(int argc, char **argv) { int i, j, k, treeNo, sumLength; char ch; TTree **treeSet; FILE *text_fv; clock_t totalStart; double totalSecs, scale, sum; char *ancestor; totalStart = clock(); ReadParams(argc, argv); if (rateHetero == CodonRates && invariableSites) { fprintf(stderr, "Invariable sites model cannot be used with codon rate heterogeneity.\n"); exit(4); } if (writeAncestors && fileFormat == NEXUSFormat) { fprintf(stderr, "Warning - When writing ancestral sequences, relaxed PHYLIP format is used.\n"); } if (writeAncestors && maxPartitions > 1) { fprintf(stderr, "Writing ancestral sequences can only be used for a single partition.\n"); exit(4); } if (!userSeed) randomSeed = CreateSeed(); SetSeed(randomSeed); if (!quiet) PrintTitle(); numTrees = OpenTreeFile(); /* if (!treeFile) { */ ReadFileParams(); /*} */ if ((ancestorSeq>0 && !hasAlignment) || ancestorSeq>numSequences) { fprintf(stderr, "Bad ancestral sequence number: %d (%d sequences loaded)\n", ancestorSeq, numSequences); exit(4); } if (textFile) { if ( (text_fv=fopen(textFileName, "rt"))==NULL ) { fprintf(stderr, "Error opening text file for insertion into output: '%s'\n", textFileName); exit(4); } } ancestor=NULL; if (hasAlignment) { AllocateMemory(); ReadFile(); if (numSites<0) numSites=numAlignmentSites; if (ancestorSeq>0) { if (numSites!=numAlignmentSites) { fprintf(stderr, "Ancestral sequence is of a different length to the simulated sequences (%d)\n", numAlignmentSites); exit(4); } ancestor=sequences[ancestorSeq-1]; } } else if (numSites<0) numSites=1000; SetModel(model); numTaxa=-1; scale=1.0; treeSet = (TTree **)malloc(sizeof(TTree **) * maxPartitions); if (treeSet==NULL) { fprintf(stderr, "Out of memory\n"); exit(5); } partitionLengths = (int *)malloc(sizeof(int) * maxPartitions); if (partitionLengths==NULL) { fprintf(stderr, "Out of memory\n"); exit(5); } partitionRates = (double *)malloc(sizeof(double) * maxPartitions); if (partitionRates==NULL) { fprintf(stderr, "Out of memory\n"); exit(5); } for (i = 0; i < maxPartitions; i++) { if ((treeSet[i]=NewTree())==NULL) { fprintf(stderr, "Out of memory\n"); exit(5); } } CreateRates(); treeNo=0; do { partitionLengths[0] = -1; ReadTree(tree_fv, treeSet[0], treeNo+1, 0, NULL, &partitionLengths[0], &partitionRates[0]); if (treeNo==0) { numTaxa=treeSet[0]->numTips; if (!quiet) fprintf(stderr, "Random number generator seed: %ld\n\n", randomSeed); if (fileFormat == NEXUSFormat) { fprintf(stdout, "#NEXUS\n"); fprintf(stdout, "[\nGenerated by %s %s\n\n", PROGRAM_NAME, VERSION_NUMBER); PrintVerbose(stdout); fprintf(stdout, "]\n\n"); } } else if (treeSet[0]->numTips != numTaxa) { fprintf(stderr, "All trees must have the same number of tips.\n"); exit(4); } if (maxPartitions == 1) { if (partitionLengths[0] != -1) { fprintf(stderr, "\nWARNING: The treefile contained partion lengths but only one partition\n"); fprintf(stderr, "was specified.\n"); } partitionLengths[0] = numSites; } sumLength = partitionLengths[0]; i = 1; while (sumLength < numSites && i <= maxPartitions) { if (!IsTreeAvail(tree_fv)) { fprintf(stderr, "\nA set of trees number %d had less partition length (%d) than\n", treeNo + 1, sumLength); fprintf(stderr, "was required to make a sequence of length %d.\n", numSites); exit(4); } ReadTree(tree_fv, treeSet[i], treeNo+1, treeSet[0]->numTips, treeSet[0]->names, &partitionLengths[i], &partitionRates[i]); if (treeSet[i]->numTips != numTaxa) { fprintf(stderr, "All trees must have the same number of tips.\n"); exit(4); } sumLength += partitionLengths[i]; i++; } if (i > maxPartitions) { fprintf(stderr, "\nA set of trees number %d had more partitions (%d) than\n", treeNo + 1, i); fprintf(stderr, "was specified in the user options (%d).\n", maxPartitions); } numPartitions = i; if (sumLength != numSites) { fprintf(stderr, "The sum of the partition lengths in the treefile does not equal\n"); fprintf(stderr, "the specified number of sites.\n"); exit(4); } for (i = 0; i < numPartitions; i++) CreateSequences(treeSet[i], partitionLengths[i]); if (numPartitions > 1) { sum = 0.0; for (i = 0; i < numPartitions; i++) sum += partitionRates[i] * partitionLengths[i]; for (i = 0; i < numPartitions; i++) partitionRates[i] *= numSites / sum; } if (treeNo==0 && verbose && !quiet) { PrintVerbose(stderr); InitProgressBar(numTrees*numDatasets); DrawProgressBar(); } for (i=0; i<numDatasets; i++) { SetCategories(); k = 0; for (j = 0; j < numPartitions; j++) { scale = partitionRates[j]; if (scaleTrees) { if (!treeSet[j]->rooted) { fprintf(stderr, "To scale tree length, they must be rooted and ultrametric.\n"); exit(4); } scale *= treeScale/treeSet[j]->totalLength; } else if (scaleBranches) scale *= branchScale; EvolveSequences(treeSet[j], k, partitionLengths[j], scale, ancestor); k += partitionLengths[j]; } if (writeAncestors) WriteAncestralSequences(stdout, treeSet[0]); else WriteSequences(stdout, (numTrees > 1 ? treeNo+1 : -1), (numDatasets > 1 ? i+1 : -1), treeSet, partitionLengths); if (writeRates) { WriteRates(stderr); } if (textFile) { while (!feof(text_fv)) { ch = fgetc(text_fv); if (!feof(text_fv)) fputc(ch, stdout); } fputc('\n', stdout); rewind(text_fv); } if (verbose && !quiet) ProgressBar(); } for (i = 0; i < numPartitions; i++) DisposeTree(treeSet[i]); treeNo++; } while (IsTreeAvail(tree_fv)); /* for (i = 0; i < maxPartitions; i++) FreeTree(treeSet[i]); */ if (treeFile) fclose(tree_fv); if (textFile) fclose(text_fv); totalSecs = (double)(clock() - totalStart) / CLOCKS_PER_SEC; if (!quiet) { fprintf(stderr, "Time taken: %G seconds\n", totalSecs); if (verboseMemory) fprintf(stderr, "Total memory used: %ld\n", totalMem); } return 0; }
void CalcPeriod(char *DataFile = "drs4_peds_5buffers.dat", Int_t nevt, Int_t startEv = 1, char *PedFile) { // create progress bar TGHProgressBar *gProgress = ProgressBar("Calcolo periodo"); // Redefine DOMINO Depth in ADC counts const Float_t DominoDepthADC = pow(2, DOMINO_DEPTH); // open file FILE *fdata = OpenDataFile(DataFile); struct channel_struct *p; struct channel_struct *dep; // create list of graphs for pedestals TList *grPedList = new TList(); TGraphErrors *grPed; // create period histogram TString title = "Period histogram"; TH1 *hPeriod = new TH1F(title,title, 2*((Int_t) DOMINO_NCELL), (Double_t) -DOMINO_NCELL, (Double_t) DOMINO_NCELL); // calculate or read pedestals from file grPedList = OpenPedestals(PedFile); grPed = (TGraphErrors *) grPedList->At(anaChannel); // Count number of events in data file int nevtDataMax = 0; while (!feof(fdata)) { fread((void *) &event_data, 1, sizeof(event_data), fdata); nevtDataMax++; } printf("nevtDataMax: %d\n", nevtDataMax - 1); if (nevt > (nevtDataMax - startEv) || nevt == 0) nevt = nevtDataMax - startEv; cout << endl << "==>> Processing " << nevt << " events from file " << DataFile << endl; rewind(fdata); Int_t ievt = 1; // go to first event (startEv) while (ievt < startEv) { fread((void *) &event_data, 1, sizeof(event_data), fdata); if (feof(fdata)) break; ievt++; } ievt = 1; Int_t flagEnd = 0; Int_t fitusati = 0; Double_t chtmp; Double_t PedVal, itmp; Double_t mean, rms; Double_t ratio; //debug canvas TCanvas *cfitTest = new TCanvas("cfitTest", "fit tests", 1200, 780); cfitTest->Divide(1,nevt); // loop on events gProgress->Reset(); gProgress->SetMax(nevt); gSystem->ProcessEvents(); while (ievt <= nevt && !flagEnd) { fread((void *) &event_data, 1, sizeof(event_data), fdata); if (feof(fdata)) flagEnd = 1; p = (struct channel_struct *) &event_data.ch[0]; // read bunch of data dep = (struct channel_struct *) &event_data.ch[1]; // read bunch of data // goes to channel to analyze p += anaChannel; // read data, subtract pedestals values and save results in grAnaChDataTemp graph with // fixed error for each point (x = 0.5 and y = 2.1). Also generate an array with Domino // X and Y values TGraphErrors *grAnaChDataTemp = new TGraphErrors(DOMINO_NCELL); for (int ch = 0; ch < DOMINO_NCELL; ch++) { // Read pedestal value for this cell grPed->GetPoint(ch, itmp, PedVal); chtmp = (Double_t)(p->data[ch]); // data value chtmp = chtmp - PedVal; grAnaChDataTemp->SetPoint(ch, (Double_t) ch, chtmp); grAnaChDataTemp->SetPointError(ch, 0.5, 2.1); } // create fit functions TF1 *fsin = new TF1("fsin", sigSin, 0., 1024., 4); fsin->SetParameters(600., 255., 150., 150.); fsin->SetParNames("amplitude", "Period", "Phase", "DC-Offset"); grAnaChDataTemp->Fit("fsin", "Q"); TF1 *fsinFit = grAnaChDataTemp->GetFunction("fsin"); fsinFit->SetParNames("amplitude", "Period", "Phase", "DC-Offset"); // debug cfitTest->cd(ievt); grAnaChDataTemp->SetMarkerStyle(20); grAnaChDataTemp->SetMarkerSize(0.3); grAnaChDataTemp->GetYaxis()->SetLabelSize(0.12); grAnaChDataTemp->GetXaxis()->SetLabelSize(0.12); grAnaChDataTemp->Draw("APE"); Double_t fitPeriod, fitAmplitude, chisquare; fitPeriod = fsinFit->GetParameter("Period"); fitAmplitude = TMath::Abs(fsinFit->GetParameter("amplitude")); chisquare = fsinFit->GetChisquare(); cout << "period: " << fitPeriod << " amplitude: " << fitAmplitude << " chisquare: " << chisquare << endl; if(chisquare > 0.1e+06) { gProgress->Increment(1); gSystem->DispatchOneEvent(kTRUE); ievt++; continue; } gProgress->Increment(1); gSystem->DispatchOneEvent(kTRUE); hPeriod->Fill(fitPeriod); fitusati++; ievt++; } cout << "fit scartati :" << nevt - fitusati << endl; //draw TString Title = "Period distribution for nevt events"; TCanvas *cPeriod = new TCanvas("cPeriod", Title, 700, 700); hPeriod->Draw(); hPeriod->Fit("gaus"); TF1 *fgausFit = hPeriod->GetFunction("gaus"); //mean = fgausFit->GetParameter(1); // rms = fgausFit->GetParameter(2); mean = hPeriod->GetMean(); rms = hPeriod->GetRMS(); TString OutFile = "Period"; OutFile += nevt; OutFile += "events.dat"; FILE *f = fopen(OutFile.Data(), "w"); fwrite(&mean, sizeof(mean), 1, f); fwrite(&rms, sizeof(rms), 1, f); ((TGMainFrame *) gProgress->GetParent())->CloseWindow(); fclose(f); cout << "mean: " << mean << " rms: " << rms << endl; fclose(fdata); }
//11static int Copy_One_File(PAR_FILE *pf, char *msg, char *fName) //Копирование одного файла static int Copy_One_File(PAR_FILE *pf, char *msg) //Копирование одного файла { BYTE buff[sCl_B]; //Память под один кластер DWORD nb; #if !defined EMULATOR_HDD_AND_COPY //НЕТ Режима эмулятора с эмуляцией копирования ZeroMemory(buff, sCl_B); //Очистка буфера чтения #endif DWORD wSizeB = sCl_B; //Число записываемых байт равно числу байт в кластере DWORD nCl = pf->ClSt; //Текущий номер кластера равен первому кластеру файла LONGLONG SizeToEnd = pf->SizeF; //Число байт которые осталось записать DWORD numCl = DWORD((pf->SizeF + sCl_B - 1) / sCl_B); //Число кластеров необходимое для размещения файла данного размера if(numCl > 0) InitProgressBar(numCl, msg); for(DWORD i=0; i<numCl; i++) //По числу кластеров { if(nCl == 0x0FFFFFFF) //Признак конца цепочки return Error1((Lan+12)->msg); //return Error1("Неожиданно найден признак конца цепочки FAT."); if(*(FAT1 + nCl) == 0) //Ненормальная ситуация return Error1((Lan+11)->msg); //return Error1("Обнаружено несоответствие значения FAT и ссылки на кластер файла."); if(wSizeB > SizeToEnd) //11 wSizeB = DWORD(((SizeToEnd + 511) / 512) * 512); //Размер остатка записи меньше размера кластера ?? Почему сектор wSizeB = DWORD(SizeToEnd); //Размер остатка записи меньше размера кластера #if !defined EMULATOR_HDD_AND_COPY //НЕТ Режима эмулятора с эмуляцией копирования DWORD nSector = Start_SecDir1 + (nCl - 1) * sClSec; //Сектор начала текущего кластера if(ReadClast1_P(nSector, buff) < 0) return -1; //Чтение очeредного кластера #endif if(WriteFile(outFile, buff, wSizeB, &nb, NULL) == false || nb != wSizeB) return ErrorSys1((Lan+83)->msg); //return ErrorSys1("Ошибка при записи выходного файла."); SizeToEnd -= wSizeB; //Число байт которые осталось записать nCl = *(FAT1 + nCl); //Номер следующего кластера if(nCl > maxZapFAT1 && nCl != 0x0FFFFFFF) return Error1((Lan+13)->msg); //"Номер кластера превышает допустимое значение." if(SizeToEnd == 0 && nCl != 0x0FFFFFFF) Error1((Lan+29)->msg); //return Error2("Выходной файл заданного размера записан,", "а признак конца цепочки FAT не найден."); if(ProgressBar(wSizeB) < 0) return -1; //Оператор нажал кнопку Прервать } CloseFile(&outFile); //Закрыли выходной файл /*11 if((pf->SizeF % sCl_B) != 0) //Размер файла не является кратным размеру кластера { int n = 0; //Счетчик для ожидания освобождения файла if(Open_FileR(fName, &outFile, &n) < 0) //Открытие выходного файла return -1; LARGE_INTEGER TPoz; TPoz.QuadPart = pf->SizeF; TPoz.u.LowPart = SetFilePointer(outFile, TPoz.u.LowPart, &TPoz.u.HighPart, FILE_BEGIN); if(TPoz.u.LowPart == 0xFFFFFFFF && GetLastError() != NO_ERROR) return ErrorSys1((Lan+83)->msg); //"Ошибка при позиционировании по диску." if(SetEndOfFile(outFile) == false) return ErrorSys1((Lan+83)->msg); //return ErrorSys1("Ошибка при записи выходного файла."); } */ FILETIME fTime, flTime; SYSTEMTIME sysTime; sysTime.wYear = pf->Year; sysTime.wMonth = pf->Mon; // sysTime.wDayOfWeek = 0; sysTime.wDay = pf->Day; sysTime.wHour = pf->Hour; sysTime.wMinute = pf->Min; sysTime.wSecond = pf->Sec; sysTime.wMilliseconds = 0; SystemTimeToFileTime(&sysTime, &flTime); //Преобразовали время LocalFileTimeToFileTime(&flTime, &fTime); SetFileTime(outFile, &fTime, &fTime, &fTime); //Дата файла return 0;
void CalibrateData(Int_t nevt,Int_t startEv = 1, char *PedFile = "drs4_20100311_t_ped.root") { // create progress bar TGHProgressBar *gProgress = ProgressBar("Calibrazione dati"); // Redefine DOMINO Depth in ADC counts const Float_t DominoDepthADC = pow(2, DOMINO_DEPTH); // create list of histograms for pedestals TList *grPedList = new TList(); TGraphErrors *grPed; // create list of histograms for channels TList *hCellCalibList = new TList(); TH1F *hCellCalib; TList *grCellCalibList = new TList(); TGraphErrors *grCellCalib; int mV[NCALIBFILES] = {-500,-400,-300,-200,-100,0,100,200,300,400,500}; /*for (int iFile = 0; iFile < NCALIBFILES; iFile++) { mV[iFile] = mVStart; mVStart += mVStep; }*/ char *calibrationFile; char *calibrationFileArray[NCALIBFILES]; calibrationFileArray[0] = "drs4_1000ev_dcm500mv.dat"; calibrationFileArray[1] = "drs4_1000ev_dcm400mv.dat"; calibrationFileArray[2] = "drs4_1000ev_dcm300mv.dat"; calibrationFileArray[3] = "drs4_1000ev_dcm200mv.dat"; calibrationFileArray[4] = "drs4_1000ev_dcm100mv.dat"; calibrationFileArray[5] = "drs4_1000ev_dc1mv.dat"; calibrationFileArray[6] = "drs4_1000ev_dc100mv.dat"; calibrationFileArray[7] = "drs4_1000ev_dc200mv.dat"; calibrationFileArray[8] = "drs4_1000ev_dc300mv.dat"; calibrationFileArray[9] = "drs4_1000ev_dc400mv.dat"; calibrationFileArray[10] = "drs4_1000ev_dc500mv.dat"; for (int iFile = 0; iFile < NCALIBFILES; iFile++) { for (int ch = 0; ch < DOMINO_NCELL; ch++) { // TString title = "Calibration signal file:"; title += iFile; title += " ch:"; title += ch; hCellCalib = new TH1F(title,title, DominoDepthADC, -DominoDepthADC, DominoDepthADC); hCellCalibList->Add(hCellCalib); } } for (int ch = 0; ch < DOMINO_NCELL; ch++) { grCellCalib = new TGraphErrors(NCALIBFILES); grCellCalibList->Add(grCellCalib); } // calculate or read pedestals from file grPedList = OpenPedestals(PedFile); grPedData = (TGraphErrors *) grPedList->At(anaChannel); grPedTrig = (TGraphErrors *) grPedList->At(trigChannel); // create gauss function TF1 *fgauss = new TF1("fgauss", "TMath::Gaus(x,[0],[1],0)", -DOMINO_NCELL, DOMINO_NCELL); fgauss->SetParameter(0,0.); fgauss->SetParameter(1,1.); fgauss->SetParLimits(0, 0., DominoDepthADC); fgauss->SetParLimits(1, 0.1, 20.); TCanvas *ctest = new TCanvas("ChannelTest", "ChannelTest", 800, 600); ctest->Divide(3, 4); gProgress->Reset(); gProgress->SetMax(nevt*NCALIBFILES); gSystem->ProcessEvents(); for (int iFile = 0; iFile < NCALIBFILES; iFile++) { // open file calibrationFile = calibrationFileArray[iFile]; FILE *fdata = OpenDataFile(calibrationFile); struct channel_struct *p; struct channel_struct *dep; Double_t refval=0, reftmp = 0; Double_t PedVal, itmp; // Count number of events in data file int nevtDataMax = 0; while (!feof(fdata)) { fread((void *) &event_data, 1, sizeof(event_data), fdata); nevtDataMax++; } printf("nevtDataMax: %d\n", nevtDataMax); if (nevt > (nevtDataMax - startEv) || nevt == 0) nevt = nevtDataMax - startEv; cout << endl << "==>> Processing " << nevt << " events from file " << calibrationFile << endl; rewind(fdata); for (int j = 0; j < 1; j++) { fread((void *) &event_data, 1, sizeof(event_data), fdata); p = (struct channel_struct *) &event_data.ch[0]; // read bunch of data p += anaChannel; for (ch = 0; ch < DOMINO_NCELL; ch++) { grPedData->GetPoint(ch, itmp, PedVal); reftmp = TMath::Abs((Double_t)(p->data[ch])-PedVal); if (reftmp > 0.8* refval) refval = 0.2*reftmp+0.8*refval; // cout << ch << " " <<p->data[ch] << " " <<reftmp << " " << refval <<endl ; } } cout << "refval="<< refval<<endl; rewind(fdata); Int_t ievt = 1; // go to first event (startEv) while (ievt < startEv) { fread((void *) &event_data, 1, sizeof(event_data), fdata); if (feof(fdata)) break; ievt++; } ievt = 1; Int_t iTrig = 0; Int_t flagEnd = 0; Double_t chtmp, chtrig; Double_t ratio; Double_t mean, rms; // loop on events while (ievt <= nevt && !flagEnd) { fread((void *) &event_data, 1, sizeof(event_data), fdata); if (feof(fdata)) flagEnd = 1; p = (struct channel_struct *) &event_data.ch[0]; // read bunch of data dep = (struct channel_struct *) &event_data.ch[1]; // read bunch of data //now anaChannel analysis p += anaChannel; // read data, subtract pedestals values and fill hCellCalibList. for (int ch = 0; ch < DOMINO_NCELL; ch++) { // Read pedestal value for this cell grPedData->GetPoint(ch, itmp, PedVal); chtmp = (Double_t)(p->data[ch]); // data value chtmp = chtmp - PedVal; //if (TMath::Abs(chtmp) > 0.9 * refval) ((TH1 *) hCellCalibList->At(iFile*DOMINO_NCELL+ch))->Fill(chtmp); //cout << ch << " " << iFile << " " << chtmp << endl; } gProgress->Increment(1); gSystem->DispatchOneEvent(kTRUE); ievt++; // next event } TH1 *hCellTmp; for(ch = 0; ch < DOMINO_NCELL;ch++) { hCellTmp = ((TH1 *) hCellCalibList->At(iFile*DOMINO_NCELL+ch)); //hCellTmp->Fit("gaus", "Q"); //mean = (hCellTmp->GetFunction("gaus"))->GetParameter(1); //rms = (hCellTmp->GetFunction("gaus"))->GetParameter(2); mean = hCellTmp->GetMean(); rms = hCellTmp->GetRMS(); ((TGraphErrors *) (grCellCalibList->At(ch)))->SetPoint(iFile, (Double_t) mV[iFile], mean); ((TGraphErrors *) (grCellCalibList->At(ch)))->SetPointError(iFile, 0., rms); } ctest->cd(iFile + 1); hCellTmp = ((TH1 *) hCellCalibList->At(567 + iFile*DOMINO_NCELL)); hCellTmp->Fit("gaus","Q"); hCellTmp->DrawCopy(); } TString OutFile = "CalibrationDataNew"; OutFile += nevt; OutFile += "events.root"; TFile *f = new TFile(OutFile, "RECREATE"); for (int ch = 0; ch < DOMINO_NCELL; ch++) { TString key = "CalibDataCell"; key += ch; ((TGraphErrors*) grCellCalibList->At(ch))->Write(key); } f->Close(); hCellCalibList->Delete(); ((TGMainFrame *) gProgress->GetParent())->CloseWindow(); fclose(fdata); }
void CDialogProcSelect::OnAttachButton( ) { int SelectedIndex = m_ProcessList.GetSelectionMark( ); if (SelectedIndex != -1) { HANDLE ProcessHandle; DWORD SelectedProcessId; TCHAR SelectedProcessIdText[64]; m_ProcessList.GetItemText( SelectedIndex, COLUMN_PROCESSID, SelectedProcessIdText, sizeof( SelectedProcessIdText ) ); SelectedProcessId = _tcstoul( SelectedProcessIdText, NULL, 10 ); auto FoundProcessInfo = std::find_if( m_ProcessInfos.begin( ), m_ProcessInfos.end( ), [SelectedProcessId] ( const ProcessInfoStack& proc ) -> bool { return proc.dwProcessId == SelectedProcessId; } ); if (FoundProcessInfo != m_ProcessInfos.end( )) { ProcessHandle = ReClassOpenProcess( PROCESS_ALL_ACCESS, FALSE, FoundProcessInfo->dwProcessId ); if (ProcessHandle == NULL || GetLastError( ) != ERROR_SUCCESS) { CString MessageText; MessageText.Format( _T( "Failed to attach to process \"%s\"!" ), FoundProcessInfo->strProcessName.GetString( ) ); MessageBox( MessageText, g_ReClassApp.m_pszAppName, MB_OK | MB_ICONERROR ); } else { if (g_hProcess != NULL) // Stop leaking handles! CloseHandle( g_hProcess ); g_hProcess = ProcessHandle; g_ProcessID = FoundProcessInfo->dwProcessId; g_ProcessName = FoundProcessInfo->strProcessName; UpdateMemoryMap( ); if (g_bSymbolResolution && m_LoadAllSymbols.GetCheck( ) == BST_CHECKED) { OnClose( ); MSG Msg; CStatusBar* StatusBar = g_ReClassApp.GetStatusBar( ); CProgressBar ProgressBar( _T( "Progress" ), 100, 100, TRUE, 0, StatusBar ); ProgressBar.SetStep( 1 ); ProgressBar.SetText( _T( "Symbols loading: " ) ); for (size_t i = 0; i < g_MemMapModules.size( ); i++) { TCHAR ProgressText[256]; MemMapInfo *CurrentModule = &g_MemMapModules[i]; ProgressBar.SetRange32( 0, (int)g_MemMapModules.size( ) ); _stprintf_s( ProgressText, _T( "[%d/%d] %s" ), (UINT)i + 1, (UINT)g_MemMapModules.size( ), CurrentModule->Name.GetString( ) ); StatusBar->SetPaneText( 1, ProgressText ); //MemMapInfo* pCurrentModule = new MemMapInfo( CurrentModule ); //Utils::NtCreateThread( LoadModuleSymbolsThread, pCurrentModule, 0 ); if (!g_ReClassApp.m_pSymbolLoader->LoadSymbolsForModule( CurrentModule->Path, CurrentModule->Start, CurrentModule->Size )) { PrintOut( _T( "Failed to load symbols for %s" ), CurrentModule->Name.GetString( ) ); } ProgressBar.StepIt( ); // Peek and pump through messages to stop reclass from hanging while (::PeekMessage( &Msg, NULL, 0, 0, PM_NOREMOVE )) { if (!AfxGetApp( )->PumpMessage( )) ::PostQuitMessage( 0 ); } } StatusBar->SetPaneText( 1, _T( "" ) ); return; } OnClose( ); } } } }
int main() { ProgressBar(); return 0; }
int main(int argc, char **argv) // ============================================================================= // Main program // ============================================================================= { RunUserMenu(); FILE *OutputFile = fopen("euler.dat", "w"); double *x = (double*) malloc((Nx+2*Ng)*sizeof(double)); Conserved *U = (Conserved*) malloc((Nx+2*Ng)*sizeof(Conserved)); int i; // --------------------------------------------------------------------------- // Initial conditions setup. for (i=0; i<Nx+2*Ng; ++i) { // Here we initialize the array of x coordinates, and set the initial // conditions on the conserved array. x[i] = -0.5 + (i-Ng+0.5) / Nx; Primitive P = testProblem->InitialCondition(x[i]); U[i] = PrimToCons(&P); } int CycleCounter = 0; double CurrentTime = 0.0; double EndTime = OutputTime; double dt = 0.0; double dx = 1.0 / Nx; // --------------------------------------------------------------------------- // This is the main iteration loop. while (CurrentTime < EndTime) { MaxWavespeed = 0.0; integrationMethod->AdvanceSolution(U, dt); CurrentTime += dt; CycleCounter++; dt = CFL * dx / MaxWavespeed; printf("\r[%s]", ProgressBar(CurrentTime/EndTime)); fflush(stdout); } // --------------------------------------------------------------------------- // Output solution. for (i=Ng; i<Nx+Ng; ++i) { // This loop prints an ASCII table of x-coordinate values with their // associated primitive variables. Primitive P = ConsToPrim(&U[i]); fprintf(OutputFile, "%+8.6e %+8.6e %+8.6e %+8.6e %+8.6e %+8.6e\n", x[i], P.rho, P.p, P.vx, P.vy, P.vz); } free(x); free(U); fclose(OutputFile); // --------------------------------------------------------------------------- // Create a simple GNUplot script. FILE *gnuplot = fopen("plot.gp", "w"); fprintf(gnuplot, "set title \"%s %s t=%3.2f PLM=%3.2f\"\n", testProblem->Name, integrationMethod->Name, OutputTime, PlmTheta); fprintf(gnuplot, "set xlabel \"x\"\n"); fprintf(gnuplot, "plot \\\n"); fprintf(gnuplot, "\"euler.dat\" u 1:2 title \"Density \",\\\n"); fprintf(gnuplot, "\"euler.dat\" u 1:3 title \"Pressure\",\\\n"); fprintf(gnuplot, "\"euler.dat\" u 1:4 title \"Velocity\" \n"); fprintf(gnuplot, "pause(-1)\\\n"); fclose(gnuplot); printf("\n\n"); printf("All done. Data is in euler.dat, but if you have gnuplot simply run\n" "$> gnuplot plot.gp\n\n"); return 0; }
void InitializeGauge (void) { loadOp = 0; ProgressBar (TXT_INITIALIZING, 0, InitGaugeSize (), InitializePoll); }
int divide_page(const char* filename,const int pages,int save) { /* 分页函数 参数说明: filename: 当前打开文件的文件名 pages: 需要分的页数 save: 是否需要跳回第一页 (初始化时使用) 返回值: 0: 已读到文件末尾 1: 未读到文件末尾 */ int cx,cy; int i=0,j; const int pp=16; int is_chs=0; // 中文字符标识 int tmp=cached,total=0; int decades_passed = 1; int handle; char* buf=(char*)malloc(460); FONTCHARACTER fname[64]; char_to_font(filename,fname); handle=Bfile_OpenFile_OS(fname,0); tmp=cached; totbytes=bytes[cached]; // 保险修正 // 如果请求的页数超过 9999 页,修正为 9999 页 if ((total=tmp+pages)>9999) total=9999; // 在 9999 页时尝试往后翻一页,跳出 if (cached+1>9999) {Bfile_CloseFile_OS(handle);return 0;}; // 在屏幕上显示分页的进度 ProgressBar(0, total - tmp); for (j=tmp;j<total;++j) // 从当前已缓存页面分到请求的页面,使用模拟填充显示区域方法 { // 尝试读取一段文字以备分页 memset(buf,0,461); Bfile_ReadFile_OS(handle,buf,400,totbytes); // 如果读到文件末尾则跳出 if (!buf[0]) { ProgressBar(total - tmp, total - tmp); Bfile_CloseFile_OS(handle); MsgBoxPop(); return 0; } // 填充位置设置为初始状态 cx=0; cy=24; for (i=0;;) { is_chs=buf[i] & 0x80; // 判断高位字节,确定是否为中文 if ((cx+pp)>368) // 填充超过屏幕右边缘 goto cn; if (is_chs) i+=2; // 中文,跳2字节 else { if (buf[i] == '\r' || buf[i] == '\n') // 若读到回车符直接进入下一行 { i++; if (buf[i] == '\r' || buf[i] == '\n') // 若读到回车符直接进入下一行 i++; goto cn; } i++; } // 将字符填充入当前行,增加字符偏移 if (is_chs) cx+=25; else cx+=18; // 填充超过屏幕右边缘 if (cx>368) { cn: cx=0; cy+=24; // 增加纵向字符偏移,进入下一行 if (cy>190) // 填充超过屏幕下边缘,跳出 break; } } bytes[j+1]=i+totbytes; // 将最后一个字符在文件中的位置存入下一页的缓存,以备读取 totbytes+=i; // 读取字节指针增加 ++cached; // 已缓存页面增加,表示分页成功 // 每分完1/10的总体,增加进度显示 if (j - tmp == (total - tmp) / 10 * decades_passed) { ProgressBar(j - tmp, total - tmp); decades_passed++; } } if (save) page=0; // 跳回第一页 ProgressBar(total - tmp, total - tmp); Bfile_CloseFile_OS(handle); MsgBoxPop(); return 1; }
bool InstallFiles() { ButtonBar.Clear(); ButtonBar.AddButton("C", "Cancel"); ButtonBar.Draw(); char *msg; char *dbuttons[2] = { GetTranslation("Continue"), GetTranslation("Exit program") }; if ((InstallInfo.dest_dir_type == DEST_SELECT) || (InstallInfo.dest_dir_type == DEST_DEFAULT)) { msg = CreateText(GetTranslation("This will install %s to the following directory:\n%s\nContinue?"), InstallInfo.program_name.c_str(), MakeCString(InstallInfo.dest_dir)); } else { msg = CreateText(GetTranslation("This will install %s\nContinue?"), InstallInfo.program_name.c_str()); } CCDKDialog Diag(CDKScreen, CENTER, CENTER, msg, dbuttons, 2); Diag.SetBgColor(26); int sel = Diag.Activate(); Diag.Destroy(); refreshCDKScreen(CDKScreen); if (sel == 1) return false; CCDKSWindow InstallOutput(CDKScreen, 0, 6, GetDefaultHeight()-5, -1, CreateText("<C></29/B>%s", GetTranslation("Install output")), 2000); InstallOutput.SetBgColor(5); nodelay(WindowOf(InstallOutput.GetSWin()), true); // Make sure input doesn't block const int maxx = getmaxx(InstallOutput.GetSWin()->win); CCDKSWindow ProggWindow(CDKScreen, 0, 2, 5, maxx, NULL, 4); ProggWindow.SetBgColor(5); ProggWindow.AddText(""); ProggWindow.AddText(CreateText("</B/29>%s:<!29!B>", GetTranslation("Status"))); ProggWindow.AddText(CreateText("%s (1/%d)", GetTranslation("Extracting files"), InstallInfo.command_entries.size()+1), true, BOTTOM, 24); CCDKHistogram ProgressBar(CDKScreen, 25, 3, 1, maxx-29, HORIZONTAL, CreateText("<C></29/B>%s", GetTranslation("Progress")), false); ProgressBar.SetBgColor(5); ProgressBar.SetHistogram(vPERCENT, TOP, 0, 100, 0, COLOR_PAIR (24) | A_REVERSE | ' ', A_BOLD); setCDKSwindowLLChar(ProggWindow.GetSWin(), ACS_LTEE); setCDKSwindowLRChar(ProggWindow.GetSWin(), ACS_RTEE); InstallOutput.Draw(); ProggWindow.Draw(); // Check if we need root access char *passwd = NULL; LIBSU::CLibSU SuHandler; SuHandler.SetUser("root"); SuHandler.SetTerminalOutput(false); bool askpass = false; for (std::list<command_entry_s *>::iterator it=InstallInfo.command_entries.begin(); it!=InstallInfo.command_entries.end(); it++) { if ((*it)->need_root != NO_ROOT) { // Command may need root permission, check if it is so if ((*it)->need_root == DEPENDED_ROOT) { param_entry_s *p = GetParamByVar((*it)->dep_param); if (p && !WriteAccess(p->value)) { (*it)->need_root = NEED_ROOT; if (!askpass) askpass = true; } } else if (!askpass) askpass = true; } } if (!askpass) askpass = !WriteAccess(InstallInfo.dest_dir); // Ask root password if one of the command entries need root access and root isn't passwordless if (askpass && SuHandler.NeedPassword()) { CCDKEntry entry(CDKScreen, CENTER, CENTER, GetTranslation("This installation requires root(administrator) privileges in order to continue\n" "Please enter the password of the root user"), "", 60, 0, 256, vHMIXED); entry.SetHiddenChar('*'); entry.SetBgColor(26); while(1) { char *sz = entry.Activate(); if ((entry.ExitType() != vNORMAL) || !sz || !sz[0]) { if (YesNoBox(GetTranslation("Root access is required to continue\nAbort installation?"))) EndProg(); refreshCDKScreen(CDKScreen); } else { if (SuHandler.TestSU(sz)) { passwd = strdup(sz); for (short s=0;s<strlen(sz);s++) sz[s] = 0; break; } for (short s=0;s<strlen(sz);s++) sz[s] = 0; entry.Clean(); // Some error appeared if (SuHandler.GetError() == LIBSU::CLibSU::SU_ERROR_INCORRECTPASS) { WarningBox(GetTranslation("Incorrect password given for root user\nPlease retype")); } else { throwerror(true, GetTranslation("Could not use su to gain root access\n" "Make sure you can use su(adding the current user to the wheel group may help)")); } } } // Restore screen entry.Destroy(); refreshCDKScreen(CDKScreen); } short percent = 0; bool alwaysroot = false; if (!WriteAccess(InstallInfo.dest_dir)) { CExtractAsRootFunctor Extracter; Extracter.SetUpdateProgFunc(SUUpdateProgress, &ProgressBar); Extracter.SetUpdateTextFunc(SUUpdateText, &InstallOutput); if (!Extracter(passwd)) { CleanPasswdString(passwd); passwd = NULL; throwerror(true, "Error during extracting files"); } InstallOutput.AddText("Done!\n"); alwaysroot = true; // Install commands need root now too } else { while(percent<100) { std::string curfile; percent = ExtractArchive(curfile); InstallOutput.AddText("Extracting file: " + curfile, false); if (percent==100) InstallOutput.AddText("Done!", false); else if (percent==-1) throwerror(true, "Error during extracting files"); ProgressBar.SetValue(0, 100, percent/(1+InstallInfo.command_entries.size())); ProgressBar.Draw(); chtype input = getch(); if (input == 'c') { if (YesNoBox(GetTranslation("Install commands are still running\n" "If you abort now this may lead to a broken installation\n" "Are you sure?"))) { CleanPasswdString(passwd); passwd = NULL; EndProg(); } } } } SuHandler.SetThinkFunc(InstThinkFunc, passwd); SuHandler.SetOutputFunc(PrintInstOutput, &InstallOutput); percent = 100/(1+InstallInfo.command_entries.size()); // Convert to overall progress short step = 2; // Not 1, because extracting files is also a step for (std::list<command_entry_s*>::iterator it=InstallInfo.command_entries.begin(); it!=InstallInfo.command_entries.end(); it++, step++) { if ((*it)->command.empty()) continue; ProggWindow.Clear(); ProggWindow.AddText(""); ProggWindow.AddText(CreateText("</B/29>%s:<!29!B>", GetTranslation("Status"))); ProggWindow.AddText(CreateText("%s (%d/%d)", GetTranslation((*it)->description.c_str()), step, InstallInfo.command_entries.size()+1), true, BOTTOM, 24); ProgressBar.Draw(); std::string command = (*it)->command + " " + GetParameters(*it); InstallOutput.AddText(""); InstallOutput.AddText(CreateText("Execute: %s", command.c_str())); InstallOutput.AddText(""); InstallOutput.AddText(""); if (((*it)->need_root == NEED_ROOT) || alwaysroot) { SuHandler.SetPath((*it)->path.c_str()); SuHandler.SetCommand(command); if (!SuHandler.ExecuteCommand(passwd)) { if ((*it)->exit_on_failure) { CleanPasswdString(passwd); passwd = NULL; throwerror(true, "%s\n('%s')", GetTranslation("Failed to execute install command"), SuHandler.GetErrorMsgC()); } } } else { // Redirect stderr to stdout, so that errors will be displayed too command += " 2>&1"; setenv("PATH", (*it)->path.c_str(), 1); FILE *pipe = popen(command.c_str(), "r"); char term[1024]; if (pipe) { while (fgets(term, sizeof(term), pipe)) { InstallOutput.AddText(term); chtype input = getch(); if (input == 'c') /*injectCDKSwindow(InstallOutput.GetSWin(), input);*/ { if (YesNoBox(GetTranslation("Install commands are still running\n" "If you abort now this may lead to a broken installation\n" "Are you sure?"))) { CleanPasswdString(passwd); passwd = NULL; EndProg(); } } } // Check if command exitted normally and close pipe int state = pclose(pipe); if (!WIFEXITED(state) || (WEXITSTATUS(state) == 127)) // SH returns 127 if command execution failes { if ((*it)->exit_on_failure) { CleanPasswdString(passwd); passwd = NULL; throwerror(true, "Failed to execute install command"); } } } else { CleanPasswdString(passwd); passwd = NULL; throwerror(true, "Could not execute installation commands (could not open pipe)"); } #if 0 // Need to find a good way to safely suspend a process...this code doesn't always work :( int pipefd[2]; pipe(pipefd); pid_t pid = fork(); if (pid == -1) throwerror(true, "Error during command execution: Could not fork process"); else if (pid) // Parent process { close(pipefd[1]); // We're not going to write here std::string out; char c; int compid = -1; // PID of the executed command while(read(pipefd[0], &c, sizeof(c)) > 0) { out += c; if (c == '\n') { if (compid == -1) { compid = atoi(out.c_str()); InstallOutput.AddText(CreateText("pid: %d compid: %d", pid, compid), false); } else InstallOutput.AddText(out, false); out.clear(); } chtype input = getch(); if (input != ERR) /*injectCDKSwindow(InstallOutput.GetSWin(), input);*/ { if (kill(compid, SIGTSTP) < 0) // Pause command execution WarningBox("PID Error: %s\n", strerror(errno)); char *buttons[2] = { GetTranslation("Yes"), GetTranslation("No") }; CCharListHelper msg; msg.AddItem(GetTranslation("This will abort the installation")); msg.AddItem(GetTranslation("Are you sure?")); CCDKDialog dialog(CDKScreen, CENTER, CENTER, msg, msg.Count(), buttons, 2); dialog.SetBgColor(26); int ret = dialog.Activate(); bool cont = ((ret == 1) || (dialog.ExitType() != vNORMAL)); dialog.Destroy(); refreshCDKScreen(CDKScreen); if (!cont) { kill(pid, SIGTERM); EndProg(); } kill(compid, SIGCONT); // Continue command execution } } close (pipefd[0]); int status; //waitpid(pid, &status, 0); } else // Child process { // Redirect stdout to pipe close(STDOUT_FILENO); dup (pipefd[1]); close (pipefd[0]); // No need to read here // Make sure no errors are printed and write pid of new command command += " 2> /dev/null & echo $!"; execl("/bin/sh", "sh", "-c", command.c_str(), NULL); system(CreateText("echo %s", strerror(errno))); _exit(1); } #endif } percent += (1.0f/((float)InstallInfo.command_entries.size()+1.0f))*100.0f; ProgressBar.SetValue(0, 100, percent); } ProgressBar.SetValue(0, 100, 100); ProgressBar.Draw(); CleanPasswdString(passwd); passwd = NULL; ButtonBar.Clear(); ButtonBar.AddButton("Arrows", "Scroll install output"); ButtonBar.AddButton("Enter", (FileExists(InstallInfo.own_dir + "/config/finish")) ? "Continue" : "Finish"); // HACK ButtonBar.Draw(); WarningBox("Installation of %s complete!", InstallInfo.program_name.c_str()); InstallOutput.Activate(); return (InstallOutput.ExitType() == vNORMAL); }