Beispiel #1
0
int CALLBACK WinMain(
					HINSTANCE hInstance1,
					HINSTANCE hPrevInstance,
					LPSTR     lpCmdLine,
					int       nCmdShow
					)
{
	windowWidth = 800;
	windowHeight = 600;
	camZoom = 2;
	hInstance = hInstance1;
	LPCTSTR className = "GraphicsGame";
	WNDCLASS wc = {};
	wc.style = CS_OWNDC|CS_VREDRAW|CS_HREDRAW;
	wc.lpfnWndProc = (WNDPROC)WindowProc;
	wc.hInstance = hInstance;
	wc.lpszClassName = className;
	wc.hCursor = NULL;

	if(!RegisterClass(&wc))
	{
		killWindow(className);
		MessageBox(NULL, "Couldnt Register Class", "Error", MB_OK);
		return 1;
	}

	int windowStatus = createGLWindow(hInstance, className);
	if(!windowStatus)
	{
		return 1;
	}

	

	double dx = 0;
	double dy = 0;
	double maxSpeed = 5;
	double accel = 0.1f;
	MSG message;
	game = (Game*)calloc(1, sizeof(Game));
	initGL();
	initGame(game);
	int counter = 0;
	LARGE_INTEGER cps;
	LARGE_INTEGER curCount;
	LARGE_INTEGER prevCount;
	LONGLONG countDifference;

	QueryPerformanceFrequency(&cps);
	double secsPassed = 0;
	QueryPerformanceCounter(&curCount);
	float pan = 0.2;
	float topPan = 1;
	float lowPan = 0.2;
	while(!game->done)
	{
		prevCount = curCount;
		QueryPerformanceCounter(&curCount);
		countDifference = curCount.QuadPart - prevCount.QuadPart;
		secsPassed = (long double)countDifference / (long double)cps.QuadPart;
		while(PeekMessage(&message, hWindow, 0, 0, PM_REMOVE))
		{
			if(message.message == WM_QUIT)
			{
				game->done = true;
			}
			TranslateMessage(&message);
			DispatchMessage(&message);
		}
		dx = 0;
		dy = 0;
		if(game->keys[VK_SHIFT])
		{
			pan = topPan;
		}
		else
		{
			pan = lowPan;
		}
		if(game->keys['W'])
		{
			camY+=pan;
		}
		if(game->keys['A'])
		{
			camX-=pan;
		}
		if(game->keys['S'])
		{
			camY-=pan;
		}
		if(game->keys['D'])
		{
			camX+=pan;
		}
		
		if(game->keys['Q'])
		{
			camZoom += 0.01;
			if(camZoom > 6) camZoom = 6;
			resize(windowWidth, windowHeight);
		}
		if(game->keys['E'])
		{
			camZoom -= 0.01;
			if(camZoom < 1) camZoom = 1;
			resize(windowWidth, windowHeight);
		}
		if(game->keys[VK_SPACE])
		{
			saveFile(game);
			
		}
		
		
		



		updateGame(game, dx, dy, secsPassed);
		
		drawScene(game);
		SwapBuffers(hDeviceContext);

	}
	free(game);
	killWindow(className);
	return 0;
}
void PaletteEditor::saveGradientAction()
{
	QString saveFile( QFileDialog::getSaveFileName(this,
		tr("Save gradient to a cpt file"),
		QFileInfo(m_lastBrowseDir).absoluteFilePath(),
		tr("CPT Gradient Files (*.cpt)")) );

	if (saveFile.isEmpty())
		return;

	QFileInfo file( saveFile );
	QString openDir( file.absoluteFilePath() );
	logInfo(QString("PaletteEditor::saveGradientAction : saving gradient to %1").arg(saveFile));
	if (openDir != m_lastBrowseDir)
		m_lastBrowseDir = openDir;

	QFile data(file.absoluteFilePath());
	if (!data.open(QFile::ReadWrite))
	{
		QMessageBox msgBox;
		msgBox.setText(tr("Error: Couldn't open file %1").arg(file.filePath()));
		msgBox.setIcon(QMessageBox::Warning);
		msgBox.exec();
		return;
	}

	QTextStream os(&data);
	os << "# COLOR_MODEL = RGB" << endl
		<< scientific << qSetRealNumberPrecision(6) << qSetFieldWidth(4);
	p_stops = m_gradientStops->getStops();
	qStableSort(p_stops.begin(), p_stops.end(), GradientStop::lessThanGradientStopComparison);
	GradientStops::const_iterator i = p_stops.constBegin();
	os << left << (*i).first
		<< right
		<< (*i).second.red()
		<< (*i).second.green()
		<< (*i).second.blue() << ' ';
	++i;
	for ( ; i != p_stops.constEnd(); ++i)
	{
		os << left << (*i).first
		<< right
		<< (*i).second.red()
		<< (*i).second.green()
		<< (*i).second.blue() << endl;

		if (i + 1 != p_stops.constEnd())
			os << left << (*i).first
			<< right
			<< (*i).second.red()
			<< (*i).second.green()
			<< (*i).second.blue() << ' ';
	}
	os << "B   0   0   0" << endl
		<< "F 255 255 255" << endl
		<< "N 255   0   0" << endl;

	data.close();
	if (data.error() != QFile::NoError)
	{
		QMessageBox msgBox;
		msgBox.setText(tr("Error: Couldn't write to file %1").arg(file.filePath()));
		msgBox.setIcon(QMessageBox::Warning);
		msgBox.exec();
	}
}
Beispiel #3
0
MainWindow::MainWindow(AmViewerState *state) : _state(state) {
    _state->recon_tree = NULL;
    _state->amEvent = NULL;
    _state->show_dBm = false;
    _state->filtered = true;
    _state->sumpols = false;
    _state->resetSearch(); // couldn't hurt?

    setWindowTitle("AmViewer");

    // creat dialogs
    _searchWindow = new SearchWindow(this,_state);
    _visWindow = new VisWindow(this,_state);
    _fovWindow = new FovWindow(this,_state);
    _filterWindow = NULL;
    _infoWindow = NULL;

    QWidget *centralWidget = new QWidget();
    setCentralWidget(centralWidget);
    QVBoxLayout *bigLayout = new QVBoxLayout(centralWidget);

    // File menu
    QAction *quitMenu = new QAction("&Exit",this);
    quitMenu->setShortcut(tr("Ctrl+Q"));
    connect(quitMenu,SIGNAL(triggered()),qApp,SLOT(quit()));

    QAction *openMenu = new QAction("&Open ROOT file...",this);
    openMenu->setShortcut(tr("Ctrl+O"));
    connect(openMenu,SIGNAL(triggered()),this,SLOT(openFile()));

    _saveMenu = new QAction("&Save event candidates...",this);
    connect(_saveMenu,SIGNAL(triggered()),this,SLOT(saveFile()));

    QMenu *fileDrop;
    fileDrop = menuBar()->addMenu("&File");
    fileDrop->addAction(openMenu);
    fileDrop->addAction(_saveMenu);
    fileDrop->addAction(quitMenu);

    _saveMenu->setEnabled(false);

    // View menu
    _unitsMenu = new QAction("&Display dBm",this);
    _unitsMenu->setCheckable(true);
    _unitsMenu->setChecked(false);
    connect(_unitsMenu,SIGNAL(triggered()),this,SLOT(applyUnits()));

    // Filter dialog
    _filterMenu = new QAction("&Filter Settings",this);
    connect(_filterMenu,SIGNAL(triggered()),this,SLOT(openFilter()));

    // Polarization checkbox
    _polMenu = new QAction("&Sum Polarizations",this);
    _polMenu->setCheckable(true);
    _polMenu->setChecked(false);
    _polMenu->setEnabled(false);
    connect(_polMenu,SIGNAL(triggered()),this,SLOT(applySumPol()));

    QMenu *viewDrop;
    viewDrop = menuBar()->addMenu("&View");
    viewDrop->addAction(_unitsMenu);
    viewDrop->addAction(_polMenu);
    viewDrop->addAction(_filterMenu);
    _filterMenu->setEnabled(false);

    // Analysis menu
    QAction *infoMenu = new QAction("&Event Info",this);
    connect(infoMenu,SIGNAL(triggered()),this,SLOT(openInfo()));

    _analysisDrop = menuBar()->addMenu("&Analysis");
    _analysisDrop->addAction(infoMenu);

    QAction *searchMenu = new QAction("&Search Parameters",this);
    connect(searchMenu,SIGNAL(triggered()),this,SLOT(openSearch()));

    _analysisDrop->addAction(searchMenu);
    _analysisDrop->setEnabled(false);

    QAction *visMenu = new QAction("&Event Visualization",this);
    connect(visMenu,SIGNAL(triggered()),this,SLOT(openVis()));
    _analysisDrop->addAction(visMenu);

    QAction*fovMenu = new QAction("&AMBER Field of View",this);
    connect(fovMenu,SIGNAL(triggered()),this,SLOT(openFov()));
    _analysisDrop->addAction(fovMenu);

    // Set up layout for event browser, pixel windows, graphs
    QHBoxLayout *hbox = new QHBoxLayout();
    bigLayout->addLayout(hbox);

    // Event list stuff
    _eventList = new QTreeWidget(this);
    _eventList->setColumnCount(2);
    _eventList->setColumnHidden(1,true); //'true' valid in C++?

    QTreeWidgetItem *_source0 = new QTreeWidgetItem(_eventList);
    _source0->setText(0,"Source:0 (LTRIG)");

    QTreeWidgetItem *_source1 = new QTreeWidgetItem(_eventList);
    _source1->setText(0,"Source:1 (PPS)");

    QTreeWidgetItem *_source2 = new QTreeWidgetItem(_eventList);
    _source2->setText(0,"Source:2 (Auger)");

    _eventList->setHeaderLabel("Events");

    hbox->addWidget(_eventList);

    // Some gross stuff concerning the clickable horns
    _hornDisplay = new HornDisplay(this,1);

    CenterHorns *centerLegend = new CenterHorns("center",true);
    QGraphicsProxyWidget *centerLegendProxy = new QGraphicsProxyWidget();
    centerLegendProxy->setWidget(centerLegend->widget);

    _hornDisplay->hornScene->addItem(centerLegendProxy);

    centerLegendProxy->rotate(45);
    centerLegendProxy->setPos(0,-50);
    centerLegendProxy->setZValue(0.0);

    AmHorn *ppsHorn[4];

    int i;
    stringstream out;

    QToolButton *b;

    for(i=0; i<4; i++) {
        b = new QToolButton();
        b->setFixedSize(25,25);
        out.str("");
        out << (i+1);
        ppsHorn[i] = new AmHorn(b,"PPS" + out.str());
        ppsHorn[i]->proxyWidget = new QGraphicsProxyWidget();
        ppsHorn[i]->proxyWidget->setWidget(ppsHorn[i]->_button);
        _hornDisplay->hornScene->addItem(ppsHorn[i]->proxyWidget);
        ppsHorn[i]->proxyWidget->setPos(25*i-145,375);

        // probably stupid, delete
        //ppsHorn[i]->trigger_color = "blue";
        //ppsHorn[i]->updateStyle();

        //delete b;
    }

    QGraphicsSimpleTextItem *item;

    for(i=0; i<4; i++) {
        item = new QGraphicsSimpleTextItem();
        _hornDisplay->hornScene->addItem(item);
        if(i==0) {
            item->setText("CH");
            item->setPos(-7,-31);
            item->setZValue(1.0);
        }
        if(i==1) {
            item->setText("CV");
            item->setPos(-7,5);
            item->setZValue(1.0);
        }
        if(i==2) {
            item->setText("KH");
            item->setPos(-24,-15);
            item->setZValue(1.0);
        }
        if(i==3) {
            item->setText("KV");
            item->setPos(12,-15);
            item->setZValue(1.0);
        }
        //delete item;
    }

    // CRUFT ALERT
    // THIS WHOLE NEXT LOOP IS HIGHLY SUSPECT, I DOUBT IT DOES ANYTHING
    QString qstr;
    for(i=0; i<16; i++) {
        out.str("");
        out << (i+1);
        qstr = QString::fromStdString(out.str());
        item = new QGraphicsSimpleTextItem(qstr);
        _hornDisplay->hornScene->addItem(item);
        if(i==0)
            item->setPos(-2.5,75.0);
        else if(i==1)
            item->setPos(-105.0,177.5);
        else if(i==2)
            item->setPos(-2.5,280.0);
        else if(i==3)
            item->setPos(102.5,177.5);
        else if(i==4)
            item->setPos(-70.0,55.0);
        else if(i==5)
            item->setPos(-95.0,80.0);
        else if(i==6)
            item->setPos(-120.0,105.0);
        else if(i==7)
            item->setPos(-125.0,250.0);
        else if(i==8)
            item->setPos(-100.0,275.5);
        else if(i==9)
            item->setPos(-75.0,300.0);
        else if(i==10)
            item->setPos(60.0,300.0);
        else if(i==11)
            item->setPos(85.0,275.0);
        else if(i==12)
            item->setPos(110.0,250.0);
        else if(i==13)
            item->setPos(120.0,110.0);
        else if(i==14)
            item->setPos(95.0,85.0);
        else if(i==15)
            item->setPos(70.0,60.0);
    }

    QVBoxLayout *evVbox = new QVBoxLayout();
    hbox->addLayout(evVbox);

    QGridLayout *evInfoGrid = new QGridLayout();
    evVbox->addLayout(evInfoGrid);

    _evIdLabel = new QLabel("");
    _evSourceLabel = new QLabel("");
    _evSecLabel = new QLabel("");
    _evNsLabel = new QLabel("");
    _evInfoLabel = new QLabel("");

    evInfoGrid->addWidget(_evIdLabel,0,0);
    evInfoGrid->addWidget(_evSourceLabel,0,1);
    evInfoGrid->addWidget(_evSecLabel,1,0);
    evInfoGrid->addWidget(_evNsLabel,1,1);
    evInfoGrid->addWidget(_evInfoLabel,2,0);

    evVbox->addWidget(_hornDisplay);

    QVBoxLayout *pixelVbox = new QVBoxLayout();
    hbox->addLayout(pixelVbox);

    for(i=0; i<4; i++) {
        pixelWindow[i] = new PixelWindow(this,i);
        pixelWindow[i]->setMinimumHeight(100);
        pixelWindow[i]->setMinimumWidth(300);
        pixelVbox->addWidget(pixelWindow[i]);
    }

    for(i=0; i<28; i++) {
        _hornDisplay->channel[i]->setHornClickFunction(this);
        connect(_hornDisplay->channel[i]->_button,SIGNAL(clicked()),_hornDisplay->channel[i],SLOT(hornClick()));
    }

    for(i=0; i<4; i++) {
        //ppsHorn[i]->setHornClickFunction(clickHornSetPixel);
        ppsHorn[i]->setHornClickFunction(this);
        connect(ppsHorn[i]->_button,SIGNAL(clicked()),ppsHorn[i],SLOT(hornClick()));
    }
}
Beispiel #4
0
/*
 *   If containerFile is NULL, then we don't use that as a source for paths and we set the parent ID to 0.
 */
int TskL01Extract::extractFiles(TskFile * containerFile /*= NULL*/)
{
    static const std::string MSG_PREFIX = "TskL01Extract::extractFiles : ";
    
    try
    {
        m_containerFile = containerFile;

        if (m_archivePath.empty())
        {
            throw TskException(MSG_PREFIX + "No path to archive provided.");
        }

        std::string L01Path = TskUtilities::toUTF8(m_archivePath);
        if (m_containerFile != NULL)
        {
            L01Path = m_containerFile->getPath();
        }

        //m_db.addImageInfo((int)m_img_info->itype, m_img_info->sector_size);
        m_db.addImageName(L01Path.c_str());

        if (openContainer() != 0)
        {
            return -1;
        }

        if (m_imgInfo == NULL)
        {
            throw TskException(MSG_PREFIX +"Images not open yet");
        }

		// Create a map of directory names to file ids to use to 
		// associate files/directories with the correct parent.
		std::map<std::string, uint64_t> directoryMap;

        std::vector<ArchivedFile>::iterator it = m_archivedFiles.begin();
        for (; it != m_archivedFiles.end(); ++it)
        {
            Poco::Path path(it->path);
            Poco::Path parent = it->path.parent();
            std::string name;

            if (path.isDirectory())
            {
                name = path[path.depth() - 1];
            }
            else
            {
                name = path[path.depth()];
            }

            // Determine the parent id of the file.
            uint64_t parentId = 0;
            if (path.depth() == 0 || path.isDirectory() && path.depth() == 1)
            {
                // This file or directory lives at the root so our parent id
                // is the containing file id (if a containing file was provided).
                if (m_containerFile != NULL)
                {
                    parentId = m_containerFile->getId();
                }
            }
            else
            {
                // We are not at the root so we need to lookup the id of our
                // parent directory.
                std::map<std::string, uint64_t>::const_iterator pos;
                pos = directoryMap.find(parent.toString());

                if (pos == directoryMap.end())
                {
                    //error!
                    std::stringstream msg;
                    msg << "extractFiles: parent ID not mapped for " << it->path.toString();
                    LOGERROR(msg.str());
                }
                else
                {
                    parentId = pos->second;
                }
            }

            // Store some extra details about the derived (i.e, extracted) file.
            std::stringstream details;  ///@todo anything here?

            std::string fullpath = "";
            if (m_containerFile != NULL)
            {
                fullpath.append(m_containerFile->getFullPath());
            }
            fullpath.append("\\");
            fullpath.append(path.toString());

            uint64_t fileId;
            if (m_db.addDerivedFileInfo(name,
                parentId,
                path.isDirectory(),
                it->size,
                details.str(), 
                static_cast<int>(it->ctime),
                static_cast<int>(it->crtime),
                static_cast<int>(it->atime),
                static_cast<int>(it->mtime),
                fileId, fullpath) == -1) 
            {
                    std::wstringstream msg;
                    msg << L"addDerivedFileInfo failed for name="
                        << name.c_str();
                    LOGERROR(msg.str());
            }

            if (path.isDirectory())
            {
                directoryMap[path.toString()] = fileId;
            }
            else
            {
                // For file nodes, recreate file locally
                // Will save zero-length files
                if (saveFile(fileId, *it) == 0)
                {
                    // Schedule
                    m_db.updateFileStatus(fileId, TskImgDB::IMGDB_FILES_STATUS_READY_FOR_ANALYSIS);
                    TskServices::Instance().getScheduler().schedule(Scheduler::FileAnalysis, fileId, fileId);
                }
            }
        }

    }
    catch (TskException &ex)
    {
        std::ostringstream msg;
        msg << MSG_PREFIX << "TskException: " << ex.message();
        LOGERROR(msg.str());
        return -1;
    }
    catch (std::exception &ex)
    {
        std::ostringstream msg;
        msg << MSG_PREFIX << "std::exception: " << ex.what();
        LOGERROR(msg.str());
        return -1;
    }
    catch (...)
    {
        LOGERROR(MSG_PREFIX + "unrecognized exception");
        return -1;
    }

    return 0; //success
}
Beispiel #5
0
MainWindow::MainWindow(
  QWidget *parent)
  : QMainWindow(parent),
    ui(new Ui::MainWindow),
    aboutForm(0),
    documentationForm(0),
    preferencesForm(0),
    toolBar(0),
    formulaInput(0),
    cellLabel(0),
    optionsButton(0),
    scanButton(0),
    csvModel(0),
    table(0),
    barcodeViewForm(0),
    optionsDialog(0)
{
  ui->setupUi(this);
  setAttribute(Qt::WA_Maemo5StackedWindow);

  barcodeViewForm = new LasBarcodeViewForm(this);
  optionsDialog = new LasOptionsDialog(this);
  preferencesForm = new LasPreferencesForm(this);

  toolBar = new QToolBar();
  addToolBar(toolBar);

  formulaInput = new QLineEdit();

  cellLabel = new QLabel(toolBar);
  cellLabel->setMinimumSize(80, 0);

  optionsButton = new QPushButton();
  optionsButton->setIcon(QIcon(":/icons/dash.svg"));

  scanButton = new QPushButton();
  scanButton->setIcon(QIcon(":/icons/plus.svg"));

  toolBar->addWidget(scanButton);
  toolBar->addWidget(cellLabel);
  toolBar->addWidget(formulaInput);
  toolBar->addWidget(optionsButton);

  table = new LasSheet(this);
  ui->centralLayout->addWidget(table);

  QSettings settings("pietrzak.org", "Lasagne");

  if (settings.contains("currentFilename"))
  {
    currentFilename = settings.value("currentFilename").toString();
  }
  else
  {
    currentFilename = "/home/user/MyDocs/.documents/Lasagne.csv";
  }
  
  csvModel = new LasCsvModel(currentFilename, this, true);

  table->setModel(csvModel);

  table->resizeAllCells();

//  statusBar();
/*
  connect(
    table,
    SIGNAL(currentItemChanged(QTableWidgetItem*, QTableWidgetItem*)),
    this,
    SLOT(updateStatus(QTableWidgetItem*)));
*/

  connect(
    table->selectionModel(),
    SIGNAL(currentChanged(const QModelIndex &, const QModelIndex &)),
    this,
    SLOT(updateToolbar(const QModelIndex &)));

/*
  connect(
    table,
    SIGNAL(itemChanged(QTableWidgetItem*)),
    this,
    SLOT(updateStatus(QTableWidgetItem*)));
*/

  connect(
    formulaInput,
    SIGNAL(returnPressed()),
    this,
    SLOT(returnPressed()));

/*
  connect(
    table,
    SIGNAL(itemChanged(QTableWidgetItem*)),
    this,
    SLOT(updateLineEdit(QTableWidgetItem*)));
*/

//  table->updateColor(0);

  connect(
    optionsButton,
    SIGNAL(clicked()),
    optionsDialog,
    SLOT(exec()));

  connect(
    scanButton,
    SIGNAL(clicked()),
    this,
    SLOT(displayBarcodeForm()));

  connect(
    barcodeViewForm,
    SIGNAL(barcodeFound(QString, QString, QString, QString, QString)),
    this,
    SLOT(addNewRow(QString, QString, QString, QString, QString)));

/*
  connect(
    optionsDialog,
    SIGNAL(editFormula()),
    this,
    SLOT(something()));
*/

  connect(
    optionsDialog,
    SIGNAL(clearCell()),
    this,
    SLOT(clearCurrentCell()));

  connect(
    optionsDialog,
    SIGNAL(removeRow()),
    this,
    SLOT(removeCurrentRow()));

  connect(
    optionsDialog,
    SIGNAL(loadFile()),
    this,
    SLOT(load()));

  connect(
    optionsDialog,
    SIGNAL(saveFile()),
    this,
    SLOT(save()));

  connect(
    optionsDialog,
    SIGNAL(saveFileAs()),
    this,
    SLOT(saveAs()));

  // Preferences form:
  connect(
    preferencesForm,
    SIGNAL(beepPreference(bool)),
    barcodeViewForm,
    SLOT(setBeepPref(bool)));

  // Initialize beep preference:
  barcodeViewForm->setBeepPref(preferencesForm->getBeepPref());

  connect(
    preferencesForm,
    SIGNAL(ignoreLensCover(bool)),
    barcodeViewForm,
    SLOT(updateIgnoreCover(bool)));

  barcodeViewForm->updateIgnoreCover(preferencesForm->getIgnoreCover());
}
void VehicleTemplateExportDialog::saveTemplate(QString path)
{
    QJsonObject exportObject;

    QList<UAVObject *> objectsToExport;
    objectsToExport << StabilizationSettings::GetInstance(m_uavoManager);
    objectsToExport << StabilizationSettingsBank1::GetInstance(m_uavoManager);
    objectsToExport << StabilizationSettingsBank2::GetInstance(m_uavoManager);
    objectsToExport << StabilizationSettingsBank3::GetInstance(m_uavoManager);
    objectsToExport << MixerSettings::GetInstance(m_uavoManager);
    objectsToExport << EKFConfiguration::GetInstance(m_uavoManager);
    m_uavoManager->toJson(exportObject, objectsToExport);

    exportObject["type"]       = m_type;
    exportObject["subtype"]    = m_subType;
    exportObject["name"]       = ui->Name->text();
    exportObject["owner"]      = ui->Owner->text();
    exportObject["nick"]       = ui->ForumNick->text();
    exportObject["size"]       = ui->Size->text();
    exportObject["weight"]     = ui->Weight->text();
    exportObject["motor"]      = ui->Motor->text();
    exportObject["esc"]        = ui->Esc->text();
    exportObject["servo"]      = ui->Servo->text();
    exportObject["battery"]    = ui->Battery->text();
    exportObject["propeller"]  = ui->Propeller->text();
    exportObject["controller"] = ui->Controllers->currentText();
    exportObject["comment"]    = ui->Comment->document()->toPlainText();
    QUuid uuid = QUuid::createUuid();
    exportObject["uuid"]       = uuid.toString();

    if (!m_image.isNull()) {
        QByteArray bytes;
        QBuffer buffer(&bytes);
        buffer.open(QIODevice::WriteOnly);
        m_image.scaled(IMAGE_SCALE_WIDTH, IMAGE_SCALE_HEIGHT, Qt::KeepAspectRatio,
                       Qt::SmoothTransformation).save(&buffer, "PNG");
        exportObject["photo"] = QString::fromLatin1(bytes.toBase64().data());
    }

    QJsonDocument saveDoc(exportObject);

    const char *fileType = ".optmpl";

    QString fileName     = QString("%1-%2-%3%4")
                           .arg(fixFilenameString(ui->Name->text(), 20))
                           .arg(fixFilenameString(ui->Type->text(), 30))
                           .arg(fixFilenameString(uuid.toString().right(12)))
                           .arg(fileType);

    QString fullPath;
    if (path.isEmpty()) {
        fullPath = QString("%1%2%3").arg(QDir::homePath()).arg(QDir::separator()).arg(fileName);
        fullPath = QFileDialog::getSaveFileName(this, tr("Export settings"), fullPath, QString("%1 (*%2)").arg(tr("OPTemplates"), fileType));
    } else {
        fullPath = QString("%1%2%3").arg(path).arg(QDir::separator()).arg(fileName);
    }

    if (!fullPath.isEmpty()) {
        if (!fullPath.endsWith(fileType)) {
            fullPath.append(fileType);
        }
        QFile saveFile(fullPath);
        if (saveFile.open(QIODevice::WriteOnly)) {
            saveFile.write(saveDoc.toJson());
            saveFile.close();
        } else {
            QMessageBox::information(this, "Export", tr("Settings could not be exported to \n%1(%2).\nPlease try again.")
                                     .arg(QFileInfo(saveFile).absoluteFilePath(), saveFile.error()), QMessageBox::Ok);
        }
    }
}
Beispiel #7
0
void KMiniEdit::fileSaveAs()
{
  saveFile(KURL());
}
Beispiel #8
0
MainWindow::MainWindow()
{
    QMenu *fileMenu = new QMenu(tr("&File"));

    QAction *saveAction = fileMenu->addAction(tr("&Save..."));
    saveAction->setShortcut(tr("Ctrl+S"));

    QAction *quitAction = fileMenu->addAction(tr("E&xit"));
    quitAction->setShortcut(tr("Ctrl+Q"));

    menuBar()->addMenu(fileMenu);
    editor = new QTextEdit();

    QTextCursor cursor(editor->textCursor());
    cursor.movePosition(QTextCursor::Start); 

    QTextFrame *mainFrame = cursor.currentFrame();
    
    QTextCharFormat plainCharFormat;
    QTextCharFormat boldCharFormat;
    boldCharFormat.setFontWeight(QFont::Bold);
/*  main frame
//! [0]
    QTextFrame *mainFrame = cursor.currentFrame();
    cursor.insertText(...);
//! [0]
*/
    cursor.insertText("Text documents are represented by the "
                      "QTextDocument class, rather than by QString objects. "
                      "Each QTextDocument object contains information about "
                      "the document's internal representation, its structure, "
                      "and keeps track of modifications to provide undo/redo "
                      "facilities. This approach allows features such as the "
                      "layout management to be delegated to specialized "
                      "classes, but also provides a focus for the framework.",
                      plainCharFormat);

//! [1]
    QTextFrameFormat frameFormat;
    frameFormat.setMargin(32);
    frameFormat.setPadding(8);
    frameFormat.setBorder(4);
//! [1]
    cursor.insertFrame(frameFormat);

/*  insert frame
//! [2]
    cursor.insertFrame(frameFormat);
    cursor.insertText(...);
//! [2]
*/
    cursor.insertText("Documents are either converted from external sources "
                      "or created from scratch using Qt. The creation process "
                      "can done by an editor widget, such as QTextEdit, or by "
                      "explicit calls to the Scribe API.", boldCharFormat);

    cursor = mainFrame->lastCursorPosition();
/*  last cursor
//! [3]
    cursor = mainFrame->lastCursorPosition();
    cursor.insertText(...);
//! [3]
*/
    cursor.insertText("There are two complementary ways to visualize the "
                      "contents of a document: as a linear buffer that is "
                      "used by editors to modify the contents, and as an "
                      "object hierarchy containing structural information "
                      "that is useful to layout engines. In the hierarchical "
                      "model, the objects generally correspond to visual "
                      "elements such as frames, tables, and lists. At a lower "
                      "level, these elements describe properties such as the "
                      "style of text used and its alignment. The linear "
                      "representation of the document is used for editing and "
                      "manipulation of the document's contents.",
                      plainCharFormat);


    connect(saveAction, SIGNAL(triggered()), this, SLOT(saveFile()));
    connect(quitAction, SIGNAL(triggered()), this, SLOT(close()));

    setCentralWidget(editor);
    setWindowTitle(tr("Text Document Frames"));
}
Beispiel #9
0
bool ScriptEditorWidget::save() {
    return _currentScript.isEmpty() ? saveAs() : saveFile(_currentScript);
}
Beispiel #10
0
int main(int argc, char* argv[]) 
{

  //local variables
    HashTable *inverted_index, *test_index;
    char *target_dir, *results_file1, *results_file2, *rewritten_file;
    target_dir = results_file1 = results_file2 = rewritten_file=NULL;

    
  // 1. Program parameter processing
  //./indexer  [TARGET_DIRECTORY] [RESULTS FILENAME1] [RESULTS FILENAME2] [REWRITEN FILENAME]
  //or
  // ./indexer  [TARGET_DIRECTORY] [RESULTS FILENAME]
    if(argc == 3 || argc == 5) {
        target_dir = calloc(strlen(argv[1])+1, sizeof(char));
        if(target_dir == NULL) {
            LOG(stdout,"Error: failed to calloc the variable target_dir\n");
            return 1;
        }
        if( strcpy(target_dir, argv[1]) == NULL) {
            LOG(stdout,"Error: failed to strcpy to the variable target_dir\n");
            return 1;
        }
      //check if the directory is valid
        if(IsDir(target_dir)) {
            printf("%s is a directory\n", target_dir);
        }
        else {
            printf("Error: %s is NOT a directory\n", target_dir);
            free(target_dir);
            return 1;
        }
     
        results_file1 = calloc(strlen(argv[2])+1, sizeof(char));
        if(results_file1 == NULL) {
            LOG(stdout,"Error: failed to calloc the variable results_file1\n");
            return 1;
        }
        
        if( strcpy(results_file1, argv[2]) == NULL) {
            LOG(stdout,"Error: failed to strcpy to the variable results_file1\n");
            return 1;
        }
        
        if(argc == 5) {
            results_file2 = calloc(strlen(argv[3])+1, sizeof(char));
            if(results_file2 == NULL) {
                LOG(stdout,"Error: failed to calloc the varaible results_file2\n");
                free(target_dir);
                free(results_file1);
                return 1;
            }
            
            if( strcpy(results_file2, argv[3]) == NULL) {
                LOG(stdout,"Error: failed to strcpy to variable results_file2\n");
                free(target_dir);
                free(results_file1);
                return 1;
            }
            
            rewritten_file = calloc(strlen(argv[4])+1, sizeof(char));
            if(rewritten_file == NULL) {
                LOG(stdout,"Error: failed to calloc rewritten_file\n");
                free(target_dir);
                free(results_file1);
                free(results_file2);
                return 1;
            }
            
            if( strcpy(rewritten_file, argv[4]) == NULL) {
                LOG(stdout,"Error: failed to strcpy to variable rewritten_file\n");
                free(target_dir);
                free(results_file1);
                free(results_file2);
                return 1;
            }
        }
    }
    else {
      //wrong input parameters, inform the user about it.
        printf("Usage: ./indexer [TARGET_DIRECTORY] [RESULTS FILENAME]\n");
        printf("   or  ./indexer [TARGET_DIRECTORY] [RESULTS FILENAME1] [RESULTS FILENAME2] [REWRITEN FILENAME]\n");
        printf("You have entered %d parameters\n", (argc - 1));
        return 1;
    }
    
    
    
  // 2. Initialize data structures
  // allocate Inverted_index, zero it, and set links to NULL.
    inverted_index = calloc(1, sizeof(HashTable));
    if(inverted_index == NULL) {
        LOG(stdout,"Error: failed to calloc the variable inverted_index\n");
        return 1;
    }
    

  // 3.print to stdout that the building of index is starting
    //printf("\nStarting to build the index\n");
    LOG(stdout,"Starting to build the index\n");

  // 4. Build the inverted index
    if(buildIndexFromDirectory (inverted_index, target_dir)) {
        LOG(stdout, "Error: buildIndexFromDirectory() failed\n");
        return 1;
    }
    LOG(stdout,"Building the inverted index\n");

  // 5. Save the inverted index
    if(!saveFile(inverted_index, results_file1)) {
        LOG(stdout,"Successfully saved the inverted index\n");
    }
    else {
      LOG(stdout, "Error: saveFile() failed\n");
    }
    
    
  // 6. Free appropriate memory
    destroyHash(inverted_index);
    free(target_dir);
    free(results_file1);
    

  // 7. If 4 input parameters are detected
    if(5 == argc) {
        test_index = calloc(1, sizeof(HashTable));
        
        if(test_index == NULL) {
            LOG(stdout, "Error: failed to calloc the variable test_index\n");
            free(results_file2);
            free(rewritten_file);
            destroyHash(test_index);
            return 1;
        }
        
        if(!IsFile(results_file2)) {
            printf("Error: %s is not a file\n", results_file2);
            free(results_file2);
            free(rewritten_file);
            destroyHash(test_index);
            return 1;
        }
        
        
        
  // 8. Inform user that testing has started
        LOG(stdout, "Starting the testing process\n");
  
      
      
  // 9. Reload the index from the file and rewrite it to a new file
        if(readFile(test_index, results_file2)) {
            LOG(stdout,"Error: readFile failed\n");
            free(results_file2);
            free(rewritten_file);
            destroyHash(test_index);
            return 1;
        }
          

  // 10. save the reconstructed index
        if(saveFile(test_index, rewritten_file)) {
            LOG(stdout,"Error: saveFile(test_index, rewritten_file) failed\n");
            free(results_file2);
            free(rewritten_file);
            destroyHash(test_index);
            return 1;
        }
        else {
            LOG(stdout,"Successfully saved the inverted index\n");
        }
        
  // 11. free appropriate memory
        free(results_file2);
        free(rewritten_file);
        destroyHash(test_index);
      
        LOG(stdout,"Test is complete\n");
    }
  
  // 12. Finished
    LOG(stdout,"indexer.c has finished\n");
    return 0;
}
int main(int argc, char *argv[])
{
	FILE *fp_config;
	/*---------Begin process cmd-line args and Redirection--------*/

	switch (argc) {
	case 1: // No parameters, use stdin
		printf("NO argument provided\n");
		fp_config = stdin;
		break;

	case 2: // One parameter, use .lan file supplied	
		errno_t err;
		if ((err = fopen_s(&fp_config, argv[1], "r")) != 0) {
			fprintf(stderr, "Cannot open config file %s!\n", argv[1]);
		}
		break;

	default:
		printf("Syntax: scanner [file]\n");
		return(1);
	}

	// BEGIN check if file empty
	
	fseek(fp_config, 0, SEEK_END);
	if (ftell(fp_config) == 0) {
		printf("File is empty.\n");
		exit(1);
	}
	else {
		rewind(fp_config);
	}

	// END check if file empty

	// load tokenlist
	std::vector<std::string> tokenlist;
	loadlist(tokenlist, "res_tokenlist.txt");

	std::vector<std::string> correstokenlist;
	loadlist(correstokenlist, "res_correstokenlist.txt");

	std::vector<std::string> rwordlist;
	loadlist(rwordlist, "res_wordlist.txt");

	std::vector<std::string> correswordlist;
	loadlist(correswordlist, "res_correswordlist.txt");

	std::vector<std::string> latexcommandslist;
	loadlist(latexcommandslist, "res_latexcommandslist.txt");
	// END load corresponding tokens list

	// BEGIN filewalking
	char c;
	std::vector<token> stub;
	std::vector<std::string> wordlist;
	std::string word;
	std::vector<int> hierarchytypes;
	int currenthierarchy = 0;
	int lasthierarchytype = 0;
	while ((c = fgetc(fp_config)) != EOF) {
		if ((c >= 48 && c <= 57) || (c >= 65 && c <= 90) || (c >= 97 && c <= 122) || c==46 || c == 44) {
			word.push_back(c);
		}
		else {
			if (word != "") {
				wordlist.push_back(word);
				token token_line = token(TYPWORD, currenthierarchy, lasthierarchytype, wordlist.size()-1);
				stub.push_back(token_line);
				word = "";
			}

			if (c == '\n') {
				token token_line = token(TYPLINE, currenthierarchy, lasthierarchytype);
				stub.push_back(token_line);
			}
			else if (c == '(') {
				currenthierarchy++;
				lasthierarchytype = RNDBR;
				hierarchytypes.push_back(RNDBR);
				token token_line = token(TYPBRAC, currenthierarchy, lasthierarchytype);
				stub.push_back(token_line);
			}
			else if (c == '[') {
				currenthierarchy++;
				lasthierarchytype = SQUBR;
				hierarchytypes.push_back(SQUBR);
				token token_line = token(TYPBRAC, currenthierarchy, lasthierarchytype);
				stub.push_back(token_line);
			}
			else if (c == '{') {
				currenthierarchy++;
				lasthierarchytype = SWGBR;
				hierarchytypes.push_back(SWGBR);
				token token_line = token(TYPBRAC, currenthierarchy, lasthierarchytype);
				stub.push_back(token_line);
			}
			else if (c == '|') {
				if (lasthierarchytype == ABSBR) {
					currenthierarchy--;
					hierarchytypes.pop_back();
					if (currenthierarchy == 0) {
						lasthierarchytype = NONBR;
					}
					else {
						lasthierarchytype = hierarchytypes[hierarchytypes.size() - 1];
					}
					token token_line = token(TYPBRAC, currenthierarchy + 1, lasthierarchytype);
					stub.push_back(token_line);
				}
				else {
					currenthierarchy++;
					lasthierarchytype = ABSBR;
					hierarchytypes.push_back(ABSBR);
					token token_line = token(TYPBRAC, currenthierarchy, lasthierarchytype);
					stub.push_back(token_line);
				}

			}
			else if (c == ')') {
				currenthierarchy--;
				hierarchytypes.pop_back();
				if (currenthierarchy == 0) {
					lasthierarchytype = NONBR;
				}
				else {
					lasthierarchytype = hierarchytypes[hierarchytypes.size() - 1];
				}
				token token_line = token(TYPBRAC, currenthierarchy + 1, lasthierarchytype);
				stub.push_back(token_line);
			}
			else if (c == ']') {
				currenthierarchy--;
				hierarchytypes.pop_back();
				if (currenthierarchy == 0) {
					lasthierarchytype = NONBR;
				}
				else {
					lasthierarchytype = hierarchytypes[hierarchytypes.size() - 1];
				}
				token token_line = token(TYPBRAC, currenthierarchy + 1, lasthierarchytype);
				stub.push_back(token_line);
			}
			else if (c == '}') {
				currenthierarchy--;
				hierarchytypes.pop_back();
				if (currenthierarchy == 0) {
					lasthierarchytype = NONBR;
				}
				else {
					lasthierarchytype = hierarchytypes[hierarchytypes.size() - 1];
				}
				token token_line = token(TYPBRAC, currenthierarchy + 1, lasthierarchytype);
				stub.push_back(token_line);
			}
			else if (c == ' ') {

			}
			else {
				int tokenid = chkstringid(std::string(1, c), tokenlist);
				if (tokenid > -1) {
					token token_line = token(TYPTOKN, currenthierarchy, lasthierarchytype, tokenid);
					stub.push_back(token_line);
				}
			}
		}
	}
	// END filewalking

	// BEGIN translation

	int left = 0;
	int middle = 0;
	int right = 0;
	// Construct to map IDs in the complex environment:
	// Runner:				[left]		[middle]	[right]		----->
	// IDs:		[1]			[2]			[4]			[5]			[2]			[8]
	for (int i = 2; i < stub.size(); i++) {
		left = i - 2;
		middle = i - 1;
		right = i;
		if (stub[left].get_type() == 1 && stub[middle].get_type() == 4 && stub[right].get_type() == 1 && stub[middle].get_wordlistid() == 1) {
			int hierarchyentrypoint = 0;
			for (int a = left; a > 0; a--) {
				if (stub[a].get_hierarchy() < stub[left].get_hierarchy()) {
					hierarchyentrypoint = a + 1;
					break;
				}
			}
			token token_LCMD = token(TYPLCMD, stub[hierarchyentrypoint].get_hierarchy() - 1, stub[hierarchyentrypoint].get_hierarchy() - 1, 0);
			stub[hierarchyentrypoint].become_SWGBR_Left();
			stub[left].become_SWGBR_Right();
			stub[right].become_SWGBR_Left();
			stub.insert(stub.begin() + hierarchyentrypoint, token_LCMD);
			i++; left = i - 2;	middle = i - 1;	right = i;
			stub.erase(stub.begin() + middle);
			for (int a = right+1; a < stub.size(); a++) {
				if (stub[a].get_type()==TYPBRAC) {
					if (stub[a].get_hierarchy() == stub[middle].get_hierarchy()) {
						if(stub[a].get_lasthierarchytype() == stub[middle].get_lasthierarchytype()-1)
							i=a; left = i - 2;	middle = i - 1;	right = i;
							stub[i].become_SWGBR_Right();
							break;
					}
					
				}
			}
		}
	}

	std::string output;
	for (int i = 0; i < stub.size(); i++) {
		switch (stub[i].get_type()) {
		case TYPBRAC: {
			if (chkopenbracket(stub, i)) {
				switch (stub[i].get_lasthierarchytype()) {
				case RNDBR: {
					output += "\\left (";
					hierarchytypes.push_back(RNDBR);
					break;
				}
				case SQUBR: {
					output += "\\left [";
					hierarchytypes.push_back(SQUBR);
					break;
				}
				case SWGBR: {
					output += "\\left {"; 
					hierarchytypes.push_back(SWGBR);
					break;
				}
				case ABSBR: {
					output += "\\left |";
					hierarchytypes.push_back(ABSBR);
					break;
				}
				}
			}
			else {
					switch (hierarchytypes[hierarchytypes.size() - 1]) {
					case RNDBR: {
						output += "\\right )";
						hierarchytypes.pop_back();
						break;
					}
					case SQUBR: {
						output += "\\right ]";
						hierarchytypes.pop_back();
						break;
					}
					case SWGBR: {
						output += "\\right }";
						hierarchytypes.pop_back();
						break;
					}
					case ABSBR: {
						output += "\\right |";
						hierarchytypes.pop_back();
						break;
					}
					}
			}
			break;
		}
		case TYPWORD: {
			std::string variable = "";
			std::string parameters = "";
			std::string prefix = "";
			getwordparameters(wordlist[stub[i].get_wordlistid()], variable, parameters, prefix, rwordlist, correswordlist);
			output += prefix + " " + variable + parameters;
			break;
		}
		case TYPLINE: {
			output += "\n";
			break;
		}
		case TYPTOKN: {
			output += correstokenlist[stub[i].get_wordlistid()];
			break;
		}
		case TYPLCMD: {
			output += latexcommandslist[stub[i].get_wordlistid()];
		}
		}
	}
	std::ofstream saveFile("Save.txt");
	saveFile << output;
	saveFile.close();
    return 0;
}
bool MainWindow::save()
{
    if(painter->isNull()) return true;
    if(curFile.isEmpty()) return saveAs();
    return saveFile(curFile);
}
Beispiel #13
0
void MainWindow::file_SaveAs()
{
    QString fileName = QFileDialog::getSaveFileName(this, tr("Save As"), curFile, tr("SPICE Netlist (*.sp)"));
    if(!fileName.isEmpty())
        saveFile(fileName);
}
Beispiel #14
0
void CV(const char* fileName, const char* type, double A, double v1, double v2, double v3, double v4, double &vdepl, double &evdepl, double &neff, double &eneff, double &w, double &ew, bool savePlots=false) {

  TString simsstring("SIMU");
  TString datastring("DATA");
  int NMAX = 1001;
  if ( ! (simsstring.EqualTo(type) || datastring.EqualTo(type) ) ) {
    std::cerr << "type must be either SIMU or DATA, not -> " << type << "\n";
    exit(2);
  }
  double *C = new double[NMAX];
  double *V = new double[NMAX];
  double *logC = new double[NMAX];
  double *logV = new double[NMAX];
  double *C2 = new double[NMAX];
  double c,v;
  int i = 0;
  std::ifstream file;
  file.open(fileName);
  if ( !file.good() ) {
    std::cerr << "Problems opening file " << fileName << "\n";
    std::cerr << "rdstate =             " << file.rdstate() << "\n";
    exit(3);
  }

  while(1) {
    file >> v >> c;
    if (file.eof()) break;
    if (! (c>0) ) continue; 
    c=fabs(c);
    v=fabs(v);
    C[i]=c;
    V[i]=v;
    logC[i]=TMath::Log10(c);
    logV[i]=TMath::Log10(v);
    C2[i]=1./c/c;
    i++;
    if ( i > NMAX ) {
      std::cerr << "Too many lines: " << i << "\n";
      std::cerr << "Maximum is :    " << NMAX << "\n";
      exit(4);
    }

  } 

  TGraph* grCV = new TGraph(i,V,C);
  grCV->SetName("grCV");
  grCV->SetTitle("");
  TCanvas *c1 = new TCanvas("c1","",2000,1000);
  c1->cd();
  grCV->SetMarkerColor(kBlue);
  grCV->SetMarkerStyle(24);
  grCV->SetMarkerSize(1.2);
  grCV->SetLineColor(kBlue);
  grCV->Draw("AP");
  grCV->GetYaxis()->SetTitle("C [F]");
  grCV->GetXaxis()->SetTitle("V_{bias} [V]");
  c1->SetTicks(1);
  c1->SetGrid(1,1);

  TCanvas *c2 = new TCanvas("c2","",2000,1000);
  c2->cd();
  TGraph* grlogClogV = new TGraph(i,logV,logC);
  grlogClogV->SetName("grlogClogV");
  grlogClogV->SetTitle("");
  grlogClogV->SetMarkerColor(kBlack);
  grlogClogV->SetMarkerStyle(24);
  grlogClogV->SetMarkerSize(1.2);
  grlogClogV->SetLineColor(kBlack);
  grlogClogV->Draw("AP");
  grlogClogV->GetYaxis()->SetTitle("log_{10}(C/F)");
  grlogClogV->GetXaxis()->SetTitle("log_{10}(V_{bias}/V)");
  c2->SetTicks(1);
  c2->SetGrid(1,1);

  double logv1 = TMath::Log10(v1);
  double logv2 = TMath::Log10(v2);
  double logv3 = TMath::Log10(v3);
  double logv4 = TMath::Log10(v4);

  TF1 *loglin1 = new TF1("loglin1","[0]+[1]*x",logv1,logv2);
  TF1 *loglin2 = new TF1("loglin2","[0]+[1]*x",logv3,logv4);
  loglin1->SetLineColor(kRed);
  loglin2->SetLineColor(kBlue);
  grlogClogV->Fit("loglin1","R","",logv1,logv2);
  grlogClogV->Fit("loglin2","R+","",logv3,logv4);

  double logq1 = loglin1->GetParameter(0);
  double logq2 = loglin2->GetParameter(0);
  double logm1 = loglin1->GetParameter(1);
  double logm2 = loglin2->GetParameter(1);

  double elogq1 = loglin1->GetParError(0);
  double elogq2 = loglin2->GetParError(0);
  double elogm1 = loglin1->GetParError(1);
  double elogm2 = loglin2->GetParError(1);

  assert((logm1-logm2)!=0);
  double logvdep = (logq1-logq2)/(logm2-logm1);
  vdepl = TMath::Power(10.,logvdep);
  double Deltam = sqrt(TMath::Power(elogm1,2.)+TMath::Power(elogm2,2.));
  double Deltaq = sqrt(TMath::Power(elogq1,2.)+TMath::Power(elogq2,2.));

  evdepl = sqrt(TMath::Power(Deltaq,2.)/TMath::Power((logm2-logm1),2.) + TMath::Power(Deltam,2.)*TMath::Power((logq1-logq2),2.)/TMath::Power((logm2-logm1),2.));

  evdepl = TMath::Power(10.,evdepl);

  TF1 *flog1 = new TF1("flog1","[0]+[1]*x",logv1*0.8,logv2*1.2);
  TF1 *flog2 = new TF1("flog2","[0]+[1]*x",logv3*0.8,logv4*1.2);
  flog1->SetParameters(logq1,logm1);
  flog2->SetParameters(logq2,logm2);
  flog1->SetLineStyle(7);
  flog1->SetLineColor(loglin1->GetLineColor());
  flog2->SetLineStyle(kDashed);
  flog2->SetLineColor(loglin2->GetLineColor());
  grlogClogV->Draw("AP");
  flog1->Draw("same");
  flog2->Draw("same");
  loglin1->Draw("same");
  loglin2->Draw("same");


  TCanvas *c3 = new TCanvas("c3","",2000,1000);
  c3->cd();
  TGraph *grC2V = new TGraph(i,V,C2);
  grC2V->SetName("grC2V");
  grC2V->SetTitle("");
  grC2V->SetMarkerColor(kBlue);
  grC2V->SetMarkerStyle(24);
  grC2V->SetMarkerSize(1.2);
  grC2V->SetLineColor(kBlue);
  grC2V->Draw("AP");
  grC2V->GetYaxis()->SetTitle("C^{-2} [F^{-2}]");
  grC2V->GetXaxis()->SetTitle("V_{bias} [V]");
  c3->SetTicks(1);
  c3->SetGrid(1,1);

  grC2V->Fit("pol1","R","",v1,v2);
  TF1 *lin = (TF1*)gROOT->GetFunction("pol1");
  lin->SetLineColor(kRed);

  double C2der = lin->GetParameter(1);
  double eC2der = lin->GetParError(1);

  neff = 2./A/A/q0/eR/e0/C2der;
  eneff = 2./A/A/q0/eR/e0/C2der/C2der*eC2der;

  w = TMath::Power(2.*eR*e0*vdepl/q0/neff,0.5);

  double ewA = 2*eR*e0/q0;
  ewA = TMath::Power(ewA,0.5);

  double ewNeff = 0.5*ewA*TMath::Power(vdepl,0.5)*TMath::Power(neff,-1.5)*eneff;
  double ewV = 0.5*ewA*TMath::Power(vdepl,-0.5)*TMath::Power(neff,-0.5)*evdepl;

  ew = TMath::Sqrt(ewNeff*ewNeff+ewV*ewV);

  std::cout << "v1 = " << v1 << " V\n"; 
  std::cout << "v2 = " << v2 << " V\n"; 
  std::cout << "v3 = " << v3 << " V\n"; 
  std::cout << "v4 = " << v4 << " V\n"; 

  std::cout << "vdepl = " << vdepl << " V \n";
  std::cout << "evdepl = " << evdepl << " V \n";

  std::cout << "neff = " << neff << " 1./cm^3\n";
  std::cout << "eneff = " << eneff << " 1./cm^3\n";
  std::cout << "w = " << w*1e+4 << " um\n";
  std::cout << "ew = " << ew*1e+4 << " um\n";

  file.close();

  if ( savePlots == true ) {
    std::cout << "I will save plots\n";
    TString saveFile(fileName);
    TString cvFile = saveFile;
    cvFile.ReplaceAll(".dat","_CV.png");
    TString c2vFile = saveFile;
    c2vFile.ReplaceAll(".dat","_C2V.png");
    TString logclogvFile = saveFile;
    logclogvFile.ReplaceAll(".dat","_logClogV.png");
    c1->Draw();
    c1->SaveAs(cvFile.Data());
    c2->Draw();
    c2->SaveAs(logclogvFile.Data());
    c3->Draw();
    c3->SaveAs(c2vFile.Data());
  }

} 
Beispiel #15
0
void MainWindow::initial()
{
    my_sync_widget->setWindowModality(Qt::WindowModal);
    my_sync_widget->hide();

    connect(my_sync_widget, SIGNAL(getSaveFile(QString&)), this, SLOT(syncSaveFile(QString&)));
    connect(my_sync_widget, SIGNAL(enableServiceButton(QString&)), this, SLOT(serviceAdded(QString&)));
    connect(this, SIGNAL(syncClickEmit()), my_sync_widget, SLOT(syncFiles()));
    connect(my_sync_widget, SIGNAL(openXml(QString&)), this, SLOT(openXmlRecv(QString&)));

    connect(my_sync_widget, SIGNAL(dboxAuthResult(bool)), this, SLOT(dboxAuthStatus(bool)));
    connect(my_sync_widget, SIGNAL(dboxRecvResult(bool)), this, SLOT(dboxRecvStatus(bool)));
    connect(my_sync_widget, SIGNAL(dboxSendResult(bool)), this, SLOT(dboxSendStatus(bool)));

    connect(my_sync_widget, SIGNAL(googleAuthResult(bool)), this, SLOT(googleAuthStatus(bool)));
    connect(my_sync_widget, SIGNAL(googleRecvResult(bool)), this, SLOT(googleRecvStatus(bool)));
    connect(my_sync_widget, SIGNAL(googleSendResult(bool)), this, SLOT(googleSendStatus(bool)));

    fileMenu = menuBar()->addMenu(tr("&File"));

    newList = new QAction( tr("&New lists..."), this );
    newList->setShortcuts(QKeySequence::New);
    fileMenu->addAction(newList);
    connect(newList, SIGNAL(triggered()),
            this->my_task_list,SLOT(new_list()));

    fileMenu->addSeparator();
    loadAction = new QAction(tr("&Open XML..."), this);
    loadAction->setShortcuts(QKeySequence::Open);
    fileMenu->addAction(loadAction);
    connect(loadAction, SIGNAL(triggered()),
            this, SLOT(loadFile()));

    saveAction = new QAction( tr("&Save..."), this );
    saveAction->setShortcuts(QKeySequence::Save);
    fileMenu->addAction(saveAction);
    connect(saveAction, SIGNAL(triggered()),
            this, SLOT(saveFile()));

    saveAsAction = new QAction( tr("&Save as..."), this );
    //saveAsAction->setShortcuts(QKeySequence::SaveAs);
    fileMenu->addAction(saveAsAction);
    connect(saveAsAction, SIGNAL(triggered()),
            this, SLOT(saveasFile()));

    fileMenu->addSeparator();


    printAction = new QAction(tr("&Print"),this);
    printAction->setShortcuts(QKeySequence::Print);
    fileMenu->addAction(printAction);
    connect(printAction, SIGNAL(triggered()),
            this,SLOT(print()));

    fileMenu->addSeparator();

    exitAction = new QAction(tr("&Exit"), this);
    fileMenu->addAction(exitAction);
    connect(exitAction, SIGNAL(triggered()),
            this, SLOT(close()));

    OptMenu = menuBar()->addMenu(tr("&Options"));

    change_font = new QAction(tr("&Change Font"),this);
    OptMenu->addAction(change_font);

    display_note = new QAction(tr("&Display/Hide Note"), this);
    OptMenu->addAction(display_note);

    search_for= new QAction(tr("&Search"),this);
    search_for->setShortcut(QKeySequence::Find);
    OptMenu->addAction(search_for);
    connect(search_for,SIGNAL(triggered()),this,SLOT(search_start()));

    Template = menuBar()->addMenu(tr("&Template"));

    new_grocery = new QAction(tr("&Groceries"),this);
    Template->addAction(new_grocery);

    new_week_task = new QAction(tr("&Weekly Task"),this);
    Template->addAction(new_week_task);


    Sync = menuBar()->addMenu(tr("&Sync Menu"));

    new_service = new QAction(tr("&Add Service"), this);
    Sync->addAction(new_service);
    sync_service = new QAction(tr("&Sync Services (On)"), this);
    Sync->addAction(sync_service);
    sync_service_off = new QAction(tr("&Sync Services Off"), this);
    Sync->addAction(sync_service_off);
    send_service = new QAction(tr("&Send Current File"), this);
    Sync->addAction(send_service);
    get_service = new QAction(tr("&Get Dropbox Files"), this);
    Sync->addAction(get_service);
    send_service_gtask = new QAction(tr("&Send Current File (GTask)"), this);
    Sync->addAction(send_service_gtask);
    get_service_gtask = new QAction(tr("&Get GTask Files"), this);
    Sync->addAction(get_service_gtask);

    sync_service->setDisabled(true);
    send_service->setDisabled(true);
    sync_service_off->setDisabled(true);
    get_service->setDisabled(true);
    send_service_gtask->setDisabled(true);
    get_service_gtask->setDisabled(true);

    addTask = new QPushButton( tr("Add Task") );
    delTask = new QPushButton( tr("Delete") );
    editTask = new QPushButton( tr("Edit Task") );
    pop_up = new QPushButton(tr("Pop Task Up"));
    move_down = new QPushButton(tr("Move Task Down"));
    search_button = new QPushButton(tr("Search"));

    QWidget *main_widget = new QWidget;

    QVBoxLayout *main_layout = new QVBoxLayout;
    QHBoxLayout *button_layout1 = new QHBoxLayout;
    QHBoxLayout *button_layout2 = new QHBoxLayout;

    //here is the list name area
    //main_layout->addWidget( new QLabel(tr("Lists name")),0,Qt::AlignCenter );
    //main_layout->addWidget(my_task_list->lists_name);


    this->my_task_list->setColumnCount(5);
    QStringList tmp_l;
    tmp_l << "Name" << "Note" << "Tag" << "Due Date" << "Status";
    this->my_task_list->setHeaderLabels(tmp_l );

    this->my_task_list->setEditTriggers(QAbstractItemView::DoubleClicked);
    this->my_task_list->setSelectionMode(QAbstractItemView::SingleSelection);
    this->my_task_list->setSelectionBehavior(QAbstractItemView::SelectRows);
    //here is the table content
    /*QStandardItemModel *tmp_mod = my_task_list->mod;
    tmp_mod->setColumnCount(4);
    tmp_mod->setHeaderData(0, Qt::Horizontal, tr("Name"));
    tmp_mod->setHeaderData(1,Qt::Horizontal, tr("Note"));
    tmp_mod->setHeaderData(2,Qt::Horizontal, tr("Due date"));
    tmp_mod->setHeaderData(3,Qt::Horizontal, tr("Status"));
    my_task_list->table->setModel(tmp_mod);
    my_task_list->table->setEditTriggers(QAbstractItemView::DoubleClicked);
    my_task_list->table->setSelectionMode(QAbstractItemView::SingleSelection);
    my_task_list->table->setSelectionBehavior(QAbstractItemView::SelectRows);*/

    /*QTreeWidgetItem* task_child = new QTreeWidgetItem(this->my_task_list,0);
    task_child->setText(0,"a");
    this->my_task_list->addTopLevelItem(task_child);
    QTreeWidgetItem* task_child1 = new QTreeWidgetItem(task_child,1);
    task_child1->setText(0,"1");
    QTreeWidgetItem* task_child2 = new QTreeWidgetItem(task_child,1);
    task_child2->setText(0,"2");
    QTreeWidgetItem* task_child3 = new QTreeWidgetItem(task_child,1);
    task_child3->setText(0,"3");
    task_child->addChild(task_child1);
        task_child->addChild(task_child2);
            task_child->addChild(task_child3);
            QTreeWidgetItem* task_child4 = new QTreeWidgetItem(task_child,1);
            task_child4->setText(0,"0");
            task_child->insertChild(-2,task_child4);
    */


    main_layout->addWidget( new QLabel(tr("Current Lists")),0,Qt::AlignCenter );
    main_layout->addWidget(this->my_task_list);

    button_layout1->addWidget(addTask);
    button_layout1->addWidget(delTask);
    button_layout1->addWidget(editTask);

    button_layout2->addWidget(pop_up);
    button_layout2->addWidget(move_down);
    button_layout2->addWidget(search_button);

    main_layout->addLayout(button_layout1);
    main_layout->addLayout(button_layout2);
    main_widget->setLayout(main_layout);
    main_widget->setMinimumSize(520,500);
    this->setCentralWidget(main_widget);

    //connection
    connect(addTask, SIGNAL(clicked()),
            this->my_task_list,SLOT(addTask()));

    connect(delTask, SIGNAL(clicked()),
            this->my_task_list,SLOT(delTask()));

    connect(editTask, SIGNAL(clicked()),
            this->my_task_list, SLOT(editTask()));

    connect(display_note, SIGNAL(triggered()),
            this->my_task_list, SLOT(show_hide_Note()));//the action one in the menu

    connect(change_font, SIGNAL(triggered()),
            this->my_task_list, SLOT(changeFont()));

    connect(pop_up, SIGNAL(clicked()),
            this->my_task_list, SLOT(pop_up()));

    connect(move_down, SIGNAL(clicked()),
            this->my_task_list, SLOT(move_down()));

    connect(new_grocery, SIGNAL(triggered()),
            this->my_task_list, SLOT(grocery()));

    connect(new_week_task, SIGNAL(triggered()),
            this->my_task_list, SLOT(week_task()));

    connect(new_service, SIGNAL(triggered()),
            this, SLOT(newServiceClick()));

    connect(sync_service, SIGNAL(triggered()),
            this, SLOT(syncClick()));
    connect(sync_service_off, SIGNAL(triggered()),
            this, SLOT(syncClickOff()));
    connect(send_service, SIGNAL(triggered()),
            this->my_sync_widget, SLOT(sendFiles()));
    connect(get_service, SIGNAL(triggered()),
            this->my_sync_widget, SLOT(getFiles()));
    connect(send_service_gtask, SIGNAL(triggered()),
            this->my_sync_widget, SLOT(sendFilesGTask()));
    connect(get_service_gtask, SIGNAL(triggered()),
            this->my_sync_widget, SLOT(getFilesGTask()));

    connect(search_button, SIGNAL(clicked()), this, SLOT(search_start()));

}
/*
 * Write a tar file containing the specified files.
 */
static void
writeTarFile(int fileCount, const char ** fileTable)
{
	struct	stat	statbuf;

	errorFlag = FALSE;

	/*
	 * Make sure there is at least one file specified.
	 */
	if (fileCount <= 0)
	{
		fprintf(stderr, "No files specified to be saved\n");

		return;
	}

	/*
	 * Create the tar file for writing.
	 */
	tarFd = open(tarName, O_WRONLY | O_CREAT | O_TRUNC, 0666);

	if (tarFd < 0)
	{
		perror(tarName);

		return;
	}

	/*
	 * Get the device and inode of the tar file for checking later.
	 */
	if (fstat(tarFd, &statbuf) < 0)
	{
		perror(tarName);

		goto done;
	}

	tarDev = statbuf.st_dev;
	tarInode = statbuf.st_ino;

	/*
	 * Append each file name into the archive file.
	 * Follow symbolic links for these top level file names.
	 */
	while (!intFlag && !errorFlag && (fileCount-- > 0))
	{
		saveFile(*fileTable++, FALSE);
	}

	if (intFlag)
		fprintf(stderr, "Interrupted - aborting archiving\n");

	/*
	 * Now write an empty block of zeroes to end the archive.
	 */
	writeTarBlock("", 1);


done:
	/*
	 * Close the tar file and check for errors if it was opened.
	 */
	if ((tarFd >= 0) && (close(tarFd) < 0))
		perror(tarName);
}
Beispiel #17
0
int main(int argc, char *argv[])
{
    QApplication a(argc, argv);

    QCommandLineParser parser;
    parser.addHelpOption();
    parser.addOptions({
            { "nogui", QString("Using command line arguments, do not show GUI.") },
            { { "p", "path" }, QString("Path for job files or shape files."), QString("path") },
            { { "g", "align" }, QString("Input is not aligned. Find lowest cost alignment.") },
            { { "s", "sourceShape" }, QString("Path for source shape file."), QString("source") },
            { { "t", "targetShape" }, QString("Path for target shape file."), QString("target") },
            { { "a", "auto" }, QString("Automatically try to find initial correspondence. Not used for job files.") },
			{ { "j", "job" }, QString("Job file to load."), QString("job") },
			{ { "f", "folder" }, QString("Folder for a shape dataset."), QString("folder") },
            { { "z", "output" }, QString("Folder for output JSON file."), QString("output") },
			{ { "q", "quiet" }, QString("Skip visualization.") },
            { { "m", "asymmetry" }, QString("Ignore symmetry groups. Used for evaluation.") },

            /* Actual paramteres */
            { { "k", "k" }, QString("(k) parameter for DP search."), QString("k") },
            { { "o", "roundtrip" }, QString("Compute least cost from source to target, and target to source.") },
            { { "c", "cut" }, QString("Allow part cuts/joins.") },

			/* Experiments */
			{ { "e", "experiment" }, QString("Perform hard coded experiments.") },
	});

    if (!parser.parse(QCoreApplication::arguments())) {
        QString errorText = parser.errorText();
        std::cout << qPrintable(errorText);
        return CommandLineError;
    }
	else
		parser.process(a);

	QString path = parser.value("p");
	QDir::setCurrent(path);

	/// Experiments:
	if (parser.isSet("e"))
	{
		QVariantMap options;
        //options["k"].setValue(6);
        //options["isQuietMode"].setValue(true);
		options["isOutputMatching"].setValue(true);
		options["isSaveReport"].setValue(true);
		options["isLogJobs"].setValue(true);

		QString sourceShape = "C:/Development/GeoTopo/standalone/ChairWood2/Woodchair2.xml";
		QString targetShape = "C:/Development/GeoTopo/standalone/chairVK2110/chair2110.xml";

		srand(time(nullptr));

        for (int i = 0; i < 1; i++)
		{
			auto bp = QSharedPointer<BatchProcess>(new BatchProcess(sourceShape, targetShape, options));
			bp->jobUID = (double(rand()) / RAND_MAX) * 10;
			bp->run();

			for (auto & report : bp->jobReports){
				int time = report["search_time"].toInt();
				double c = report["min_cost"].toDouble();

				std::cout << "cost = " << c << " , time = " << time << std::endl;
			}

			//std::swap(sourceShape, targetShape);
		}

		return 0;
	}

    /// Process shape sets:
    if(parser.isSet("folder"))
    {
		QElapsedTimer timer; timer.start();

        QString dataset = parser.value("folder");
        QDir d("");
        QString dir_name = QDir(dataset).dirName();

		// 1) get sorted set of pairs to compare
        QVector< QPair<int, int> > shapePairs;
		auto folders = shapesInDataset(dataset);
		auto folderKeys = folders.keys();
		for (int i = 0; i < folderKeys.size(); i++)
			for (int j = i + 1; j < folderKeys.size(); j++)
                shapePairs << qMakePair(i,j);
		int shapePairsCount = shapePairs.size();
		int curShapePair = 0;

        QMap< QString,QPair<int,int> > pair_idx;

		// 2) perform correspondence for shape pairs
		{
			// Remove previous log file
			d.remove("log.txt");

			// go over pairs
			for (auto shapePair : shapePairs)
			{
				QProcess p;
                QString source = folders[folders.keys().at(shapePair.first)]["graphFile"].toString();
                QString target = folders[folders.keys().at(shapePair.second)]["graphFile"].toString();

				auto sg = QFileInfo(source).baseName();
				auto tg = QFileInfo(target).baseName();

                pair_idx[sg+tg] = qMakePair(shapePair.first, shapePair.second);

				std::cout << QString("Now: %1 / %2").arg(sg).arg(tg).leftJustified(35, ' ', true).toStdString();

				QStringList pargs;

                // Inputs
				pargs << "-s" << source << "-t" << target;	

                // Forward search options
                if (parser.isSet("o")) pargs << "-o";
                if (parser.isSet("k")) pargs << "-k" << parser.value("k");
				if (parser.isSet("q")) pargs << "-q";
                if (parser.isSet("c")) pargs << "-c";
                if (parser.isSet("m")) pargs << "-m";

                // Execute as a seperate process
				p.start(a.applicationFilePath(), pargs);
				p.waitForFinished(-1);

                // Show progress to user
				auto percent = (double(curShapePair++) / shapePairsCount) * 100.0;
				std::cout << QString("[%1 %] - %2 - ").arg((int)percent).arg(shapePairsCount-curShapePair).toStdString();
				int secPerPercent = (timer.elapsed() / 1000) / (percent + 1);
				int timeMinLeft = (secPerPercent * (100 - percent)) / 60;
				std::cout << QString("Time (%1s=%2m) ETA(%3m)\n").arg(timer.elapsed() / 1000).arg(timer.elapsed() / 60000).arg(timeMinLeft).toStdString();
			}
		}

		// 3) prepare results folder
		QString job_name = QString("job_%1").arg(QDateTime::currentDateTime().toString("dd_MM_yyyy_hh_mm_ss"));
		d.mkpath(job_name);

        // 4) collect all pair-wise results
		{
            // output sorted set of shape names
			{
                QFile file(d.absolutePath() + "/" + job_name + "/" + "_" + dir_name + "_shapes.txt");
				if (file.open(QIODevice::WriteOnly | QIODevice::Text)){
					QTextStream out(&file);
					for (int i = 0; i < folderKeys.size(); i++)
						out << QString("%1 %2\n").arg(i).arg(folderKeys.at(i));
				}
			}

			// read log and record the minimum costs and correspondence results
			{
				QFile ff(d.absolutePath() + "/" + "log.txt");
				ff.open(QFile::ReadOnly | QFile::Text);
				QTextStream in(&ff);
				auto datasetLogLines = in.readAll().split("\n", QString::SkipEmptyParts);

				// Record final results
                QJsonArray results;

                for(int idx = 0; idx < datasetLogLines.size(); idx++)
                {
                    // Read matching pair info
                    auto log_line = datasetLogLines[idx].split(",", QString::SkipEmptyParts);
                    QJsonObject matching;
                    matching["source"] = log_line.at(0);
                    matching["target"] = log_line.at(1);
                    matching["cost"] = log_line.at(2).toDouble();

                    // Get correspondence data
                    QString correspondenceFile = log_line.at(3);
                    bool isSwapped = (log_line.at(4).toInt() % 2) == 0;
                    QJsonArray correspondence;
                    {
                        // Open correspondence file
                        QFile cf(correspondenceFile);
                        cf.open(QFile::ReadOnly | QFile::Text);
                        QTextStream cfin(&cf);
                        auto corrLines = cfin.readAll().split("\n", QString::SkipEmptyParts);

                        // Read correspondence file (swapping if needed)
                        for (auto line : corrLines)
                        {
                            auto matched_pair = line.split(" ", QString::SkipEmptyParts);
                            QString sid = matched_pair.at(0);
                            QString tid = matched_pair.at(1);
                            if (isSwapped) std::swap(sid, tid);

                            QJsonArray part_pair;
                            part_pair.push_back(sid);
                            part_pair.push_back(tid);
                            correspondence.push_back(part_pair);
                        }
                    }
                    matching["correspondence"] = correspondence;

                    // Thumbnail files if any
                    QString correspondenceThumb = log_line.back();
                    if(correspondenceThumb != "null"){
                        QString targetThumb = QFileInfo(correspondenceThumb).fileName();
                        targetThumb = QString(d.absolutePath() + "/" + job_name + "/" + targetThumb);
                        QFile::copy(correspondenceThumb, targetThumb);
                        matching["thumbnail"] = targetThumb;
                    }

                    // indexing
                    auto sg = QFileInfo(log_line.at(0)).baseName();
                    auto tg = QFileInfo(log_line.at(1)).baseName();
                    auto pi = pair_idx[sg+tg];
                    matching["i"] = pi.first;
                    matching["j"] = pi.second;

                    // Record result
                    results.push_back(matching);
                }

				// Write all results in JSON format
				{
					QJsonDocument saveDoc(results);

                    QString jsonFilename = d.absolutePath() + "/" + job_name + "/_" + dir_name + "_corr.json";

                    // User specified output folder
                    if(parser.isSet("output")) jsonFilename = parser.value("output") + "/" + dir_name + "_corr.json";

                    QFile saveFile( jsonFilename );
                    saveFile.open( QIODevice::WriteOnly );
                    saveFile.write( saveDoc.toJson() );
				}
			}
		}

		return folders.size();
    }

	MainWindow w;
	//w.show();

    /// Here we perform the actual pair-wise correspondence:
    QString jobs_filename;

    if(parser.isSet("nogui") || parser.isSet("auto") || parser.isSet("sourceShape"))
    {
        if (parser.isSet("auto") || parser.isSet("sourceShape") || parser.isSet("targetShape"))
		{
			QString sourceShape = parser.value("sourceShape");
			QString targetShape = parser.value("targetShape");
			QVariantMap options;

            if(parser.isSet("g")) options["align"].setValue(true);
            if(parser.isSet("o")) options["roundtrip"].setValue(true);
            if(parser.isSet("k")) options["k"].setValue(parser.value("k").toInt());
			if(parser.isSet("q")) options["isQuietMode"].setValue(true);
            if(parser.isSet("c")) options["isAllowCutsJoins"].setValue(true);
            if(parser.isSet("m")) options["isIgnoreSymmetryGroups"].setValue(true);

            if(options["roundtrip"].toBool() || options["align"].toBool())
			{
				options["isManyTypesJobs"].setValue(true);
				options["isOutputMatching"].setValue(true);

				QTimer::singleShot(1, [sourceShape, targetShape, options]
				{
					int numJobs = 0;

					auto cur_options = options;

					QVector< QVector<QVariantMap> > reports;

					int numIter = 1;

					// Command line now only supports two tests.. GUI has more options
					if (cur_options["align"].toBool()) numIter = 2;

					for (int iter = 0; iter < numIter; iter++)
					{
						auto bp = QSharedPointer<BatchProcess>(new BatchProcess(sourceShape, targetShape, cur_options));

						bp->jobUID = numJobs++;
						bp->run();

						reports << bp->jobReports;

						if (cur_options["roundtrip"].toBool())
						{
							auto bp2 = QSharedPointer<BatchProcess>(new BatchProcess(targetShape, sourceShape, cur_options));

							bp2->jobUID = numJobs++;
							bp2->run();

							reports << bp2->jobReports;
						}

						cur_options["isFlip"].setValue(true);
					}

					// Look at reports
					double minEnergy = 1.0;
					int totalTime = 0;
					QVariantMap minJob;
					for (auto & reportVec : reports)
					{
						for (auto & report : reportVec)
						{
							totalTime += report["search_time"].toInt();

							double c = report["min_cost"].toDouble();
							if (c < minEnergy){
								minEnergy = c;
								minJob = report;
							}
						}
					}

					std::cout << "\nJobs computed: " << numJobs << "\n";
					std::cout << minEnergy << " - " << qPrintable(minJob["img_file"].toString());

					// Aggregate results
					{
						QFile file("log.txt");
						if (file.open(QIODevice::WriteOnly | QIODevice::Text | QIODevice::Append))
						{
                            QString thumb_filename = minJob["img_file"].toString();

							QTextStream out(&file);
                            out << sourceShape << "," << targetShape << "," << minJob["min_cost"].toDouble() << ","
                                << minJob["match_file"].toString() << "," << minJob["job_uid"].toInt() << ","
                                << (thumb_filename.isEmpty() ? "null" : thumb_filename) << "\n";
						}
                    }
                }); // end of QTimer::singleShot
            }
            else
            {
                auto bp = new BatchProcess(sourceShape, targetShape, options);
                QObject::connect(bp, SIGNAL(allJobsFinished()), &w, SLOT(close()));
                QObject::connect(bp, SIGNAL(finished()), bp, SLOT(deleteLater()));
                bp->start();
            }

			return a.exec();
		}
		else
		{
			jobs_filename = parser.value("job");
			if (jobs_filename.isEmpty()){
				std::cout << "Please provide a job file.";
				return CommandLineError;
			}
		}

		std::cout << "Not enough arguments.";
		return CommandLineError;
    }
    else
	{
		jobs_filename = QFileDialog::getOpenFileName(&w, "Load Jobs", "", "Jobs File (*.json)");
    }

    QTimer::singleShot(0, [&] {
        BatchProcess * bp = new BatchProcess(jobs_filename);
        QObject::connect(bp, SIGNAL(allJobsFinished()), &w, SLOT(close()));
		QObject::connect(bp, SIGNAL(finished()), bp, SLOT(deleteLater()));
        bp->start();
    });

    return a.exec();
}
/*
 * Save a directory and all of its files to the tar file.
 */
static void
saveDirectory(const char * dirName, const struct stat * statbuf)
{
	DIR *		dir;
	struct dirent *	entry;
	BOOL		needSlash;
	char		fullName[PATH_LEN];

	/*
	 * Construct the directory name as used in the tar file by appending
	 * a slash character to it.
	 */
	strcpy(fullName, dirName);
	strcat(fullName, "/");

	/*
	 * Write out the header for the directory entry.
	 */
	writeHeader(fullName, statbuf);

	/*
	 * Open the directory.
	 */
	dir = opendir(dirName);

	if (dir == NULL)
	{
		fprintf(stderr, "Cannot read directory \"%s\": %s\n",
			dirName, strerror(errno));

		return;
	}

	/*
	 * See if a slash is needed.
	 */
	needSlash = (*dirName && (dirName[strlen(dirName) - 1] != '/'));

	/*
	 * Read all of the directory entries and check them,
	 * except for the current and parent directory entries.
	 */
	while (!intFlag && !errorFlag && ((entry = readdir(dir)) != NULL))
	{
		if ((strcmp(entry->d_name, ".") == 0) ||
			(strcmp(entry->d_name, "..") == 0))
		{
			continue;
		}

		/*
		 * Build the full path name to the file.
		 */
		strcpy(fullName, dirName);

		if (needSlash)
			strcat(fullName, "/");

		strcat(fullName, entry->d_name);

		/*
		 * Write this file to the tar file, noticing whether or not
		 * the file is a symbolic link.
		 */
		saveFile(fullName, TRUE);
	}

	/*
	 * All done, close the directory.
	 */
	closedir(dir);
}
Beispiel #19
0
void KMiniEdit::fileSave()
{
  saveFile(url);
}
Beispiel #20
0
/**
 * Constructor.
 * @param window The main application window.
 * @param toolbar The main toolbar
 * @param fileDescription The description of the document file type as it is
 *                        to appear in file dialogs
 * @param fileExtension The file extension of the document file type (do not
 *                      include the period)
 * @param newFileLaunchesDialog True if creating a new file launches a dialog
 *                              to set additional parameters, false otherwise
 */
QQMenuHelper::QQMenuHelper(QMainWindow *window, QToolBar *toolbar,
                           const QString &fileDescription,
                           const QString &fileExtension,
                           bool newFileLaunchesDialog)
 : QObject(window), mainWindow(window), mainToolBar(toolbar),
   description(fileDescription), extension(fileExtension), file(0), help(0)
{
    QChar ellipsis(8230);

    // Some phrases need to be handled differently on Mac OS X
    QString prefsText = menuText(tr("Pr&eferences"));
    QString macPrefsText = QMenuBar::tr("Preferences");
    QString quitText = menuText(tr("&Quit"));
    QString macQuitText = QMenuBar::tr("Quit %1");
    QString helpText = tr("Help Contents");
    QString macHelpText = tr("%1 Help").arg(qApp->applicationName());
    QString aboutText = menuText(tr("&About %1")).arg(qApp->applicationName());
    QString macAboutText = QMenuBar::tr("About %1");
    QString aboutQtText = menuText(tr("About &Qt"));
    QString macAboutQtText = QMenuBar::tr("About Qt");
#ifdef Q_WS_MAC
    prefsText = macPrefsText;
    quitText = macQuitText;
    helpText = macHelpText;
    aboutText = macAboutText;
    aboutQtText = macAboutQtText;
#endif

    // File menu actions
    QString fileNewText(tr("&New"));
    if (newFileLaunchesDialog) {
      fileNewText += ellipsis;
    }
    fileNewAction = new QAction(QIcon(":/icons/new.png"), menuText(fileNewText), window);
    fileNewAction->setStatusTip(tr("Create a new file"));
    fileNewAction->setToolTip(fileNewAction->statusTip());
    fileNewAction->setShortcut(QKeySequence::New);
    connect(fileNewAction, SIGNAL(triggered()), this, SLOT(emitNewFile()));

    fileOpenAction = new QAction(QIcon(":/icons/open.png"), menuText(tr("&Open")) + ellipsis, window);
    fileOpenAction->setStatusTip(tr("Open an existing file"));
    fileOpenAction->setToolTip(fileOpenAction->statusTip());
    fileOpenAction->setShortcut(QKeySequence::Open);
    connect(fileOpenAction, SIGNAL(triggered()), this, SLOT(emitOpenFile()));

    quitAction = new QAction(QIcon(":/icons/quit.png"), quitText, window);
    quitAction->setStatusTip(tr("Quit the application"));
#if !defined(Q_WS_HILDON)
    quitAction->setShortcut(QKeySequence::Quit);
#endif
    quitAction->setMenuRole(QAction::QuitRole);
    connect(quitAction, SIGNAL(triggered()), this, SIGNAL(quit()));

    fileSaveAction = new QAction(QIcon(":/icons/save.png"), menuText(tr("&Save")), window);
    fileSaveAction->setStatusTip(tr("Save the current file"));
    fileSaveAction->setToolTip(fileSaveAction->statusTip());
    fileSaveAction->setShortcut(QKeySequence::Save);
    connect(fileSaveAction, SIGNAL(triggered()), this, SIGNAL(saveFile()));

    for (int i = 0; i < MAX_RECENT_FILES; i++) {
        // we'll set the actual paths later; just need actions that stick
        // around after a file is opened
        recentActions[i] = new QAction("", window);
        connect(recentActions[i], SIGNAL(triggered()), this, SLOT(openRecent()));
    }

    fileSeparatorAction = new QAction(this);
    fileSeparatorAction->setSeparator(true);

    closeAction = new QAction(QIcon(":/icons/close.png"), menuText(tr("&Close")), window);
    closeAction->setStatusTip(tr("Close the current file"));
    closeAction->setShortcut(QKeySequence::Close);
    connect(closeAction, SIGNAL(triggered()), this, SIGNAL(closeFile()));

    prefsAction = new QAction(prefsText, window);
    prefsAction->setStatusTip(tr("Change the application settings"));
#if !defined(Q_WS_HILDON)
    prefsAction->setShortcut(QKeySequence::Preferences);
#endif
    prefsAction->setMenuRole(QAction::PreferencesRole);
    connect(prefsAction, SIGNAL(triggered()), this, SIGNAL(editPreferences()));

#if defined(Q_WS_MAC) || defined(Q_WS_HILDON) || defined(Q_WS_MAEMO_5)
    fileNewAction->setIconVisibleInMenu(false);
    fileOpenAction->setIconVisibleInMenu(false);
    quitAction->setIconVisibleInMenu(false);
    fileSaveAction->setIconVisibleInMenu(false);
    closeAction->setIconVisibleInMenu(false);
#endif
#if defined(Q_WS_MAC)
    docIcon = QIcon(":/icons/document_small.png");
    modifiedDocIcon = QIcon(darkenPixmap(QPixmap(":/icons/document_small.png")));
#endif

    // File menu basic setup
    file = new QMenu(menuText(tr("&File")), window);
    recent = new QMenu(menuText(tr("Open &Recent")), window);
    file->addAction(fileNewAction);
    file->addAction(fileOpenAction);
    file->addMenu(recent);
    file->addAction(fileSaveAction);
    file->addAction(fileSeparatorAction);
    file->addAction(closeAction);
    file->addAction(prefsAction);
    insertionPoint = fileSeparatorAction;
#if !defined(Q_WS_MAC)
    file->addSeparator();
#endif
    file->addAction(quitAction);
#if !defined(Q_WS_HILDON) && !defined(Q_WS_MAEMO_5)
    window->menuBar()->addMenu(file);
#endif

    // Help menu actions
    helpAction = new QAction(helpText, window);
    helpAction->setStatusTip(helpText);
    helpAction->setShortcut(QKeySequence::HelpContents);
    connect(helpAction, SIGNAL(triggered()), this, SLOT(showHelp()));

    aboutAction = new QAction(aboutText, window);
    aboutAction->setStatusTip(aboutText);
    aboutAction->setMenuRole(QAction::AboutRole);
    connect(aboutAction, SIGNAL(triggered()), this, SIGNAL(aboutApplication()));

    aboutQtAction = new QAction(aboutQtText, window);
    aboutQtAction->setStatusTip(aboutQtText);
    aboutQtAction->setMenuRole(QAction::AboutQtRole);
    connect(aboutQtAction, SIGNAL(triggered()), this, SLOT(aboutQt()));

    // Help menu setup
    help = new QMenu(menuText(tr("&Help")), window);
#if !defined(Q_WS_HILDON) && !defined(Q_WS_MAEMO_5)
    help->addAction(helpAction);
#if !defined(Q_WS_MAC)
    // skip this on the mac, since both "About.." actions get moved elsewhere
    help->addSeparator();
#endif
    help->addAction(aboutAction);
    help->addAction(aboutQtAction);
    window->menuBar()->addMenu(help);
#endif

    // toolbar setup
    addToToolBar(fileNewAction);
    addToToolBar(fileOpenAction);
    addToToolBar(fileSaveAction);

    // build the actions hash
    actions[New] = fileNewAction;
    actions[Open] = fileOpenAction;
    actions[Save] = fileSaveAction;
    actions[Recent1] = recentActions[0];
    actions[Recent2] = recentActions[1];
    actions[Recent3] = recentActions[2];
    actions[Recent4] = recentActions[3];
    actions[Recent5] = recentActions[4];
    actions[Separator] = fileSeparatorAction;
    actions[Close] = closeAction;
    actions[Preferences] = prefsAction;
    actions[Quit] = quitAction;
    actions[Help] = helpAction;
    actions[About] = aboutAction;
    actions[AboutQt] = aboutQtAction;
}
Beispiel #21
0
void pSocket::onDataReceived()
{
#ifdef FUNC_DEBUG
    qDebug() << '\n' << Q_FUNC_INFO;
#endif

    auto data = _socket->readAll();

    if (_packetSize == 0) {
        int n = data.indexOf("\n\n");
        if (n == -1) {
            qDebug() << "Wrong data received. Disconnect" << _socket->localAddress();
            _socket->disconnectFromHost();
            return;
        }

        QByteArray header = data.left(n);
        auto content = data.mid(n+2);
        _buffer = content;
        _limit.fetchAndAddAcquire(content.size());
        _packetSize = getValue(header, "size").toInt();
        _protoVersion   = getValue(header, "version");
        _fileType = getValue(header, "type");

        if (_packetSize == 0) {
            qDebug() << "Client trying to send empty data";
            _socket->disconnectFromHost();
        }

        if (_fileType == "" || !Settings::types().contains(_fileType) ) {
            qDebug() << "Sender type is not exist. Disconnect" << _socket->localAddress();
            _socket->disconnectFromHost();
            return;
        }

    } else {
        _buffer += data;
        _limit.fetchAndAddAcquire(data.size());
    }

    if (_buffer.size() > MAX_DATA_SIZE || _limit.loadAcquire() > MAX_DAY_SIZE) {
        qDebug() << "File is too big! Disconnect" << _socket->localAddress();
        _socket->disconnectFromHost();
        _socket->deleteLater();
        return;
    }

#ifdef FUNC_DEBUG
    qDebug() << '\n' << Q_FUNC_INFO << "read";
#endif

    if (_buffer.size() == _packetSize) {

#ifdef FUNC_DEBUG
        qDebug() << '\n' << Q_FUNC_INFO << "emit";
#endif

        _packetSize = 0;
        emit saveFile(_buffer, _fileType);

#ifdef TIME_DEBUG
        qDebug() << dTime->elapsed();
#endif
    }

#ifdef FUNC_DEBUG
    qDebug() << '\n' << Q_FUNC_INFO << "end";
#endif
}
BackgroundWidget::BackgroundWidget(QWidget *parent) :
    QWidget(parent)
{

    this->setWindowTitle("Background");
    this->setWindowIcon(QIcon(":/resources/icons/resources/background.png"));

    zoomInAction = new QAction(QIcon(":/icons/actions/zoom-in.png"), "Zoom In", NULL);
    connect(zoomInAction, SIGNAL(triggered()), this, SLOT(zoomIn()));
    zoomOutAction = new QAction(QIcon(":/icons/actions/zoom-out.png"), "Zoom Out", NULL);
    connect(zoomOutAction, SIGNAL(triggered()), this, SLOT(zoomOut()));
    QAction* openAction = new QAction(QIcon(":/icons/actions/open.png"), "Load from file", NULL);
    connect(openAction, SIGNAL(triggered()), this, SLOT(openFile()));
    QAction* saveAction = new QAction(QIcon(":/icons/actions/save.png"), "Save to file", NULL);
    connect(saveAction, SIGNAL(triggered()), this, SLOT(saveFile()));
    QAction* printAction = new QAction(QIcon(":/icons/actions/print.png"), "Print", NULL);
    connect(printAction, SIGNAL(triggered()), this, SLOT(print()));

    QVBoxLayout* propertiesLayout = new QVBoxLayout();

    QLabel* nameLabel = new QLabel("Name: ");
    QLineEdit* nameEdit = new QLineEdit("bg_0", this);

    QToolBar* toolBar = new QToolBar();
    toolBar->addAction(QIcon(":/icons/actions/accept.png"), "Save Changes");
    toolBar->addAction(openAction);
    toolBar->addAction(saveAction);
    toolBar->addAction(printAction);

    toolBar->addSeparator();
    toolBar->addAction(zoomInAction);
    toolBar->addAction(zoomOutAction);
    toolBar->addSeparator();
    toolBar->addWidget(nameLabel);
    toolBar->addWidget(nameEdit);

    toolBar->setStyleSheet(" QToolBar { height: 18px; width: 18px; icon-size: 18px; } ");

    QCheckBox* smoothCheckBox = new QCheckBox("Smooth", this);
    QCheckBox* transparentCheckBox = new QCheckBox("Transparent", this);
    QCheckBox* preloadCheckBox = new QCheckBox("Preload", this);
    QCheckBox* tilesetCheckBox = new QCheckBox("Tileset", this);

    imageLabel = new QLabel;
    imageLabel->setBackgroundRole(QPalette::Base);
    imageLabel->setSizePolicy(QSizePolicy::Ignored, QSizePolicy::Ignored);
    imageLabel->setScaledContents(true);


    scrollArea = new QScrollArea;
    scrollArea->setBackgroundRole(QPalette::Dark);
    scrollArea->setWidget(imageLabel);
    scrollArea->setAlignment(Qt::AlignHCenter | Qt::AlignVCenter);

    propertiesLayout->addWidget(smoothCheckBox);
    propertiesLayout->addWidget(transparentCheckBox);
    propertiesLayout->addWidget(preloadCheckBox);
    propertiesLayout->addWidget(tilesetCheckBox);
    QSplitter* horizontalSplitter = new QSplitter(this);
    QWidget* propertiesWidget = new QWidget(this, Qt::WindowTitleHint);
    QFormLayout* propertiesFormLayout = new QFormLayout();
    propertiesFormLayout->setLayout(0, QFormLayout::SpanningRole, propertiesLayout);
    propertiesWidget->setLayout(propertiesFormLayout);

    horizontalSplitter->addWidget(propertiesWidget);
    horizontalSplitter->addWidget(scrollArea);
    horizontalSplitter->setStretchFactor(0, 0);
    horizontalSplitter->setStretchFactor(1, 1);

    QVBoxLayout* verticalLayout = new QVBoxLayout();
    verticalLayout->addWidget(toolBar);
    verticalLayout->addWidget(horizontalSplitter);
    QStatusBar* statusBar = new QStatusBar();
    statusBar->showMessage("Width: 0 | Height: 0 | Memory: 0 B | Zoom: 100%");
    statusBar->setSizePolicy(QSizePolicy::Ignored, QSizePolicy::Fixed);
    verticalLayout->addWidget(statusBar);
    verticalLayout->setContentsMargins(2, 2, 2, 2);
    this->setLayout(verticalLayout);
}
Beispiel #23
0
int tool_main(int argc, char** argv) {
    SetupCrashHandler();
    SkCommandLineFlags::Parse(argc, argv);
#if SK_ENABLE_INST_COUNT
    if (FLAGS_leaks) {
        gPrintInstCount = true;
    }
#endif
    SkAutoGraphics ag;

    // First, parse some flags.
    BenchLogger logger;
    if (FLAGS_logFile.count()) {
        logger.SetLogFile(FLAGS_logFile[0]);
    }

    LoggerResultsWriter logWriter(logger, FLAGS_timeFormat[0]);
    MultiResultsWriter writer;
    writer.add(&logWriter);

    SkAutoTDelete<JSONResultsWriter> jsonWriter;
    if (FLAGS_outResultsFile.count()) {
        jsonWriter.reset(SkNEW(JSONResultsWriter(FLAGS_outResultsFile[0])));
        writer.add(jsonWriter.get());
    }

    // Instantiate after all the writers have been added to writer so that we
    // call close() before their destructors are called on the way out.
    CallEnd<MultiResultsWriter> ender(writer);

    const uint8_t alpha = FLAGS_forceBlend ? 0x80 : 0xFF;
    SkTriState::State dither = SkTriState::kDefault;
    for (size_t i = 0; i < 3; i++) {
        if (strcmp(SkTriState::Name[i], FLAGS_forceDither[0]) == 0) {
            dither = static_cast<SkTriState::State>(i);
        }
    }

    BenchMode benchMode = kNormal_BenchMode;
    for (size_t i = 0; i < SK_ARRAY_COUNT(BenchMode_Name); i++) {
        if (strcmp(FLAGS_mode[0], BenchMode_Name[i]) == 0) {
            benchMode = static_cast<BenchMode>(i);
        }
    }

    SkTDArray<int> configs;
    bool runDefaultConfigs = false;
    // Try user-given configs first.
    for (int i = 0; i < FLAGS_config.count(); i++) {
        for (int j = 0; j < static_cast<int>(SK_ARRAY_COUNT(gConfigs)); ++j) {
            if (0 == strcmp(FLAGS_config[i], gConfigs[j].name)) {
                *configs.append() = j;
            } else if (0 == strcmp(FLAGS_config[i], kDefaultsConfigStr)) {
                runDefaultConfigs = true;
            }
        }
    }
    // If there weren't any, fill in with defaults.
    if (runDefaultConfigs) {
        for (int i = 0; i < static_cast<int>(SK_ARRAY_COUNT(gConfigs)); ++i) {
            if (gConfigs[i].runByDefault) {
                *configs.append() = i;
            }
        }
    }
    // Filter out things we can't run.
    if (kNormal_BenchMode != benchMode) {
        // Non-rendering configs only run in normal mode
        for (int i = 0; i < configs.count(); ++i) {
            const Config& config = gConfigs[configs[i]];
            if (Benchmark::kNonRendering_Backend == config.backend) {
                configs.remove(i, 1);
                --i;
            }
        }
    }

#if SK_SUPPORT_GPU
    for (int i = 0; i < configs.count(); ++i) {
        const Config& config = gConfigs[configs[i]];

        if (Benchmark::kGPU_Backend == config.backend) {
            GrContext* context = gContextFactory.get(config.contextType);
            if (NULL == context) {
                SkDebugf("GrContext could not be created for config %s. Config will be skipped.\n",
                    config.name);
                configs.remove(i);
                --i;
                continue;
            }
            if (config.sampleCount > context->getMaxSampleCount()){
                SkDebugf(
                    "Sample count (%d) for config %s is not supported. Config will be skipped.\n",
                    config.sampleCount, config.name);
                configs.remove(i);
                --i;
                continue;
            }
        }
    }
#endif

    // All flags should be parsed now.  Report our settings.
    if (FLAGS_runOnce) {
        logger.logError("bench was run with --runOnce, so we're going to hide the times."
                        " It's for your own good!\n");
    }
    writer.option("mode", FLAGS_mode[0]);
    writer.option("alpha", SkStringPrintf("0x%02X", alpha).c_str());
    writer.option("antialias", SkStringPrintf("%d", FLAGS_forceAA).c_str());
    writer.option("filter", SkStringPrintf("%d", FLAGS_forceFilter).c_str());
    writer.option("dither",  SkTriState::Name[dither]);

    writer.option("rotate", SkStringPrintf("%d", FLAGS_rotate).c_str());
    writer.option("scale", SkStringPrintf("%d", FLAGS_scale).c_str());
    writer.option("clip", SkStringPrintf("%d", FLAGS_clip).c_str());

#if defined(SK_BUILD_FOR_WIN32)
    writer.option("system", "WIN32");
#elif defined(SK_BUILD_FOR_MAC)
    writer.option("system", "MAC");
#elif defined(SK_BUILD_FOR_ANDROID)
    writer.option("system", "ANDROID");
#elif defined(SK_BUILD_FOR_UNIX)
    writer.option("system", "UNIX");
#else
    writer.option("system", "other");
#endif

#if defined(SK_DEBUG)
    writer.option("build", "DEBUG");
#else
    writer.option("build", "RELEASE");
#endif

    // Set texture cache limits if non-default.
    for (size_t i = 0; i < SK_ARRAY_COUNT(gConfigs); ++i) {
#if SK_SUPPORT_GPU
        const Config& config = gConfigs[i];
        if (Benchmark::kGPU_Backend != config.backend) {
            continue;
        }
        GrContext* context = gContextFactory.get(config.contextType);
        if (NULL == context) {
            continue;
        }

        size_t bytes;
        int count;
        context->getResourceCacheLimits(&count, &bytes);
        if (-1 != FLAGS_gpuCacheBytes) {
            bytes = static_cast<size_t>(FLAGS_gpuCacheBytes);
        }
        if (-1 != FLAGS_gpuCacheCount) {
            count = FLAGS_gpuCacheCount;
        }
        context->setResourceCacheLimits(count, bytes);
#endif
    }

    // Run each bench in each configuration it supports and we asked for.
    Iter iter;
    Benchmark* bench;
    while ((bench = iter.next()) != NULL) {
        SkAutoTUnref<Benchmark> benchUnref(bench);
        if (SkCommandLineFlags::ShouldSkip(FLAGS_match, bench->getName())) {
            continue;
        }

        bench->setForceAlpha(alpha);
        bench->setForceAA(FLAGS_forceAA);
        bench->setForceFilter(FLAGS_forceFilter);
        bench->setDither(dither);
        bench->preDraw();

        bool loggedBenchName = false;
        for (int i = 0; i < configs.count(); ++i) {
            const int configIndex = configs[i];
            const Config& config = gConfigs[configIndex];

            if (!bench->isSuitableFor(config.backend)) {
                continue;
            }

            GrContext* context = NULL;
#if SK_SUPPORT_GPU
            SkGLContextHelper* glContext = NULL;
            if (Benchmark::kGPU_Backend == config.backend) {
                context = gContextFactory.get(config.contextType);
                if (NULL == context) {
                    continue;
                }
                glContext = gContextFactory.getGLContext(config.contextType);
            }
#endif

            SkAutoTUnref<SkCanvas> canvas;
            SkAutoTUnref<SkPicture> recordFrom;
            SkPictureRecorder recorderTo;
            const SkIPoint dim = bench->getSize();

            SkAutoTUnref<SkSurface> surface;
            if (Benchmark::kNonRendering_Backend != config.backend) {
                surface.reset(make_surface(config.fColorType,
                                           dim,
                                           config.backend,
                                           config.sampleCount,
                                           context));
                if (!surface.get()) {
                    logger.logError(SkStringPrintf(
                        "Device creation failure for config %s. Will skip.\n", config.name));
                    continue;
                }

                switch(benchMode) {
                    case kDeferredSilent_BenchMode:
                    case kDeferred_BenchMode:
                        canvas.reset(SkDeferredCanvas::Create(surface.get()));
                        break;
                    case kRecord_BenchMode:
                        canvas.reset(SkRef(recorderTo.beginRecording(dim.fX, dim.fY)));
                        break;
                    case kPictureRecord_BenchMode: {
                        SkPictureRecorder recorderFrom;
                        bench->draw(1, recorderFrom.beginRecording(dim.fX, dim.fY));
                        recordFrom.reset(recorderFrom.endRecording());
                        canvas.reset(SkRef(recorderTo.beginRecording(dim.fX, dim.fY)));
                        break;
                    }
                    case kNormal_BenchMode:
                        canvas.reset(SkRef(surface->getCanvas()));
                        break;
                    default:
                        SkASSERT(false);
                }
            }

            if (NULL != canvas) {
                canvas->clear(SK_ColorWHITE);
                if (FLAGS_clip)   {
                    perform_clip(canvas, dim.fX, dim.fY);
                }
                if (FLAGS_scale)  {
                    perform_scale(canvas, dim.fX, dim.fY);
                }
                if (FLAGS_rotate) {
                    perform_rotate(canvas, dim.fX, dim.fY);
                }
            }

            if (!loggedBenchName) {
                loggedBenchName = true;
                writer.bench(bench->getName(), dim.fX, dim.fY);
            }

#if SK_SUPPORT_GPU
            SkGLContextHelper* contextHelper = NULL;
            if (Benchmark::kGPU_Backend == config.backend) {
                contextHelper = gContextFactory.getGLContext(config.contextType);
            }
            BenchTimer timer(contextHelper);
#else
            BenchTimer timer;
#endif

            double previous = std::numeric_limits<double>::infinity();
            bool converged = false;

            // variables used to compute loopsPerFrame
            double frameIntervalTime = 0.0f;
            int frameIntervalTotalLoops = 0;

            bool frameIntervalComputed = false;
            int loopsPerFrame = 0;
            int loopsPerIter = 0;
            if (FLAGS_verbose) { SkDebugf("%s %s: ", bench->getName(), config.name); }
            if (!FLAGS_dryRun) {
                do {
                    // Ramp up 1 -> 2 -> 4 -> 8 -> 16 -> ... -> ~1 billion.
                    loopsPerIter = (loopsPerIter == 0) ? 1 : loopsPerIter * 2;
                    if (loopsPerIter >= (1<<30) || timer.fWall > FLAGS_maxMs) {
                        // If you find it takes more than a billion loops to get up to 20ms of runtime,
                        // you've got a computer clocked at several THz or have a broken benchmark.  ;)
                        //     "1B ought to be enough for anybody."
                        logger.logError(SkStringPrintf(
                            "\nCan't get %s %s to converge in %dms (%d loops)",
                             bench->getName(), config.name, FLAGS_maxMs, loopsPerIter));
                        break;
                    }

                    if ((benchMode == kRecord_BenchMode || benchMode == kPictureRecord_BenchMode)) {
                        // Clear the recorded commands so that they do not accumulate.
                        canvas.reset(SkRef(recorderTo.beginRecording(dim.fX, dim.fY)));
                    }

                    timer.start();
                    // Inner loop that allows us to break the run into smaller
                    // chunks (e.g. frames). This is especially useful for the GPU
                    // as we can flush and/or swap buffers to keep the GPU from
                    // queuing up too much work.
                    for (int loopCount = loopsPerIter; loopCount > 0; ) {
                        // Save and restore around each call to draw() to guarantee a pristine canvas.
                        SkAutoCanvasRestore saveRestore(canvas, true/*also save*/);

                        int loops;
                        if (frameIntervalComputed && loopCount > loopsPerFrame) {
                            loops = loopsPerFrame;
                            loopCount -= loopsPerFrame;
                        } else {
                            loops = loopCount;
                            loopCount = 0;
                        }

                        if (benchMode == kPictureRecord_BenchMode) {
                            recordFrom->draw(canvas);
                        } else {
                            bench->draw(loops, canvas);
                        }

                        if (kDeferredSilent_BenchMode == benchMode) {
                            static_cast<SkDeferredCanvas*>(canvas.get())->silentFlush();
                        } else if (NULL != canvas) {
                            canvas->flush();
                        }

    #if SK_SUPPORT_GPU
                        // swap drawing buffers on each frame to prevent the GPU
                        // from queuing up too much work
                        if (NULL != glContext) {
                            glContext->swapBuffers();
                        }
    #endif
                    }



                    // Stop truncated timers before GL calls complete, and stop the full timers after.
                    timer.truncatedEnd();
    #if SK_SUPPORT_GPU
                    if (NULL != glContext) {
                        context->flush();
                        SK_GL(*glContext, Finish());
                    }
    #endif
                    timer.end();

                    // setup the frame interval for subsequent iterations
                    if (!frameIntervalComputed) {
                        frameIntervalTime += timer.fWall;
                        frameIntervalTotalLoops += loopsPerIter;
                        if (frameIntervalTime >= FLAGS_minMs) {
                            frameIntervalComputed = true;
                            loopsPerFrame =
                              (int)(((double)frameIntervalTotalLoops / frameIntervalTime) * FLAGS_minMs);
                            if (loopsPerFrame < 1) {
                                loopsPerFrame = 1;
                            }
    //                        SkDebugf("  %s has %d loops in %f ms (normalized to %d)\n",
    //                                 bench->getName(), frameIntervalTotalLoops,
    //                                 timer.fWall, loopsPerFrame);
                        }
                    }

                    const double current = timer.fWall / loopsPerIter;
                    if (FLAGS_verbose && current > previous) { SkDebugf("↑"); }
                    if (FLAGS_verbose) { SkDebugf("%.3g ", current); }
                    converged = HasConverged(previous, current, timer.fWall);
                    previous = current;
                } while (!FLAGS_runOnce && !converged);
            }
            if (FLAGS_verbose) { SkDebugf("\n"); }

            if (!FLAGS_dryRun && FLAGS_outDir.count() && Benchmark::kNonRendering_Backend != config.backend) {
                SkAutoTUnref<SkImage> image(surface->newImageSnapshot());
                if (image.get()) {
                    saveFile(bench->getName(), config.name, FLAGS_outDir[0],
                             image);
                }
            }

            if (FLAGS_runOnce) {
                // Let's not mislead ourselves by looking at Debug build or single iteration bench times!
                continue;
            }

            // Normalize to ms per 1000 iterations.
            const double normalize = 1000.0 / loopsPerIter;
            const struct { char shortName; const char* longName; double ms; } times[] = {
                {'w', "msecs",  normalize * timer.fWall},
                {'W', "Wmsecs", normalize * timer.fTruncatedWall},
                {'c', "cmsecs", normalize * timer.fCpu},
                {'C', "Cmsecs", normalize * timer.fTruncatedCpu},
                {'g', "gmsecs", normalize * timer.fGpu},
            };

            writer.config(config.name);
            for (size_t i = 0; i < SK_ARRAY_COUNT(times); i++) {
                if (strchr(FLAGS_timers[0], times[i].shortName) && times[i].ms > 0) {
                    writer.timer(times[i].longName, times[i].ms);
                }
            }
        }
    }
#if SK_SUPPORT_GPU
    gContextFactory.destroyContexts();
#endif
    return 0;
}
Beispiel #24
0
void AutoImportWindow::importImage() {
    
    if(continuous->isChecked()) {
        analyzeImport(true);
    }
    
    if(toBeImported_.isEmpty()) {
        finishExecution();
        return;
    }

    if (imageExecuting_) {
        QString numberExec = imageExecuting_->directory();
        if (!numberExec.isEmpty()) {
            if (dirToRowNumber_.keys().contains(numberExec)) {
                if (dirToRowNumber_[numberExec] < resultsTable_->rowCount()) {
                    if (resultsTable_->item(dirToRowNumber_[numberExec], 0)) {
                        resultsTable_->item(dirToRowNumber_[numberExec], 0)->setIcon(ApplicationData::icon("process_done"));
                    }
                }
            }
        }
    }
    
    QString number;
    number = toBeImported_.keys().first();

    QStringList files = toBeImported_[number];
    toBeImported_.remove(number);
    
    //Get the original file name used for search
    QString baseName = files.first();
    
    //Deduce parameters from baseName
    QMap<QString, QString> fileNameParams = FileNameParserDialog::parseFileName(baseName);
    
    QString importGroup_ = projectData.projectParameterData()->getValue("import_target_group");
    QString importGroupSuffix = projectData.projectParameterData()->getValue("import_target_group_suffix");
    
    //Add suffix to group name
    QString suffix = "";
    
    //case importGroupSuffix=1 => parameter = specimennumber
    if(importGroupSuffix == "1") { 
        //If the file name contains this param take it from there, otherwise search master.cfg 
        if(fileNameParams.contains("specimennumber")) suffix = fileNameParams["specimennumber"];
        else {
            suffix = projectData.projectParameterData()->getValue("specimennumber");
        }
    }
    
    if(suffix == "-") suffix = "";
    
    importGroup_ = importGroup_ + suffix;
    
    if (dirToRowNumber_.keys().contains(number)) {
        if (dirToRowNumber_[number] < resultsTable_->rowCount()) {
            if(resultsTable_->item(dirToRowNumber_[number], 0)) {
                resultsTable_->item(dirToRowNumber_[number], 0)->setIcon(ApplicationData::icon("process_executing"));
                resultsTable_->scrollToItem(resultsTable_->item(dirToRowNumber_[number], 0));
            }
        }
    }
    
    statusLabel_->setText(QString("Currently importing and %2 are in queue...").arg(toBeImported_.keys().size()));
    projectData.projectParameterData()->set("import_imagenumber", number);
    
    //Create dir
    QDir workingDir = QDir(projectData.projectDir().canonicalPath() + "/" + importGroup_ + "/" + number);
    
    //create import group
    projectData.projectDir().mkpath(importGroup_);
    QFile(projectData.projectDir().absolutePath() + "/merge").link("../2dx_master.cfg", projectData.projectDir().absolutePath() + "/" + importGroup_ + "/2dx_master.cfg");
    
    //create Dir
    projectData.projectDir().mkpath(importGroup_ + "/" + number);
    workingDir.mkpath("proc");
    workingDir.mkpath("LOGS");

    //Copy Config File
    projectData.projectParameterData()->saveAs(workingDir.canonicalPath() + "/2dx_image.cfg", true);

    imageExecuting_ = projectData.addImage(importGroup_, number);
    ParametersConfiguration* conf = imageExecuting_->parameters();
    conf->set("imagenumber", number, false);
    
    bool hasAveraged = false;
    bool hasAligned = false;
    bool hasRaw = false;
    
    //Check for the averaged file
    if(files.size() > 1 && !files[1].isEmpty()) {
        conf->set("imagename", "image_2dx", false);
        conf->set("nonmaskimagename", "image_2dx", false);
        conf->set("imagename_original", files[1], false);
        conf->set("import_original_time", QString::number(QFileInfo(files[1]).created().toMSecsSinceEpoch()), false);
        scriptsToBeExecuted_.append("cp -f " + files[1] + " " + workingDir.canonicalPath() + "/" + "image_2dx.mrc");
        if(deleteCheck->isChecked()) scriptsToBeExecuted_.append("rm -f " + files[1]);
        hasAveraged = true;
    }
    
    //Check for aligned file
    if (files.size() > 2 && !files[2].isEmpty()) {
        conf->set("movie_stackname", "movie_aligned", false);
        conf->set("movie_stackname_original", files[2], false);
        conf->set("import_original_time", QString::number(QFileInfo(files[2]).created().toMSecsSinceEpoch()), false);
        scriptsToBeExecuted_.append("cp -f " + files[2] + " " + workingDir.canonicalPath() + "/" + "movie_aligned.mrcs");
        if(deleteCheck->isChecked()) scriptsToBeExecuted_.append("rm -f " + files[2]);
        hasAligned = true;
    }

    //Check for raw file
    if (files.size() > 3 && !files[3].isEmpty()) {
        int rawOption = conf->getVariant("import_rawstack_type").toInt();
        if(rawOption == 1) {
            conf->set("import_rawstack", baseName + '.' + QFileInfo(files[3]).suffix(), false);
            conf->set("import_rawstack_original", files[3], false);
            conf->set("import_original_time", QString::number(QFileInfo(files[3]).created().toMSecsSinceEpoch()), false);
            scriptsToBeExecuted_.append("cp -f " + files[3] + " " + workingDir.canonicalPath() + "/" + baseName + '.' + QFileInfo(files[3]).suffix());
            if(deleteCheck->isChecked()) scriptsToBeExecuted_.append("rm -f " + files[3]);
            hasRaw = true;
        } else if (rawOption == 2) {
            conf->set("import_rawstack", baseName + '.' + QFileInfo(files[3]).suffix(), false);
            conf->set("import_rawstack_original", files[3], false);
            conf->set("raw_gaincorrectedstack", "raw_gaincorrectedstack", false);
            conf->set("raw_gaincorrectedstack_original", files[3], false);
            conf->set("import_original_time", QString::number(QFileInfo(files[3]).created().toMSecsSinceEpoch()), false);
            scriptsToBeExecuted_.append("cp -f " + files[3] + " " + workingDir.canonicalPath() + "/" + "raw_gaincorrectedstack.mrcs");
            if(deleteCheck->isChecked()) scriptsToBeExecuted_.append("rm -f " + files[3]);
            hasRaw = true;
        }
    }

    //Check for defects list file
    QString defectsFile = conf->getValue("import_defects_original");
    if(QFileInfo(defectsFile).exists()) {
        conf->set("import_defects", "../" + QFileInfo(defectsFile).fileName(), false);
        scriptsToBeExecuted_.append("rsync -auvP " + defectsFile + " " + workingDir.canonicalPath() + "/../" + QFileInfo(defectsFile).fileName());
    }
    
    //Check for gain reference file
    QString gainRefFile = conf->getValue("import_gainref_original");
    if(QFileInfo(gainRefFile).exists()) {
        conf->set("import_gainref", "../" + QFileInfo(gainRefFile).fileName(), false);
        scriptsToBeExecuted_.append("rsync -auvP " + gainRefFile + " " + workingDir.canonicalPath() + "/../" + QFileInfo(gainRefFile).fileName());
    }
    
    //Set the parameters from filename
    for(QString param : fileNameParams.keys()) {
        if(parameterMaster.containsParameter(param)) {
            conf->set(param, fileNameParams[param], false);
            //qDebug() << "Parameter set: " << param << " => " << fileNameParams[param];
        }
    }
    
    conf->setModified(true);
    
    //Write to status folder if required
    if(userPreferenceData.get("status_folder_update") == "y" && QFileInfo(userPreferenceData.get("status_folder")).isDir()) {
        long currentMSecs = conf->getValue("import_original_time").toLong();
        
        //Write the last imported data
        QFile saveFile(userPreferenceData.get("status_folder") + "/last.txt");
        long lastMSecs = 0;
        if(saveFile.exists()) {
            if (saveFile.open(QIODevice::ReadOnly | QIODevice::Text)) {
                while (!saveFile.atEnd()) {
                    lastMSecs = QString(saveFile.readLine().simplified()).toLong();
                }
		saveFile.close();
            }
            saveFile.remove();
        }
        
	QString toBeWritten;
        if(currentMSecs >= lastMSecs) toBeWritten = QString::number(currentMSecs);
        else toBeWritten = QString::number(lastMSecs);
        if (saveFile.open(QIODevice::WriteOnly | QIODevice::Text)) {
            saveFile.write(toBeWritten.toLatin1());
        }
        saveFile.close();
        
        //Write the time stamp in the last hour processed data
        ProjectData::writeStatisticsToStatusFolder("last_recorded.txt", currentMSecs);
        ProjectData::writeStatisticsToStatusFolder("last_imported.txt");
    }
     
    //register that this image was imported
    ImportFolderSettings(QDir(conf->getValue("import_dir"))).addImportedImage(baseName, importGroup_ + "/" + number, hasAveraged, hasAligned, hasRaw);
    
    //Add the scripts to be executed during import
    QStringList scripts = importSelectorDialog.scriptPaths(ProjectPreferences().scripts("import"));
    for(QString script : scripts) {
        if(!script.isEmpty()) scriptsToBeExecuted_.append("SCRIPT:" + script);
    }
    continueExecution();
}
bool MainWindow::save()
{
    return isUntitled ? saveAs() : saveFile(curFile);
}
Beispiel #26
0
bool Settings::save(QString profile) {
  QString fileName = profileDir(profile.isEmpty() ? profileName_ : profile) % "/settings.conf";
  return saveFile(fileName);
}
MainWindow::MainWindow()
{
    QMenu *fileMenu = new QMenu(tr("&File"));

    QAction *saveAction = fileMenu->addAction(tr("&Save..."));
    saveAction->setShortcut(tr("Ctrl+S"));
    QAction *quitAction = fileMenu->addAction(tr("E&xit"));
    quitAction->setShortcut(tr("Ctrl+Q"));

    QMenu *showMenu = new QMenu(tr("&Show"));

    QAction *showTableAction = showMenu->addAction(tr("&Table"));

    menuBar()->addMenu(fileMenu);
    menuBar()->addMenu(showMenu);

    editor = new QTextEdit();

//! [0] //! [1]
    QTextCursor cursor(editor->textCursor());
//! [0]
    cursor.movePosition(QTextCursor::Start);
//! [1]

    int rows = 11;
    int columns = 4;

//! [2]
    QTextTableFormat tableFormat;
    tableFormat.setBackground(QColor("#e0e0e0"));
    QVector<QTextLength> constraints;
    constraints << QTextLength(QTextLength::PercentageLength, 16);
    constraints << QTextLength(QTextLength::PercentageLength, 28);
    constraints << QTextLength(QTextLength::PercentageLength, 28);
    constraints << QTextLength(QTextLength::PercentageLength, 28);
    tableFormat.setColumnWidthConstraints(constraints);
//! [3]
    QTextTable *table = cursor.insertTable(rows, columns, tableFormat);
//! [2] //! [3]

    int column;
    int row;
    QTextTableCell cell;
    QTextCursor cellCursor;
    
    QTextCharFormat charFormat;
    charFormat.setForeground(Qt::black);

//! [4]
    cell = table->cellAt(0, 0);
    cellCursor = cell.firstCursorPosition();
    cellCursor.insertText(tr("Week"), charFormat);
//! [4]

//! [5]
    for (column = 1; column < columns; ++column) {
        cell = table->cellAt(0, column);
        cellCursor = cell.firstCursorPosition();
        cellCursor.insertText(tr("Team %1").arg(column), charFormat);
    }

    for (row = 1; row < rows; ++row) {
        cell = table->cellAt(row, 0);
        cellCursor = cell.firstCursorPosition();
        cellCursor.insertText(tr("%1").arg(row), charFormat);

        for (column = 1; column < columns; ++column) {
            if ((row-1) % 3 == column-1) {
//! [5] //! [6]
                cell = table->cellAt(row, column);
                QTextCursor cellCursor = cell.firstCursorPosition();
                cellCursor.insertText(tr("On duty"), charFormat);
            }
//! [6] //! [7]
        }
//! [7] //! [8]
    }
//! [8]

    connect(saveAction, SIGNAL(triggered()), this, SLOT(saveFile()));
    connect(quitAction, SIGNAL(triggered()), this, SLOT(close()));
    connect(showTableAction, SIGNAL(triggered()), this, SLOT(showTable()));

    setCentralWidget(editor);
    setWindowTitle(tr("Text Document Tables"));
}
Beispiel #28
0
/**
 * Save the database to a file.
 *
 * This function uses QTemporaryFile instead of QSaveFile due to a bug
 * in Qt (https://bugreports.qt.io/browse/QTBUG-57299) that may prevent
 * the QSaveFile from renaming itself when using Dropbox, Drive, or OneDrive.
 *
 * The risk in using QTemporaryFile is that the rename function is not atomic
 * and may result in loss of data if there is a crash or power loss at the
 * wrong moment.
 *
 * @param filePath Absolute path of the file to save
 * @param atomic Use atomic file transactions
 * @param backup Backup the existing database file, if exists
 * @param error error message in case of failure
 * @return true on success
 */
bool Database::save(const QString& filePath, QString* error, bool atomic, bool backup)
{
    Q_ASSERT(!m_data.isReadOnly);
    if (m_data.isReadOnly) {
        return false;
    }

    if (atomic) {
        QSaveFile saveFile(filePath);
        if (saveFile.open(QIODevice::WriteOnly)) {
            // write the database to the file
            if (!writeDatabase(&saveFile, error)) {
                return false;
            }

            if (backup) {
                backupDatabase(filePath);
            }

            if (saveFile.commit()) {
                // successfully saved database file
                setFilePath(filePath);
                return true;
            }
        }

        if (error) {
            *error = saveFile.errorString();
        }
    } else {
        QTemporaryFile tempFile;
        if (tempFile.open()) {
            // write the database to the file
            if (!writeDatabase(&tempFile, error)) {
                return false;
            }

            tempFile.close(); // flush to disk

            if (backup) {
                backupDatabase(filePath);
            }

            // Delete the original db and move the temp file in place
            QFile::remove(filePath);

            // Note: call into the QFile rename instead of QTemporaryFile
            // due to an undocumented difference in how the function handles
            // errors. This prevents errors when saving across file systems.
            if (tempFile.QFile::rename(filePath)) {
                // successfully saved the database
                tempFile.setAutoRemove(false);
                setFilePath(filePath);
                return true;
            } else if (!backup || !restoreDatabase(filePath)) {
                // Failed to copy new database in place, and
                // failed to restore from backup or backups disabled
                tempFile.setAutoRemove(false);
                if (error) {
                    *error = tr("%1\nBackup database located at %2").arg(tempFile.errorString(), tempFile.fileName());
                }
                markAsModified();
                return false;
            }
        }

        if (error) {
            *error = tempFile.errorString();
        }
    }

    // Saving failed
    markAsModified();
    return false;
}
Beispiel #29
0
 void XmlConfig::shutdown()
 {
   // ensure everything is written to the config file
   saveFile();
 }
int main()
{
	// --added for timing code-- //
	timekeeper myTimer;
	unsigned precomputationRealTime, precomputationClockTime;
	unsigned sumOfInterpolationRealTimes = 0;
	unsigned sumOfInterpolationClockTimes = 0;

	int W=50;

	std::vector<Vector<2,double> > samplesPos(W*W);
	std::vector<double> values1(W*W, 0.);
	std::vector<double> values2(W*W, 0.);
	std::vector<double> valuesR(W*W, 0.);

	for (int i=0; i<W; i++)
	{
		for (int j=0; j<W; j++)
		{
			samplesPos[i*W+j] = Vector<2,double>(i/(double)W,j/(double)W); // the data lie on the unit grid
			values1[i*W+j] = 0.;
			values2[i*W+j] = 0.;
	
			// generate a square
			if (i>5 && i<45 && j>5 && j<45)
				values1[i*W+j] = 1;
			else
				values1[i*W+j] = 0;

			// generate a disk
			if ((i-25)*(i-25)+(j-25)*(j-25)<509)
				values2[i*W+j] = 1;
			else
				values2[i*W+j] = 0;
		}
	}

	Interpolator<2,double> interp(samplesPos, values1,  // source distribution, in R^2 
		samplesPos, values2,							// target distribution
		sqrDistLinear, rbfFuncLinear, interpolateBinsLinear, // how to represent and move the particles
		2,												// particle spread : distance to 2nd nearest neighbor at each sample point
		1);											   // 1 frequency band (standard displacement interpolation)

	// --added for timing code-- //
	myTimer.start();

	interp.precompute();

	// --added for timing code-- //
	myTimer.stop();
	precomputationRealTime = myTimer.getElapsedRealMS();
	precomputationClockTime = myTimer.getElapsedClockMS();
	myTimer.clear();

	int N = 50; // we get 50 intermediate steps
	for (int p=0; p<N; p++)
	{
		double alpha = p/((double)N-1.);

		// --added for timing code-- //
		myTimer.start();

		interp.interpolate(alpha, samplesPos, valuesR);

		// --added for timing code-- //
		myTimer.stop();
		sumOfInterpolationRealTimes += myTimer.getElapsedRealMS();
		sumOfInterpolationClockTimes += myTimer.getElapsedClockMS();
		myTimer.clear();

		saveFile(p, valuesR);
	}

	// --added for timing code-- //
	FILE* timingRecord = fopen("timing", "a");
	fprintf(timingRecord, "entry start\n");
	fprintf(timingRecord, "precomputation (ms): %u\n", precomputationRealTime);
	fprintf(timingRecord, "precomputation (clock ms): %u\n", precomputationClockTime);
	fprintf(timingRecord, "total interpolation (ms): %u\n", sumOfInterpolationRealTimes);
	fprintf(timingRecord, "total interpolation (clock ms): %u\n", sumOfInterpolationClockTimes);
	fprintf(timingRecord, "interpolation count: %d\n", N);
	fprintf(timingRecord, "\n");

	return 0;
}