当前位置: 首页>>代码示例>>C++>>正文


C++ File函数代码示例

本文整理汇总了C++中File函数的典型用法代码示例。如果您正苦于以下问题:C++ File函数的具体用法?C++ File怎么用?C++ File使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。


在下文中一共展示了File函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C++代码示例。

示例1: JmriJFrame

//@Override
/*public*/ void XmlFileLocationAction::actionPerformed(ActionEvent* ev) {

    /*final*/ QString user = FileUtil::getUserFilesPath();
    /*final*/ QString roster = Roster::getDefault()->getRosterLocation();
    /*final*/ QString profile = FileUtil::getProfilePath();
    /*final*/ QString settings = FileUtil::getPreferencesPath();
    /*final*/ QString scripts = FileUtil::getScriptsPath();
    /*final*/ QString prog = System::getProperty("user.dir");
    /*final*/ QString log = System::getProperty("jmri.log.path");

    QString configName = System::getProperty("org.jmri.Apps.configFilename");
    if (!( File(configName).isAbsolute())) {
        // must be relative, but we want it to
        // be relative to the preferences directory
        configName = profile + configName;
    }

    JFrame* frame = new JmriJFrame();  // to ensure fits
    frame->setTitle(tr("Locations"));

    QWidget* pane = new QWidget();
    pane->setLayout(new QVBoxLayout); //(pane, BoxLayout.Y_AXIS));

    QWidget* buttons = new QWidget();
    buttons->setLayout(new FlowLayout());
    pane->layout()->addWidget(buttons);

    QPushButton* b = new QPushButton("Open User Files Location");
    buttons->layout()->addWidget(b);
//    b.addActionListener(new ActionListener() {
//        //@Override
//        /*public*/ void actionPerformed(ActionEvent event) {
//            try {
//                Desktop.getDesktop().open(new File(user));
//            } catch (IOException e) {
//                XmlFileLocationAction.log.error("Error when opening user files location: " + e);
//            } catch (UnsupportedOperationException e) {
//                XmlFileLocationAction.log.error("Error when opening user files location: " + e);
//            }
//        }
//    });
    connect(b, SIGNAL(clicked(bool)), this, SLOT(on_openUserFilesButton()));
    b = new QPushButton("Open Roster Location");
    buttons->layout()->addWidget(b);
//    b.addActionListener(new ActionListener() {
//        @Override
//        /*public*/ void actionPerformed(ActionEvent event) {
//            try {
//                Desktop.getDesktop().open(new java.io.File(roster));
//            } catch (java.io.IOException e) {
//                XmlFileLocationAction.log.error("Error when opening roster location: " + e);
//            } catch (UnsupportedOperationException e) {
//                XmlFileLocationAction.log.error("Error when opening roster location: " + e);
//            }
//        }
//    });
    connect(b, SIGNAL(clicked(bool)), this, SLOT(on_openRosterButton()));
    b = new QPushButton("Open Profile Location");
    buttons->layout()->addWidget(b);
//    b.addActionListener(new ActionListener() {
//        @Override
//        /*public*/ void actionPerformed(ActionEvent event) {
//            try {
//                Desktop.getDesktop().open(new java.io.File(profile));
//            } catch (java.io.IOException e) {
//                XmlFileLocationAction.log.error("Error when opening profile location: " + e);
//            } catch (UnsupportedOperationException e) {
//                XmlFileLocationAction.log.error("Error when opening profile location: " + e);
//            }
//        }
//    });
    connect(b, SIGNAL(clicked(bool)), this, SLOT(on_openProfileButton()));
    b = new QPushButton("Open Settings Location");
    buttons->layout()->addWidget(b);
//    b.addActionListener(new ActionListener() {
//        @Override
//        /*public*/ void actionPerformed(ActionEvent event) {
//            try {
//                Desktop.getDesktop().open(new java.io.File(settings));
//            } catch (java.io.IOException e) {
//                XmlFileLocationAction.log.error("Error when opening settings location: " + e);
//            } catch (UnsupportedOperationException e) {
//                XmlFileLocationAction.log.error("Error when opening settings location: " + e);
//            }
//        }
//    });
    connect(b, SIGNAL(clicked(bool)), this, SLOT(on_openSettingsButton()));
    b = new QPushButton("Open Scripts Location");
    buttons->layout()->addWidget(b);
//    b.addActionListener(new ActionListener() {
//        @Override
//        /*public*/ void actionPerformed(ActionEvent event) {
//            try {
//                Desktop.getDesktop().open(new java.io.File(scripts));
//            } catch (java.io.IOException e) {
//                XmlFileLocationAction.log.error("Error when opening scripts location: " + e);
//            } catch (UnsupportedOperationException e) {
//                XmlFileLocationAction.log.error("Error when opening scripts location: " + e);
//            }
//.........这里部分代码省略.........
开发者ID:allenck,项目名称:DecoderPro_app,代码行数:101,代码来源:xmlfilelocationaction.cpp

示例2: ExtractFilePath

//--------------------------------------------------------------------------
// Loads all the editor settings from file.  True and false settings are saved
//  as 1 and 0.
//  If the contents of settings.dat to not match expected then default values
//  are used.
void __fastcall TOptions::LoadSettings()
{
  try {
    const int SIZE = 256;
    AnsiString str;
    str = ExtractFilePath(Application->ExeName) + "settings.dat";
    char fileName[SIZE];
    strcpy(fileName, str.c_str());        // fileName is path + settings.dat

    defaultSettings();          // start with default settings

    if(FileExists(fileName))    //check if settings file exists
    {                           //if it did then load all the settings
      char buffer[SIZE+1];
      char temp[SIZE+1];        //temp storage
      unsigned int index;       //looping index
      ifstream File(fileName);  //open settings file

      // read and set flags from file
      File.getline(buffer, SIZE); //first line contains version number

      File.getline(buffer, SIZE); // 'generate list' setting
      if (!strcmp(&buffer[1],"$generate list")) {   // if expected setting
        if(buffer[0] == '1') {
          listFlag = true;
          chkGenList->Checked = true;
        } else {
          listFlag   = false;
          chkGenList->Checked = false;
        }
      }

      File.getline(buffer, SIZE); // 'generate s-record' setting
      if (!strcmp(&buffer[1],"$generate s-record")) {   // if expected setting
        if(buffer[0] == '1') {
          objFlag = true;
          chkGenSRec->Checked = true;
        } else {
          objFlag    = false;
          chkGenSRec->Checked = false;
        }
      }

      File.getline(buffer, SIZE); // 'save before assemble' setting
      if (!strcmp(&buffer[1],"$save then assemble")) {  // if expected setting
        if(buffer[0] == '1') {
          bSave = true;
          chkSave->Checked = true;
        } else {
          bSave      = false;
          chkSave->Checked = false;
        }
      }

      File.getline(buffer, SIZE); // 'Show Warnings' setting
      if (!strcmp(&buffer[1],"$show warnings")) {  // if expected setting
        if(buffer[0] == '1') {
          WARflag = true;
          chkShowWarnings->Checked = true;
        } else {
          WARflag    = false;
          chkShowWarnings->Checked = false;
        }
      }

      File.getline(buffer, SIZE); // 'cross reference' setting
      if (!strcmp(&buffer[1],"$cross reference")) {  // if expected setting
        if(buffer[0] == '1') {
          CREflag = true;
          chkCrossRef->Checked = true;
        } else {
          CREflag    = false;
          chkCrossRef->Checked = false;
        }
      }

      File.getline(buffer, SIZE); // 'macro expanded setting' setting
      if (!strcmp(&buffer[1],"$macros expanded")) {  // if expected setting
        if(buffer[0] == '1') {
          MEXflag = true;
          chkMacEx->Checked = true;
        } else {
          MEXflag    = false;
          chkMacEx->Checked = false;
        }
      }

      File.getline(buffer, SIZE); // 'structured assembly expanded setting' setting
      if (!strcmp(&buffer[1],"$structured expand")) {  // if expected setting
        if(buffer[0] == '1') {
          SEXflag = true;
          chkStrucEx->Checked = true;
        } else {
          SEXflag    = false;
          chkStrucEx->Checked = false;
//.........这里部分代码省略.........
开发者ID:fduhia,项目名称:Easy68k,代码行数:101,代码来源:optionsS.cpp

示例3: action

File SDClass::open(const char *filepath, uint8_t mode) {
  /*

     Open the supplied file path for reading or writing.

     The file content can be accessed via the `file` property of
     the `SDClass` object--this property is currently
     a standard `SdFile` object from `sdfatlib`.

     Defaults to read only.

     If `write` is true, default action (when `append` is true) is to
     append data to the end of the file.

     If `append` is false then the file will be truncated first.

     If the file does not exist and it is opened for writing the file
     will be created.

     An attempt to open a file for reading that does not exist is an
     error.

   */

  int pathidx;

  // do the interative search
  SdFile parentdir = getParentDir(filepath, &pathidx);
  // no more subdirs!

  filepath += pathidx;

  if (! filepath[0]) {
    // it was the directory itself!
    return File(parentdir, "/");
  }

  // Open the file itself
  SdFile file;

  // failed to open a subdir!
  if (!parentdir.isOpen())
    return File();

  // there is a special case for the Root directory since its a static dir
  if (parentdir.isRoot()) {
    if ( ! file.open(SD.root, filepath, mode)) {
      // failed to open the file :(
      return File();
    }
    // dont close the root!
  } else {
    if ( ! file.open(parentdir, filepath, mode)) {
      return File();
    }
    // close the parent
    parentdir.close();
  }

  if (mode & (O_APPEND | O_WRITE)) 
    file.seekSet(file.fileSize());
  return File(file, filepath);
}
开发者ID:c1t1zen1,项目名称:RadioMusic,代码行数:63,代码来源:SD.cpp

示例4: QMainWindow


//.........这里部分代码省略.........
    recurringSendPage = new RecurringSendPage(this);

    signVerifyMessageDialog = new SignVerifyMessageDialog(this);

    centralWidget = new QStackedWidget(this);
    centralWidget->addWidget(overviewPage);
    centralWidget->addWidget(transactionsPage);
    centralWidget->addWidget(addressBookPage);
    centralWidget->addWidget(receiveCoinsPage);
    centralWidget->addWidget(sendCoinsPage);
    centralWidget->addWidget(recurringSendPage);
    centralWidget->addWidget(merchantPage);
    setCentralWidget(centralWidget);

    // Create status bar
    statusBar();

    // Status bar notification icons
    QFrame *frameBlocks = new QFrame();
    frameBlocks->setContentsMargins(0,0,0,0);
    frameBlocks->setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Preferred);
    QHBoxLayout *frameBlocksLayout = new QHBoxLayout(frameBlocks);
    frameBlocksLayout->setContentsMargins(3,0,3,0);
    frameBlocksLayout->setSpacing(3);
    labelEncryptionIcon = new QLabel();
    labelMintingIcon = new QLabel();
    labelConnectionsIcon = new QLabel();
    labelBlocksIcon = new QLabel();
    frameBlocksLayout->addStretch();
    frameBlocksLayout->addWidget(labelEncryptionIcon);
    frameBlocksLayout->addStretch();
    frameBlocksLayout->addWidget(labelMintingIcon);
    frameBlocksLayout->addStretch();
    frameBlocksLayout->addWidget(labelConnectionsIcon);
    frameBlocksLayout->addStretch();
    frameBlocksLayout->addWidget(labelBlocksIcon);
    frameBlocksLayout->addStretch();

    // Set minting pixmap
    labelMintingIcon->setPixmap(QIcon(":/icons/minting").pixmap(STATUSBAR_ICONSIZE,STATUSBAR_ICONSIZE));
    labelMintingIcon->setEnabled(false);
    // Add timer to update minting icon
    QTimer *timerMintingIcon = new QTimer(labelMintingIcon);
    timerMintingIcon->start(MODEL_UPDATE_DELAY);
    connect(timerMintingIcon, SIGNAL(timeout()), this, SLOT(updateMintingIcon()));
    // Add timer to update minting weights
    QTimer *timerMintingWeights = new QTimer(labelMintingIcon);
    timerMintingWeights->start(30 * 1000);
    connect(timerMintingWeights, SIGNAL(timeout()), this, SLOT(updateMintingWeights()));
    // Set initial values for user and network weights
    nWeight=0;
    nNetworkWeight = 0;

    // Progress bar and label for blocks download
    progressBarLabel = new QLabel();
    progressBarLabel->setVisible(false);
    progressBar = new QProgressBar();
    progressBar->setAlignment(Qt::AlignCenter);
    progressBar->setVisible(false);

    // Override style sheet for progress bar for styles that have a segmented progress bar,
    // as they make the text unreadable (workaround for issue #1071)
    // See https://qt-project.org/doc/qt-4.8/gallery.html
    QString curStyle = qApp->style()->metaObject()->className();
    if(curStyle == "QWindowsStyle" || curStyle == "QWindowsXPStyle")
    {
        progressBar->setStyleSheet("QProgressBar { background-color: #e8e8e8; border: 1px solid grey; border-radius: 7px; padding: 1px; text-align: center; } QProgressBar::chunk { background: QLinearGradient(x1: 0, y1: 0, x2: 1, y2: 0, stop: 0 #FF8000, stop: 1 orange); border-radius: 7px; margin: 0px; }");
    }

    statusBar()->addWidget(progressBarLabel);
    statusBar()->addWidget(progressBar);
    statusBar()->addPermanentWidget(frameBlocks);

    syncIconMovie = new QMovie(":/movies/update_spinner", "mng", this);
    qApp->setStyleSheet("background-color: #effbef;");
    //load stylesheet if present
    QFile File("style/stylesheet.qss");
    File.open(QFile::ReadOnly);
    QString StyleSheet = QLatin1String(File.readAll());
    qApp->setStyleSheet(StyleSheet);

    // Clicking on a transaction on the overview page simply sends you to transaction history page
    connect(overviewPage, SIGNAL(transactionClicked(QModelIndex)), this, SLOT(gotoHistoryPage()));
    connect(overviewPage, SIGNAL(transactionClicked(QModelIndex)), transactionView, SLOT(focusTransaction(QModelIndex)));

    // Double-clicking on a transaction on the transaction history page shows details
    connect(transactionView, SIGNAL(doubleClicked(QModelIndex)), transactionView, SLOT(showDetails()));

    rpcConsole = new RPCConsole(this);
    connect(openRPCConsoleAction, SIGNAL(triggered()), rpcConsole, SLOT(show()));

    // Clicking on "Verify Message" in the address book sends you to the verify message tab
    connect(addressBookPage, SIGNAL(verifyMessage(QString)), this, SLOT(gotoVerifyMessageTab(QString)));
    // Clicking on "Sign Message" in the receive coins page sends you to the sign message tab
    connect(receiveCoinsPage, SIGNAL(signMessage(QString)), this, SLOT(gotoSignMessageTab(QString)));

    gotoOverviewPage();
    statusBar()->showMessage(tr("Remember to make an external backup of your wallet"));
    QTimer::singleShot(30000, this, SLOT(noMessage()));
}
开发者ID:Milstein,项目名称:Mintcoin-Desktop-Wallet,代码行数:101,代码来源:bitcoingui.cpp

示例5: findFileSystemRoots

void File::findFileSystemRoots (Array<File>& destArray)
{
    destArray.add (File ("/"));
}
开发者ID:adscum,项目名称:MoogLadders,代码行数:4,代码来源:juce_linux_Files.cpp

示例6: name

//==============================================================================
void BinaryResources::fillInGeneratedCode (GeneratedCode& code) const
{
    if (resources.size() > 0)
    {
        code.publicMemberDeclarations << "// Binary resources:\n";

        MemoryOutputStream defs;

        defs << "//==============================================================================\n";
        defs << "// Binary resources - be careful not to edit any of these sections!\n\n";

        for (int i = 0; i < resources.size(); ++i)
        {
            code.publicMemberDeclarations
                << "static const char* "
                << resources[i]->name
                << ";\nstatic const int "
                << resources[i]->name
                << "Size;\n";

            const String name (resources[i]->name);
            const MemoryBlock& mb = resources[i]->data;

            defs << "// JUCER_RESOURCE: " << name << ", " << (int) mb.getSize()
                << ", \""
                << File (resources[i]->originalFilename)
                    .getRelativePathFrom (code.document->getCppFile())
                    .replaceCharacter ('\\', '/')
                << "\"\n";

            String line1;
            line1 << "static const unsigned char resource_"
                  << code.className << "_" << name << "[] = { ";

            defs << line1;

            int charsOnLine = line1.length();

            for (size_t j = 0; j < mb.getSize(); ++j)
            {
                const int num = (int) (unsigned char) mb[j];
                defs << num << ',';

                charsOnLine += 2;
                if (num >= 10)   ++charsOnLine;
                if (num >= 100)  ++charsOnLine;

                if (charsOnLine >= 200)
                {
                    charsOnLine = 0;
                    defs << '\n';
                }
            }

            defs
              << "0,0};\n\n"
                 "const char* " << code.className << "::" << name
              << " = (const char*) resource_" << code.className << "_" << name
              << ";\nconst int "
              << code.className << "::" << name << "Size = "
              << (int) mb.getSize()
              << ";\n\n";
        }

        code.staticMemberDefinitions << defs.toString();
    }
}
开发者ID:Neknail,项目名称:JUCE,代码行数:68,代码来源:jucer_BinaryResources.cpp

示例7: qDebug

bool PureImageCache::CreateEmptyDB(const QString &file)
{
#ifdef DEBUG_PUREIMAGECACHE
    qDebug()<<"Create database at!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!:"<<file;
#endif //DEBUG_PUREIMAGECACHE
    QFileInfo File(file);
    QDir dir=File.absoluteDir();
    QString path=dir.absolutePath();
    QString filename=File.fileName();
    if(File.exists())
        QFile(filename).remove();
    if(!dir.exists())
    {
#ifdef DEBUG_PUREIMAGECACHE
        qDebug()<<"CreateEmptyDB: Cache path doesn't exist, try to create";
#endif //DEBUG_PUREIMAGECACHE
        if(!dir.mkpath(path))
        {
#ifdef DEBUG_PUREIMAGECACHE
            qDebug()<<"CreateEmptyDB: Could not create path";
#endif //DEBUG_PUREIMAGECACHE
            return false;
        }
    }
    addDatabaseMutex.lock();
    QSqlDatabase db(QSqlDatabase::addDatabase("QSQLITE",QLatin1String("CreateConn")));
    addDatabaseMutex.unlock();
    db.setDatabaseName(file);
    if (!db.open())
    {
#ifdef DEBUG_PUREIMAGECACHE
        qDebug()<<"CreateEmptyDB: Unable to create database";
#endif //DEBUG_PUREIMAGECACHE

        return false;
    }
    QSqlQuery query(db);
    query.exec("CREATE TABLE IF NOT EXISTS Tiles (id INTEGER NOT NULL PRIMARY KEY, X INTEGER NOT NULL, Y INTEGER NOT NULL, Zoom INTEGER NOT NULL, Type INTEGER NOT NULL,Date TEXT)");
    if(query.numRowsAffected()==-1)
    {
#ifdef DEBUG_PUREIMAGECACHE
        qDebug()<<"CreateEmptyDB: "<<query.lastError().driverText();
#endif //DEBUG_PUREIMAGECACHE
        db.close();
        return false;
    }
    query.exec("CREATE TABLE IF NOT EXISTS TilesData (id INTEGER NOT NULL PRIMARY KEY CONSTRAINT fk_Tiles_id REFERENCES Tiles(id) ON DELETE CASCADE, Tile BLOB NULL)");
    if(query.numRowsAffected()==-1)
    {
#ifdef DEBUG_PUREIMAGECACHE
        qDebug()<<"CreateEmptyDB: "<<query.lastError().driverText();
#endif //DEBUG_PUREIMAGECACHE
        db.close();
        return false;
    }
    query.exec(
                "CREATE TRIGGER fki_TilesData_id_Tiles_id "
                "BEFORE INSERT ON [TilesData] "
                "FOR EACH ROW BEGIN "
                "SELECT RAISE(ROLLBACK, 'insert on table TilesData violates foreign key constraint fki_TilesData_id_Tiles_id') "
                "WHERE (SELECT id FROM Tiles WHERE id = NEW.id) IS NULL; "
                "END");
    if(query.numRowsAffected()==-1)
    {
#ifdef DEBUG_PUREIMAGECACHE
        qDebug()<<"CreateEmptyDB: "<<query.lastError().driverText();
#endif //DEBUG_PUREIMAGECACHE
        db.close();
        return false;
    }
    query.exec(
                "CREATE TRIGGER fku_TilesData_id_Tiles_id "
                "BEFORE UPDATE ON [TilesData] "
                "FOR EACH ROW BEGIN "
                "SELECT RAISE(ROLLBACK, 'update on table TilesData violates foreign key constraint fku_TilesData_id_Tiles_id') "
                "WHERE (SELECT id FROM Tiles WHERE id = NEW.id) IS NULL; "
                "END");
    if(query.numRowsAffected()==-1)
    {
#ifdef DEBUG_PUREIMAGECACHE
        qDebug()<<"CreateEmptyDB: "<<query.lastError().driverText();
#endif //DEBUG_PUREIMAGECACHE
        db.close();
        return false;
    }
    query.exec(
                "CREATE TRIGGER fkdc_TilesData_id_Tiles_id "
                "BEFORE DELETE ON Tiles "
                "FOR EACH ROW BEGIN "
                "DELETE FROM TilesData WHERE TilesData.id = OLD.id; "
                "END");
    if(query.numRowsAffected()==-1)
    {
#ifdef DEBUG_PUREIMAGECACHE
        qDebug()<<"CreateEmptyDB: "<<query.lastError().driverText();
#endif //DEBUG_PUREIMAGECACHE
        db.close();
        return false;
    }
    db.close();
//.........这里部分代码省略.........
开发者ID:AlexanderV,项目名称:MAP,代码行数:101,代码来源:pureimagecache.cpp

示例8: test_timer

void ribi::Chess::GameWidget::Test() noexcept
{
  //Testing Chess::Piece exactly once
  {
    static bool is_tested = false;
    if (is_tested) return;
    is_tested = true;
  }
  const ribi::TestTimer test_timer(__func__,__FILE__,1.0);
  #ifdef FIX_ISSUE_240
  {
    {
      const boost::shared_ptr<Chess::Game> game
        = boost::make_shared<Chess::Game>();
      const boost::shared_ptr<Chess::ChessWidget> w(
        new GameWidget(game,Geometry().CreateRect(0,0,100,100)));
      w->ClickPixel(-1,-1);
      w->ClickPixel(1000,1000);
    }
    {
      const boost::shared_ptr<Chess::Game> game
        = boost::make_shared<Chess::Game>();
      const boost::shared_ptr<Chess::GameWidget> widget(
        new Chess::GameWidget(game,Geometry().CreateRect(0,0,100,100)));
      assert(widget->GetSelector()->GetCursor()->GetFile() == Chess::File("a"));
      assert(widget->GetSelector()->GetCursor()->GetRank() == Chess::Rank("1"));
      assert(!widget->GetSelector()->GetSelected());
      //Check clicking: cursor will always follow
      for (int x=0;x!=8;++x)
      {
        for (int y=0;y!=8;++y)
        {
          const boost::shared_ptr<Square> square {
            SquareFactory().Create(
              File(x),Rank(y)
            )
          };
          widget->Click(square);
          assert(*widget->GetSelector()->GetCursor() == *square);
        }
      }
      //Check selection: Board::Widget will select any Chess::Piece, Board::Game only those of the active player
      //Click on own piece, selecting it
      {
        const boost::shared_ptr<Square> square {
          SquareFactory().Create("b1")
        };
        widget->Click(square);
      }
      assert(*widget->GetSelector()->GetCursor() == *SquareFactory().Create("b1"));
      assert(widget->GetSelector()->GetSelected());
      assert(*widget->GetSelector()->GetSelected() == *SquareFactory().Create("b1"));

      //Click on empty square, selected piece remains
      widget->Click(SquareFactory().Create("d4"));
      assert(*widget->GetSelector()->GetCursor() == *SquareFactory().Create("d4"));
      assert(widget->GetSelector()->GetSelected());
      assert(*widget->GetSelector()->GetSelected() == *SquareFactory().Create("b1"));

      //Click on selected square, undoing selection
      widget->Click(SquareFactory().Create("b1"));
      assert(*widget->GetSelector()->GetCursor() == *SquareFactory().Create("b1"));
      assert(!widget->GetSelector()->GetSelected());

      //Click on enemy square, Chess::Board will select it
      widget->Click(SquareFactory().Create("h8"));
      assert(*widget->GetSelector()->GetCursor() == *SquareFactory().Create("g8"));
      assert(!widget->GetSelector()->GetSelected());

      //Playing e7-e5 must succeed for a Board, must fail for a Game
      assert( game->GetBoard()->GetPiece(SquareFactory().Create("e7")));
      assert(!game->GetBoard()->GetPiece(SquareFactory().Create("e5")));
      widget->Click(SquareFactory().Create("e7"));
      assert(*widget->GetSelector()->GetCursor() == *SquareFactory().Create("e7"));
      assert(!widget->GetSelector()->GetSelected());

      widget->Click(SquareFactory().Create("e5"));
      assert(*widget->GetSelector()->GetCursor() == *SquareFactory().Create("e5"));
      assert(!widget->GetSelector()->GetSelected());
      assert( game->GetBoard()->GetPiece(SquareFactory().Create("e7")));
      assert(!game->GetBoard()->GetPiece(SquareFactory().Create("e5")));

      //Playing e2-e4 must succeed for both Board and Game
      assert( game->GetBoard()->GetPiece(SquareFactory().Create("e2")));
      assert(!game->GetBoard()->GetPiece(SquareFactory().Create("e4")));
      widget->Click(SquareFactory().Create("e2"));
      assert(*widget->GetSelector()->GetCursor() == *SquareFactory().Create("e2"));
      assert(widget->GetSelector()->GetSelected());
      assert(*widget->GetSelector()->GetSelected() == *SquareFactory().Create("e2"));

      widget->Click(SquareFactory().Create("e4"));
      assert(*widget->GetSelector()->GetCursor() == *SquareFactory().Create("e4"));
      assert(!widget->GetSelector()->GetSelected());
      assert(!game->GetBoard()->GetPiece(SquareFactory().Create("e2")));
      assert( game->GetBoard()->GetPiece(SquareFactory().Create("e4")));
    }
  }
  #endif
}
开发者ID:richelbilderbeek,项目名称:RibiClasses,代码行数:99,代码来源:chessgamewidget.cpp

示例9: File

void QVX_TensileTest::RunTensileTest(QString* pDispMessage)
{
	QFile File(OutFilePath);
		
	if (!File.open(QIODevice::WriteOnly | QIODevice::Text)) {
		ProgressMessage = "Could not open file. Aborting.";
		return;
	}
	QTextStream out(&File); 

//	double CurMaxDisp = 9e9;
	std::string IntMsg;

	vfloat StepPercAmt = 1.0/NumStep;
	int VoxCount = NumVox();

	int count = 0;
	int MinimumPerStep = 5;

	int NumBCs = pEnv->GetNumBCs();
	for (int j=0; j<NumBCs; j++){
		if (pEnv->GetBC(j)->Displace.Length2() == 0 ) continue; //if zero displacement, continue
		out << "Disp (m)" << "\t" << "Force (N)" << "\t";
		if (IsBasicTensile){out << "Strain (%)" << "\t" << "Stress (MPa)" << "\t" << "Modulus (MPa)" << "\t";}
	}
	
	out << "\n";

	double LastStress; //so we can calculate modulus at each point...
	double LastStrain;

	for (int i=0; i<NumStep; i++){
		ProgressMessage = "Performing tensile test...";
		for (int j=0; j<VoxCount; j++) VoxArray[j].ScaleExternalInputs((i+1)*StepPercAmt);
		//wiat to settle between timesteps...
		int LastBroken = -1;
		ClearHistories(); //needed so it doesn't immediately "converge" on the next time step

		while (NumBroken() != LastBroken){ //if one breaks, repeat the settling undtil we're done breaking...
			LastBroken = NumBroken();
			EnableFailure(false);
	
//			SetSlowDampZ(CurDamp);

			count = 0;
//			bool LastUnder = false; //were we under the threshhold last time?
//			while (!LastUnder || CurMaxDisp > ConvThresh){
			while (!StopConditionMet()){
	//			if (CurMaxDisp < ConvThresh) LastUnder = true;

				for (int i=0; i<MinimumPerStep; i++){
					if (CancelFlag) break;

					if (!TimeStep(&IntMsg)){ //always do at least 5 steps...
						ProgressMessage = "Tensile test failed. \n \n" + IntMsg;
						CancelFlag = true; //get outta here!
					}
//					CurMaxDisp = SS.NormObjDisp;
				}
				if (CancelFlag) break;
				
				count+=MinimumPerStep;
				if (count > 20000){
					QString Num = QString::number(MaxMoveHistory[0]*1000);
					ProgressMessage = "Simulation not converging at " + Num.toStdString() + ". \n Retry with larger threshold.";
				}
			}
			if (CancelFlag) break;

			EnableFailure(true); //do one step to apply breaking and re-settle as needed...
			if (!TimeStep(&IntMsg)){
				ProgressMessage = "Tensile test failed. \n \n" + IntMsg;
				CancelFlag = true; //get outta here!
			}
		}

		for (int j=0; j<NumBCs; j++){
			CVX_FRegion* pThisBC = pEnv->GetBC(j);
			if (pThisBC->Displace.Length2() != 0 ){ //if non-zero displacement
				double CurDisp = pThisBC->Displace.Length()*(i+1.0)/((double)NumStep);
				double tmp2 = -GetSumForceDir(pThisBC);
				out << CurDisp << "\t" << tmp2 << "\t";
				if (IsBasicTensile){ //only two materials, only one with displacement, so we should only ever enter here once!!
					double ThisStress = tmp2/CSArea;
					double ThisStrain = CurDisp/IniLength;
					out << ThisStrain*100 << "\t" << ThisStress/1e6 << "\t";
					if (i!=0) out << (ThisStress-LastStress)/(ThisStrain-LastStrain)/1e6 << "\t";
					else out << "" << "\t";
					LastStress = ThisStress;
					LastStrain = ThisStrain;
				}
			}
		}
		
		out << "\n";

//		for (int k=0; k<VoxArray.size(); k++){
//			VoxArray[k].ExternalDisp *= (i+2.0)/(i+1.0);
//		}

//.........这里部分代码省略.........
开发者ID:WPI-ARC,项目名称:soft_hand,代码行数:101,代码来源:QVX_TensileTest.cpp

示例10: PrintErrorPage

bool CHTTPSock::PrintFile(const CString& sFileName, CString sContentType) {
	CString sFilePath = sFileName;

	if (!m_sDocRoot.empty()) {
		sFilePath.TrimLeft("/");

		sFilePath = CDir::CheckPathPrefix(m_sDocRoot, sFilePath, m_sDocRoot);

		if (sFilePath.empty()) {
			PrintErrorPage(403, "Forbidden", "You don't have permission to access that file on this server.");
			DEBUG("THIS FILE:     [" << sFilePath << "] does not live in ...");
			DEBUG("DOCUMENT ROOT: [" << m_sDocRoot << "]");
			return false;
		}
	}

	CFile File(sFilePath);

	if (!File.Open()) {
		PrintNotFound();
		return false;
	}

	if (sContentType.empty()) {
		if (sFileName.Right(5).Equals(".html") || sFileName.Right(4).Equals(".htm")) {
			sContentType = "text/html; charset=utf-8";
		} else if (sFileName.Right(4).Equals(".css")) {
			sContentType = "text/css; charset=utf-8";
		} else if (sFileName.Right(3).Equals(".js")) {
			sContentType = "application/x-javascript; charset=utf-8";
		} else if (sFileName.Right(4).Equals(".jpg")) {
			sContentType = "image/jpeg";
		} else if (sFileName.Right(4).Equals(".gif")) {
			sContentType = "image/gif";
		} else if (sFileName.Right(4).Equals(".ico")) {
			sContentType = "image/x-icon";
		} else if (sFileName.Right(4).Equals(".png")) {
			sContentType = "image/png";
		} else if (sFileName.Right(4).Equals(".bmp")) {
			sContentType = "image/bmp";
		} else {
			sContentType = "text/plain; charset=utf-8";
		}
	}

	const time_t iMTime = File.GetMTime();
	bool bNotModified = false;
	CString sETag;

	if (iMTime > 0 && !m_bHTTP10Client) {
		sETag = "-" + CString(iMTime); // lighttpd style ETag

		AddHeader("Last-Modified", GetDate(iMTime));
		AddHeader("ETag", "\"" + sETag + "\"");
		AddHeader("Cache-Control", "public");

		if (!m_sIfNoneMatch.empty()) {
			m_sIfNoneMatch.Trim("\\\"'");
			bNotModified = (m_sIfNoneMatch.Equals(sETag, true));
		}
	}

	if (bNotModified) {
		PrintHeader(0, sContentType, 304, "Not Modified");
	} else {
		off_t iSize = File.GetSize();

		// Don't try to send files over 16 MiB, because it might block
		// the whole process and use huge amounts of memory.
		if (iSize > 16 * 1024 * 1024) {
			DEBUG("- Abort: File is over 16 MiB big: " << iSize);
			PrintErrorPage(500, "Internal Server Error", "File too big");
			return true;
		}

		char szBuf[4096];
		off_t iLen = 0;
		int i = 0;

		PrintHeader(iSize, sContentType);

		// while we haven't reached iSize and read() succeeds...
		while (iLen < iSize && (i = File.Read(szBuf, sizeof(szBuf))) > 0) {
			Write(szBuf, i);
			iLen += i;
		}

		if (i < 0) {
			DEBUG("- Error while reading file: " << strerror(errno));
		}
	}

	DEBUG("- ETag: [" << sETag << "] / If-None-Match [" << m_sIfNoneMatch << "]");

	Close(Csock::CLT_AFTERWRITE);

	return true;
}
开发者ID:NeilHanlon,项目名称:znc,代码行数:98,代码来源:HTTPSock.cpp

示例11: main

void main() {
    srand(time(0));
    int* random = randomGen(20, 13000);
    for (int i = 0; i < 20; i++) {
        random[i] = abs(random[i]) % 4;
    }
    Giraffe Giraffe_array[] = { Giraffe("Edik", 18, 234, 200),
                                Giraffe("Masha", 35, 170, 500),
                                Giraffe("Vasya", 18, 234, 201),
                                Giraffe("Kesha", 18, 240, 195) };

    Array_List<Giraffe>* giraffe_array_list = new Array_List<Giraffe>(4);
    for (int i = 0; i < giraffe_array_list->get_capacity(); i++){
        giraffe_array_list->set(i, Giraffe_array[i]);
    }
    for (int i = 0; i < 20; i++) {
        giraffe_array_list->add(Giraffe_array[random[i]]);
    }

    Hash_Table<Giraffe, int> g_table;
    for (int i = 0; i < giraffe_array_list->get_size(); i++) {
        Giraffe* animal = new Giraffe(giraffe_array_list->get(i));

        int* counter = new int(0);

        if (g_table.contains(animal)) {
            try {
                *counter = *(g_table.get_value(animal));
                (*counter)++;
            }
            catch (Key_Doesnt_Exist_Exception e) {
                printf("Bizzare error appeared, we can't help it\n");
                return;
            }
        }
        else {
            *counter = 1;
        }
        Pair<Giraffe, int> p = { animal, counter };
        g_table.put(p);
    }

    for (int i = 0; i < 4; i++) {
        giraffe_array_list->get(i).print();
        printf("%d\n\n", *(g_table.get_value(&(giraffe_array_list->get(i)))));
    }

    Hash_Table<std::string, int> table;
    std::ifstream File("input.txt");
    while (!File.eof()) {
        std::string* word = new std::string();
        int* counter = new int(0);
        File >> *word;
        if (table.contains(word)) {
            try {
                *counter = *(table.get_value(word));
                (*counter)++;
            }
            catch (Key_Doesnt_Exist_Exception e) {
                printf("Bizzare error appeared, we can't help it\n");
                return;
            }
        }
        else {
            *counter = 1;
        }
        Pair<std::string, int> p = { word, counter };
        table.put(p);
    }

    for (int i = 0; i < 16; i++) {
        int max = table.get(i).get_size();
        for (int j = 0; j < max; j++) {
            std::cout << *(table.get(i).get(j).key);
            printf(" %d\t", *(table.get(i).get(j).value));
        }
        printf("\n\n");
    }
}
开发者ID:Ejikpyroman,项目名称:NSULabs-2,代码行数:79,代码来源:main.cpp

示例12: UCIMoveImage

void Notation::image(const Board & b, const Move & m, OutputFormat format, ostream &image) {
   if (format == UCI) {
      return UCIMoveImage(m,image);
   }
   else if (format == WB_OUT) {
      if (TypeOfMove(m) == KCastle) {
          image << "O-O";
      }
      else if (TypeOfMove(m) == QCastle) {
          image << "O-O-O";
      }
      else {
         image << FileImage(StartSquare(m));
         image << RankImage(StartSquare(m));
         image << FileImage(DestSquare(m));
         image << RankImage(DestSquare(m));
         if (TypeOfMove(m) == Promotion) {
            // N.b. ICS requires lower case.
            image << (char)tolower((int)PieceImage(PromoteTo(m)));
         }
      }
      return;
   }
   // format is SAN
   if (IsNull(m)) {
       image << "(null)";
      return;
   }

   PieceType p = PieceMoved(m);
   ASSERT(p != Empty);
   if (TypeOfMove(m) == KCastle) {
       image << "O-O";
   }
   else if (TypeOfMove(m) == QCastle) {
       image << "O-O-O";
   }
   else {
      if (p == Pawn) {
         if (Capture(m) == Empty) {
            image << FileImage(DestSquare(m));
            image << RankImage(DestSquare(m));
         }
         else {
            image << FileImage(StartSquare(m));
            image << 'x';
            image << FileImage(DestSquare(m));
            image << RankImage(DestSquare(m));
         }
         if (TypeOfMove(m) == Promotion) {
            image << '=';
            image << PieceImage(PromoteTo(m));
         }
      }
      else {
         image << PieceImage(p);
         Bitboard attacks =
            b.calcAttacks(DestSquare(m), b.sideToMove());
         unsigned n = attacks.bitCount();
         int dups = 0;
         int filedups = 0;
         int rankdups = 0;
         int files[9];
         int ranks[9];

         if (n > 1) {
            Square sq;
            while (attacks.iterate(sq)) {
               if (TypeOfPiece(b[sq]) == p) {
                  files[dups] = File(sq);
                  if (files[dups] == File(StartSquare(m)))
                     filedups++;
                  ranks[dups] = Rank(sq,White);
                  if (ranks[dups] == Rank(StartSquare(m),White))
                     rankdups++;
                  ++dups;
               }
            }
         }
         if (dups > 1) {
            // need to disambiguate move.
            if (filedups == 1) {
               image << FileImage(StartSquare(m));
            }
            else if (rankdups == 1) {
               image << RankImage(StartSquare(m));
            }
            else {
               // need both rank and file to disambiguate
               image << FileImage(StartSquare(m));
               image << RankImage(StartSquare(m));
            }
         }
         if (Capture(m) != Empty) {
            image << 'x';
         }
         image << FileImage(DestSquare(m));
         image << RankImage(DestSquare(m));
      }
   }
//.........这里部分代码省略.........
开发者ID:Hasimir,项目名称:arasan-chess,代码行数:101,代码来源:notation.cpp

示例13: s


//.........这里部分代码省略.........
    }
    if (it != img.end() && (it+1) != img.end()) {
       // remainder of move should be a square identifier, e.g. "g7"
       dest = SquareValue(*it,*(it+1));
       it += 2;
    }
    if (IsInvalid(dest)) {
       return NullMove;
    }
    if (it != img.end() && *it == '=') {
       it++;
       if (it == img.end()) {
          return NullMove;
       } else {
          promotion = PieceCharValue(*it);
          if (piece != Pawn || promotion == Empty)
             return NullMove;
          it++;
       }
    }
    else if (piece == Pawn && it != img.end() && isupper(*it)) {
       // Quite a few "PGN" files have a8Q instead of a8=Q.
       promotion = PieceCharValue(*it);
       if (promotion == Empty || Rank(dest,side) != 8)
          return NullMove;
    } else if (piece == Pawn && Rank(dest,side) == 8) {
       // promotion but no piece specified, treat as error
       return NullMove;
    }

    // Informant does not use "x" for captures.  Assume that if the destination
    // is occupied, this is a capture move.
    if (board[dest] != EmptyPiece) {
       capture = 1;
    }
    // Do a sanity check on capture moves:
    if (capture && !IsEmptyPiece(board[dest]) && PieceColor(board[dest]) == board.sideToMove()) {
       return NullMove;
    }

    // Ok, now we need to figure out where the start square is. For pawn
    // moves this is implicit.

    int dups = 0;

    if (!have_start) {
       if (capture && piece == Pawn && IsEmptyPiece(board[dest]) &&
           Rank(dest,board.sideToMove()) != 8) {
          // en passant capture, special case
          int start_rank = (board.sideToMove() == White) ?
             Rank(dest,White) - 1 :
             Rank(dest,White) + 1;

          start = MakeSquare(file, start_rank, White);
          dups = 1;
       }
       else if (piece == Pawn && board[dest] == EmptyPiece) {
          start = MakeSquare(file,Rank(dest,board.sideToMove())-1,board.sideToMove());
          if (board[start] == EmptyPiece && Rank(dest,board.sideToMove())==4) {
             start = MakeSquare(file,Rank(dest,board.sideToMove())-2,board.sideToMove());
          }
          if (board[start] == EmptyPiece) return NullMove;
          dups = 1;
       }
       else {
          Bitboard attacks = board.calcAttacks(dest,side);
          Square maybe;
          while (attacks.iterate(maybe)) {
             if (TypeOfPiece(board[maybe]) == piece &&
                 PieceColor(board[maybe]) == board.sideToMove()) {
                if (file && File(maybe) != file)
                   continue;
                if (rank && Rank(maybe,White) != rank)
                   continue;
                if (PieceColor(board[maybe]) == board.sideToMove()) {
                   // Possible move to this square.  Make sure it is legal.
                   Board board_copy(board);
                   Move emove = CreateMove(board,maybe,dest,
                                           promotion);
                   board_copy.doMove(emove);
                   if (!board_copy.anyAttacks(
                          board_copy.kingSquare(board_copy.oppositeSide()),
                          board_copy.sideToMove())) {
                      ++dups;
                      start = maybe;
                   }
                }
             }
          }
       }
    }
    if (dups == 1 || have_start) {
       if (start == InvalidSquare || board[start] == EmptyPiece)
          return NullMove;
       else
          return CreateMove(board, start, dest, promotion);
    }
    else                                           // ambiguous move
       return NullMove;
}
开发者ID:Hasimir,项目名称:arasan-chess,代码行数:101,代码来源:notation.cpp

示例14: return

const File CtrlrLuaMethod::getSourceFile()
{
	return (File (methodTree.getProperty (Ids::luaMethodSourcePath)));
}
开发者ID:Srikrishna31,项目名称:ctrlr,代码行数:4,代码来源:CtrlrLuaMethod.cpp

示例15: QPointF

   //----------------------------------------------------------------------------------------------
   void TLoadDialogWizard::accept(void)
   {
   QString FilePrefix = m_LoadDialogWizardPathPage->m_JobsPrefix->currentText();
   QString Directory  = m_LoadDialogWizardPathPage->m_SavePath->currentText();

   // делим область на участки в соответствии с количеством задач
   QList<QPair<QPointF, QPointF> > Areas;
   if(m_LoadDialogWizardParametersPage->m_CountJobs->value() == 1) 
      Areas.append(qMakePair(m_PointF1, m_PointF2));
   else {
      // делим на вертикальные полосы
      qreal Y1 = m_PointF1.y();
      qreal Y2 = m_PointF2.y();
      qreal X  = m_PointF1.x();
      qreal DeltaX = 
         (m_PointF2.x() - m_PointF1.x()) / m_LoadDialogWizardParametersPage->m_CountJobs->value();
      for(int i = 1; i < m_LoadDialogWizardParametersPage->m_CountJobs->value(); i++) {
         Areas.append(qMakePair(QPointF(X, Y1), QPointF(X + DeltaX, Y2)));
         X += DeltaX;
         }
      Areas.append(qMakePair(QPointF(X, Y1), QPointF(m_PointF2.x(), Y2)));
      }
   // проходим по списку с формированием отдельных файлов заданий
   int i = 0;
   QPair<QPointF, QPointF> PointsPair;
   foreach(PointsPair, Areas) {
      QString FileNameTemplate = Directory + "/" + FilePrefix + "%1.xml";
      QFile File(FileNameTemplate.arg(i++));
      if(!File.exists()) {
         File.open(QIODevice::WriteOnly | QIODevice::Text);
         QTextStream out(&File);
         // начало документа
         out << QString("<?xml version=\"1.0\"?>\n<%1 %2=\"%3\">\n")
                   .arg(SPIDER_TAG_JOBDOCUMENT)
                   .arg(SPIDER_PARAMETER_REQUESTSCOUNT)
                   .arg(m_LoadDialogWizardParametersPage->m_SimultaneousRequestsCount->value());
         // проходим по картам
         for(QMap<QString, TMapDetails>::const_iterator it = m_LoadDialogWizardMapsPage->m_Maps.begin();
             it != m_LoadDialogWizardMapsPage->m_Maps.end(); ++it) {
            if(it.value().g_CheckBox->isChecked()) {
               IMapAdapterInterface* MapInterface = it.value().g_MapInterface;
               int FromZoom = it.value().g_FromZoom->value();
               int ToZoom   = it.value().g_ToZoom->value();
               // начинаем карту
               out << QString("\t<%1 %2=\"%3\">\n")
                         .arg(SPIDER_TAG_MAP)
                         .arg(SPIDER_PARAMETER_PLUGINNAME)
                         .arg(MapInterface->pluginName());
               // проходим по областям с масштабами
               for(int i = FromZoom; i <= ToZoom; i++) {
                  if(i >= MapInterface->minZoom() && i <= MapInterface->maxZoom()) {
                     // начинаем область
                     out << QString("\t\t<%1 %2=\"%3\">\n")
                               .arg(SPIDER_TAG_AREA)
                               .arg(SPIDER_PARAMETER_ZOOM)
                               .arg(i);
                     // пишем точки углов выделенной области
                     out << QString("\t\t\t<%1 %2=\"%3\" %4=\"%5\"/>\n")
                               .arg(SPIDER_TAG_POINT)
                               .arg(SPIDER_PARAMETER_LONGITUDE)
                               .arg(PointsPair.first.x())
                               .arg(SPIDER_PARAMETER_LATITUDE)
                               .arg(PointsPair.first.y());
                     out << QString("\t\t\t<%1 %2=\"%3\" %4=\"%5\"/>\n")
                               .arg(SPIDER_TAG_POINT)
                               .arg(SPIDER_PARAMETER_LONGITUDE)
                               .arg(PointsPair.second.x())
                               .arg(SPIDER_PARAMETER_LATITUDE)
                               .arg(PointsPair.second.y());
                     // завершаем область
                     out << QString("\t\t</%1>\n").arg(SPIDER_TAG_AREA);
                     }
                  }
               // завершаем карту
               out << QString("\t</%1>\n").arg(SPIDER_TAG_MAP);
               }
            }
         // завершаем документ
         out << QString("</%1>\n").arg(SPIDER_TAG_JOBDOCUMENT);
         File.close();
         reject();
         }
      else {
         QMessageBox::critical(0, QNetMapTranslator::tr("Error"), 
            // Russian: Файл '%1' уже существует.
            QNetMapTranslator::tr("File '%1' already exists.").arg(File.fileName()));
         }
      }
开发者ID:vasyutin,项目名称:qnetmap,代码行数:89,代码来源:qnetmap_loaddialogwizard.cpp


注:本文中的File函数示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。