<commit_before>//
// Copyright © 2017 Arm Ltd. All rights reserved.
// SPDX-License-Identifier: MIT
//

#include <boost/filesystem.hpp>
#include <boost/filesystem/operations.hpp>
#include <boost/filesystem/path.hpp>
#include <boost/program_options.hpp>

#include <algorithm>
#include <fstream>
#include <iostream>
#include <string>

namespace
{

// parses the command line to extract
// * the directory -i to look through .raw files from (must exist)
// * the name of the file -o the output CSV file path (must not already exist)
class CommandLineProcessor
{
public:
    bool ValidateDirectory(std::string& dir)
    {
        if (dir.empty())
        {
            std::cerr << "No directory specified" << std::endl;
            return false;
        }

        if (dir[dir.length() - 1] != '/')
        {
            dir += "/";
        }

        if (!boost::filesystem::exists(dir))
        {
            std::cerr << "Directory [" << dir << "] does not exist" << std::endl;
            return false;
        }

        if (!boost::filesystem::is_directory(dir))
        {
            std::cerr << "Given directory [" << dir << "] is not a directory" << std::endl;
            return false;
        }

        return true;
    }

    bool ValidateOutputFile(std::string& outputFileName)
    {
        if (outputFileName.empty())
        {
            std::cerr << "No output file name specified" << std::endl;
            return false;
        }

        if (boost::filesystem::exists(outputFileName))
        {
            std::cerr << "Output file [" << outputFileName << "] already exists" << std::endl;
            return false;
        }

        if (boost::filesystem::is_directory(outputFileName))
        {
            std::cerr << "Output file [" << outputFileName << "] is a directory" << std::endl;
            return false;
        }

        boost::filesystem::path outputPath(outputFileName);
        if (!boost::filesystem::exists(outputPath.parent_path()))
        {
            std::cerr << "Directory [" << outputPath.parent_path().c_str() << "] does not exist" << std::endl;
            return false;
        }

        return true;
    }

    bool ProcessCommandLine(int argc, char* argv[])
    {
        namespace po = boost::program_options;

        po::options_description desc("Options");
        try
        {
            desc.add_options()
                ("help,h", "Display help messages")
                ("indir,i", po::value<std::string>(&m_InputDirectory)->required(),
                            "Directory that .raw files are stored in")
                ("outfile,o", po::value<std::string>(&m_OutputFileName)->required(),
                              "Output CSV file path");
        }
        catch (const std::exception& e)
        {
            std::cerr << "Fatal internal error: [" << e.what() << "]" << std::endl;
            return false;
        }

        po::variables_map vm;

        try
        {
            po::store(po::parse_command_line(argc, argv, desc), vm);

            if (vm.count("help"))
            {
                std::cout << desc << std::endl;
                return false;
            }

            po::notify(vm);
        }
        catch (const po::error& e)
        {
            std::cerr << e.what() << std::endl << std::endl;
            std::cerr << desc << std::endl;
            return false;
        }

        if (!ValidateDirectory(m_InputDirectory))
        {
            return false;
        }

        if (!ValidateOutputFile(m_OutputFileName))
        {
            return false;
        }

        return true;
    }

    std::string GetInputDirectory() {return m_InputDirectory;}
    std::string GetOutputFileName() {return m_OutputFileName;}

private:
    std::string m_InputDirectory;
    std::string m_OutputFileName;
};

} // namespace anonymous

int main(int argc, char* argv[])
{
    CommandLineProcessor cmdline;
    if (!cmdline.ProcessCommandLine(argc, argv))
    {
        return -1;
    }

    namespace fs = boost::filesystem;

    const std::string fileFormat(".raw");
    const std::string bindingId("0");

    const std::string rawDirectory(cmdline.GetInputDirectory());
    const std::string outputPath(cmdline.GetOutputFileName());

    std::vector<fs::path> rawFiles;
    for (auto& entry : boost::make_iterator_range(fs::directory_iterator(rawDirectory), {}))
    {
        if (entry.path().extension().c_str() == fileFormat)
        {
            rawFiles.push_back(entry.path());
        }
    }

    if (!rawFiles.empty())
    {
        unsigned int pass = 0;
        std::ofstream refinementData;
        refinementData.open(outputPath, std::ofstream::out);
        if (refinementData.is_open())
        {
            for (auto const& raw : rawFiles)
            {
                refinementData << pass << ", " << bindingId << ", " << raw.c_str() << "\n";
                if (!refinementData)
                {
                    std::cerr << "Failed to write to output file: " << outputPath << std::endl;
                    continue;
                }
                ++pass;
            }
            refinementData.close();
        }
        else
        {
            std::cerr << "Failed to open output file: " << outputPath << std::endl;
            return -1;
        }
    }
    else
    {
        std::cerr << "No matching files with the \".raw\" extension found in the directory: "
                  << rawDirectory << std::endl;
        return -1;
    }

    return 0;
}<commit_msg>IVGCVSW-3564 Add optional InputLayerBindingID argument to ImageCSVFileGenerator<commit_after>//
// Copyright © 2017 Arm Ltd. All rights reserved.
// SPDX-License-Identifier: MIT
//

#include <boost/filesystem.hpp>
#include <boost/filesystem/operations.hpp>
#include <boost/filesystem/path.hpp>
#include <boost/program_options.hpp>

#include <algorithm>
#include <fstream>
#include <iostream>
#include <string>

namespace
{

// parses the command line to extract
// * the directory -i to look through .raw files from (must exist)
// * the name of the file -o the output CSV file path (must not already exist)
class CommandLineProcessor
{
public:
    bool ValidateDirectory(std::string& dir)
    {
        if (dir.empty())
        {
            std::cerr << "No directory specified" << std::endl;
            return false;
        }

        if (dir[dir.length() - 1] != '/')
        {
            dir += "/";
        }

        if (!boost::filesystem::exists(dir))
        {
            std::cerr << "Directory [" << dir << "] does not exist" << std::endl;
            return false;
        }

        if (!boost::filesystem::is_directory(dir))
        {
            std::cerr << "Given directory [" << dir << "] is not a directory" << std::endl;
            return false;
        }

        return true;
    }

    bool ValidateOutputFile(std::string& outputFileName)
    {
        if (outputFileName.empty())
        {
            std::cerr << "No output file name specified" << std::endl;
            return false;
        }

        if (boost::filesystem::exists(outputFileName))
        {
            std::cerr << "Output file [" << outputFileName << "] already exists" << std::endl;
            return false;
        }

        if (boost::filesystem::is_directory(outputFileName))
        {
            std::cerr << "Output file [" << outputFileName << "] is a directory" << std::endl;
            return false;
        }

        boost::filesystem::path outputPath(outputFileName);
        if (!boost::filesystem::exists(outputPath.parent_path()))
        {
            std::cerr << "Directory [" << outputPath.parent_path().c_str() << "] does not exist" << std::endl;
            return false;
        }

        return true;
    }

    bool ValidateBindingId(const std::string& id)
    {
         if (!std::all_of(id.begin(), id.end(), ::isdigit))
         {
             std::cerr << "Invalid input binding Id" << std::endl;
             return false;
         }

        return true;
    }

    bool ProcessCommandLine(int argc, char* argv[])
    {
        namespace po = boost::program_options;

        po::options_description desc("Options");
        try
        {
            desc.add_options()
                ("help,h", "Display help messages")
                ("indir,i", po::value<std::string>(&m_InputDirectory)->required(),
                            "Directory that .raw files are stored in")
                ("outfile,o", po::value<std::string>(&m_OutputFileName)->required(),
                              "Output CSV file path")
                ("layer-binding-id,l", po::value<std::string>(&m_InputBindingId)->default_value("0"),
                              "Input layer binding Id, Defaults to 0");
        }
        catch (const std::exception& e)
        {
            std::cerr << "Fatal internal error: [" << e.what() << "]" << std::endl;
            return false;
        }

        po::variables_map vm;

        try
        {
            po::store(po::parse_command_line(argc, argv, desc), vm);

            if (vm.count("help"))
            {
                std::cout << desc << std::endl;
                return false;
            }

            po::notify(vm);
        }
        catch (const po::error& e)
        {
            std::cerr << e.what() << std::endl << std::endl;
            std::cerr << desc << std::endl;
            return false;
        }

        if (!ValidateDirectory(m_InputDirectory))
        {
            return false;
        }

        if (!ValidateOutputFile(m_OutputFileName))
        {
            return false;
        }

        if(!ValidateBindingId(m_InputBindingId))
        {
            return false;
        }

        return true;
    }

    std::string GetInputDirectory() {return m_InputDirectory;}
    std::string GetOutputFileName() {return m_OutputFileName;}
    std::string GetInputBindingId() {return m_InputBindingId;}

private:
    std::string m_InputDirectory;
    std::string m_OutputFileName;
    std::string m_InputBindingId;
};

} // namespace anonymous

int main(int argc, char* argv[])
{
    CommandLineProcessor cmdline;
    if (!cmdline.ProcessCommandLine(argc, argv))
    {
        return -1;
    }

    namespace fs = boost::filesystem;

    const std::string fileFormat(".raw");

    const std::string rawDirectory(cmdline.GetInputDirectory());
    const std::string outputPath(cmdline.GetOutputFileName());
    const std::string bindingId(cmdline.GetInputBindingId());

    std::vector<fs::path> rawFiles;
    for (auto& entry : boost::make_iterator_range(fs::directory_iterator(rawDirectory), {}))
    {
        if (entry.path().extension().c_str() == fileFormat)
        {
            rawFiles.push_back(entry.path());
        }
    }

    if (!rawFiles.empty())
    {
        unsigned int pass = 0;
        std::ofstream refinementData;
        refinementData.open(outputPath, std::ofstream::out);
        if (refinementData.is_open())
        {
            for (auto const& raw : rawFiles)
            {
                refinementData << pass << ", " << bindingId << ", " << raw.c_str() << "\n";
                if (!refinementData)
                {
                    std::cerr << "Failed to write to output file: " << outputPath << std::endl;
                    continue;
                }
                ++pass;
            }
            refinementData.close();
        }
        else
        {
            std::cerr << "Failed to open output file: " << outputPath << std::endl;
            return -1;
        }
    }
    else
    {
        std::cerr << "No matching files with the \".raw\" extension found in the directory: "
                  << rawDirectory << std::endl;
        return -1;
    }

    return 0;
}<|endoftext|>


<commit_before>/*
 * MtoNOutputStateTest.cpp
 *
 */

#include "IndexLayer.hpp"
#include "IndexWeightConn.hpp"
#include <columns/PV_Init.hpp>
#include <columns/buildandrun.hpp>
#include <cstdlib>
#include <utils/BufferUtilsPvp.hpp>

void verifyOutputStateFiles(
      std::string const &blockDirectory,
      MPIBlock const &mpiBlock,
      int batchElementsPerProcess);
void verifyOutputStatePre(
      std::string const &path,
      MPIBlock const &mpiBlock,
      int batchElementsPerProcess);
void verifyOutputStatePost(
      std::string const &path,
      MPIBlock const &mpiBlock,
      int batchElementsPerProcess);
void verifyOutputStateSharedWeights(std::string const &path, MPIBlock const &mpiBlock);

int main(int argc, char *argv[]) {
   // Initialize
   PV_Init pv_init(&argc, &argv, false /*no unrecognized arguments*/);
   pv_init.registerKeyword("IndexLayer", Factory::create<IndexLayer>);
   pv_init.registerKeyword("IndexWeightConn", Factory::create<IndexWeightConn>);

   InfoLog() << "PID " << getpid() << ", global rank " << pv_init.getWorldRank() << ".\n";

   // Creating a checkpointer with the same constructor arguments as the
   // HyPerCol's checkpointer will have is the easiest way to get the
   // directory that outputState will write to, and the rank within the
   // MPIBlock.
   Checkpointer *tempCheckpoint = new Checkpointer(
         "column", pv_init.getCommunicator()->getGlobalMPIBlock(), pv_init.getArguments());
   tempCheckpoint->ioParams(PARAMS_IO_READ, pv_init.getParams());
   std::string outputDirectory(tempCheckpoint->getOutputPath());
   std::string const &blockDirectory = tempCheckpoint->getBlockDirectoryName();
   if (!blockDirectory.empty()) {
      outputDirectory.append("/").append(blockDirectory);
   }
   MPIBlock mpiBlock = *tempCheckpoint->getMPIBlock();

   int const rankInBlock = mpiBlock.getRank();
   delete tempCheckpoint;

   // If the directory already exists, delete it so that results aren't skewed
   // by results from a previous run.
   if (rankInBlock == 0) {
      std::string rmrfcommand = std::string("rm -rf \"") + outputDirectory + "\"";
      int rmrfstatus          = std::system(rmrfcommand.c_str());
      if (rmrfstatus > 0) {
         rmrfstatus = WEXITSTATUS(rmrfstatus);
      }
      FatalIf(
            rmrfstatus != 0,
            "Global rank %d failed running the command '%s' with exit value %d\n",
            pv_init.getWorldRank(),
            rmrfstatus);
   }

   HyPerCol *hc          = createHyPerCol(&pv_init);
   int processBatchWidth = hc->getNBatchGlobal() / mpiBlock.getGlobalBatchDimension();
   int status            = hc->run();

   if (rankInBlock == 0) {
      verifyOutputStateFiles(outputDirectory, mpiBlock, processBatchWidth);
   }

   return status == PV_SUCCESS ? EXIT_SUCCESS : EXIT_FAILURE;
}

void verifyOutputStateFiles(
      std::string const &blockDirectory,
      MPIBlock const &mpiBlock,
      int batchElementsPerProcess) {
   std::string outputStatePre = blockDirectory;
   if (!blockDirectory.empty()) {
      outputStatePre.append("/");
   }
   outputStatePre.append("Pre.pvp");
   verifyOutputStatePre(outputStatePre, mpiBlock, batchElementsPerProcess);

   std::string outputStatePost = blockDirectory;
   if (!blockDirectory.empty()) {
      outputStatePost.append("/");
   }
   outputStatePost.append("Post.pvp");
   verifyOutputStatePost(outputStatePost, mpiBlock, batchElementsPerProcess);

   std::string outputStateSharedWeights = blockDirectory;
   if (!blockDirectory.empty()) {
      outputStateSharedWeights.append("/");
   }
   outputStateSharedWeights.append("SharedWeights.pvp");
   verifyOutputStateSharedWeights(outputStateSharedWeights, mpiBlock);
}

void verifyOutputStatePre(
      std::string const &path,
      MPIBlock const &mpiBlock,
      int batchElementsPerProcess) {
   FileStream outputStatePreStream(path.c_str(), std::ios_base::in);
   auto header = BufferUtils::readActivityHeader(outputStatePreStream);
   FatalIf(header.fileType != PVP_NONSPIKING_ACT_FILE_TYPE, "%s is not a dense activity file.\n");
   FatalIf(header.dataType != BufferUtils::FLOAT, "%s does not have dataType=float.\n");

   int batchElementsPerBlock = batchElementsPerProcess * mpiBlock.getBatchDimension();

   int const numFrames  = header.nBands;
   int const numNeurons = header.nx * header.ny * header.nf;

   double frameTime    = std::strtod("NAN", nullptr);
   int localBatchIndex = 0;
   Buffer<float> buffer(header.nx, header.ny, header.nf);

   bool errorFound = false;
   for (int frame = 0; frame < numFrames; frame++) {
      double newTime  = BufferUtils::readFrame<float>(outputStatePreStream, &buffer);
      localBatchIndex = (newTime == frameTime) ? localBatchIndex + 1 : 0;
      if (localBatchIndex != frame % batchElementsPerBlock) {
         ErrorLog().printf(
               "%s, frame %d appears to be local batch index %d of time %f; expected local batch "
               "index %d of time %f.\n",
               path.c_str(),
               frame,
               localBatchIndex,
               newTime,
               frame % batchElementsPerBlock,
               (double)(frame / batchElementsPerBlock)); // Integer division
      }
      frameTime = newTime;
      for (int k = 0; k < numNeurons; k++) {
         int x          = kxPos(k, header.nx, header.ny, header.nf);
         int y          = kyPos(k, header.nx, header.ny, header.nf);
         int f          = featureIndex(k, header.nx, header.ny, header.nf);
         float observed = buffer.at(x, y, f);
         float expected = 1.0f;
         if (observed != expected) {
            ErrorLog().printf(
                  "%s, frame %d, t = %f, local batch index = %d, global batch index %d, x = %d, y "
                  "= %d, f = %d: expected %f, observed %f.\n",
                  path.c_str(),
                  frame,
                  frameTime,
                  localBatchIndex,
                  localBatchIndex + mpiBlock.getStartBatch() * batchElementsPerProcess,
                  x,
                  y,
                  f,
                  (double)expected,
                  (double)observed);
            errorFound = true;
         }
      }
   }
   FatalIf(errorFound, "Error in Pre.pvp\n");
}

void verifyOutputStatePost(
      std::string const &path,
      MPIBlock const &mpiBlock,
      int batchElementsPerProcess) {
   FileStream outputStatePostStream(path.c_str(), std::ios_base::in);
   auto header = BufferUtils::readActivityHeader(outputStatePostStream);
   FatalIf(header.fileType != PVP_NONSPIKING_ACT_FILE_TYPE, "%s is not a dense activity file.\n");
   FatalIf(header.dataType != BufferUtils::FLOAT, "%s does not have dataType=float.\n");

   int batchElementsPerBlock = batchElementsPerProcess * mpiBlock.getBatchDimension();

   int const numFrames = header.nBands;

   int numNeurons       = header.nx * header.ny * header.nf;
   int nxGlobal         = header.nx * (mpiBlock.getGlobalNumColumns() / mpiBlock.getNumColumns());
   int nyGlobal         = header.ny * (mpiBlock.getGlobalNumRows() / mpiBlock.getNumRows());
   int numNeuronsGlobal = nxGlobal * nyGlobal * header.nf;
   int kx0              = header.nx * (mpiBlock.getStartColumn() / mpiBlock.getNumColumns());
   int ky0              = header.ny * (mpiBlock.getStartRow() / mpiBlock.getNumRows());

   double frameTime    = std::strtod("NAN", nullptr);
   int localBatchIndex = 0;
   Buffer<float> buffer(header.nx, header.ny, header.nf);

   bool errorFound = false;
   for (int frame = 0; frame < numFrames; frame++) {
      double newTime  = BufferUtils::readFrame<float>(outputStatePostStream, &buffer);
      localBatchIndex = (newTime == frameTime) ? localBatchIndex + 1 : 0;
      if (localBatchIndex != frame % batchElementsPerBlock) {
         ErrorLog().printf(
               "%s, frame %d appears to be local batch index %d of time %f; expected local batch "
               "index %d of time %f.\n",
               path.c_str(),
               frame,
               localBatchIndex,
               newTime,
               frame % batchElementsPerBlock,
               (double)(frame / batchElementsPerBlock)); // Integer division
      }
      frameTime = newTime;
      for (int k = 0; k < numNeurons; k++) {
         int x                = kxPos(k, header.nx, header.ny, header.nf);
         int y                = kyPos(k, header.nx, header.ny, header.nf);
         int f                = featureIndex(k, header.nx, header.ny, header.nf);
         float observed       = buffer.at(x, y, f);
         int batchIndexOffset = mpiBlock.getStartBatch() * batchElementsPerProcess;
         int globalBatchIndex = localBatchIndex + batchIndexOffset;
         int xGlobal          = x + kx0;
         int yGlobal          = y + ky0;
         int kGlobal          = kIndex(x + kx0, y + ky0, f, nxGlobal, nyGlobal, header.nf);
         float expected = (float)frameTime * (float)(globalBatchIndex * numNeuronsGlobal + kGlobal);
         if (observed != expected) {
            ErrorLog().printf(
                  "%s, frame %d, t = %f, local batch index = %d, global batch index %d, local "
                  "coordinates (x,y,f) = (%d,%d,%d), global coordinates (x,y,f) = (%d,%d,%d), "
                  "local index %d, global index %d: expected %f, observed %f.\n",
                  path.c_str(),
                  frame,
                  frameTime,
                  localBatchIndex,
                  globalBatchIndex,
                  x,
                  y,
                  f,
                  xGlobal,
                  yGlobal,
                  f,
                  k,
                  kGlobal,
                  (double)expected,
                  (double)observed);
            errorFound = true;
         }
      }
   }
   FatalIf(errorFound, "Error in Post.pvp\n");
}

void verifyOutputStateSharedWeights(std::string const &path, MPIBlock const &mpiBlock) {

   // FileStream does not make the file size available, but calls Fatal() if you read past the end,
   // so we need to get the file size.
   struct stat fileStat;
   int statstatus = stat(path.c_str(), &fileStat);
   FatalIf(statstatus != 0, "stat \"%s\" failed: %s\n", path, strerror(errno));
   FatalIf(!S_ISREG(fileStat.st_mode), "\"%s\" is not a regular file.\n", path.c_str());
   long const fileSize = (long)fileStat.st_size;

   FileStream fileStream(path.c_str(), std::ios_base::in);

   bool errorFound = false;
   while (fileStream.getInPos() < fileSize) {
      long frameStart = fileStream.getInPos();
      BufferUtils::WeightHeader weightHeader;
      fileStream.read(&weightHeader, sizeof(weightHeader));
      FatalIf(
            weightHeader.baseHeader.fileType != PVP_KERNEL_FILE_TYPE,
            "%s is not a shared-weights file.\n");
      FatalIf(
            weightHeader.baseHeader.dataType != BufferUtils::FLOAT,
            "%s does not have dataType=float.\n");

      int const nxp = weightHeader.nxp;
      int const nyp = weightHeader.nyp;
      int const nfp = weightHeader.nfp;
      int patchSize = nxp * nyp * nfp;
      std::vector<float> weightBuffer(patchSize);
      int const numPatches = weightHeader.numPatches;
      int const numArbors  = weightHeader.baseHeader.nBands;

      for (int a = 0; a < numArbors; a++) {
         for (int p = 0; p < numPatches; p++) {
            long patchStart = fileStream.getInPos();
            short patchDims[2];
            fileStream.read(patchDims, (size_t)2 * sizeof(*patchDims));
            int offset;
            fileStream.read(&offset, sizeof(offset));
            FatalIf(
                  (int)patchDims[0] != nxp,
                  "Shared-weights file %s: frame starting at %ld, "
                  "arbor %d, patch %d: nx is not header's nxp. (%d vs %d)\n",
                  path.c_str(),
                  frameStart,
                  a,
                  p,
                  (int)patchDims[0],
                  nxp);
            FatalIf(
                  (int)patchDims[1] != nyp,
                  "Shared-weights file %s: frame starting at %ld, "
                  "arbor %d, patch %d: ny is not header's nyp. (%d vs %d)\n",
                  path.c_str(),
                  frameStart,
                  a,
                  p,
                  (int)patchDims[1],
                  nyp);
            FatalIf(
                  offset != 0,
                  "Shared-weights file %s: frame starting at %ld, arbor %d, patch "
                  "%d: offset is not 0.\n");

            fileStream.read(weightBuffer.data(), weightBuffer.size() * sizeof(float));
            for (int index = 0; index < patchSize; index++) {
               float observed = weightBuffer[index];
               float expected = (float)index + (float)weightHeader.baseHeader.timestamp;
               if (observed != expected) {
                  ErrorLog().printf(
                        "%s, frame starting at %ld, patch starting at %ld, index %d: expected %f, "
                        "observed %f.\n",
                        path.c_str(),
                        frameStart,
                        patchStart,
                        index,
                        (double)expected,
                        (double)observed);
               }
            }
         }
      }
      Buffer<float> buffer(weightHeader.nxp, weightHeader.nyp, weightHeader.nfp);
   }
   FatalIf(errorFound, "Error in SharedWeights.pvp\n");
}
<commit_msg>Corrects missing .c_str()<commit_after>/*
 * MtoNOutputStateTest.cpp
 *
 */

#include "IndexLayer.hpp"
#include "IndexWeightConn.hpp"
#include <columns/PV_Init.hpp>
#include <columns/buildandrun.hpp>
#include <cstdlib>
#include <utils/BufferUtilsPvp.hpp>

void verifyOutputStateFiles(
      std::string const &blockDirectory,
      MPIBlock const &mpiBlock,
      int batchElementsPerProcess);
void verifyOutputStatePre(
      std::string const &path,
      MPIBlock const &mpiBlock,
      int batchElementsPerProcess);
void verifyOutputStatePost(
      std::string const &path,
      MPIBlock const &mpiBlock,
      int batchElementsPerProcess);
void verifyOutputStateSharedWeights(std::string const &path, MPIBlock const &mpiBlock);

int main(int argc, char *argv[]) {
   // Initialize
   PV_Init pv_init(&argc, &argv, false /*no unrecognized arguments*/);
   pv_init.registerKeyword("IndexLayer", Factory::create<IndexLayer>);
   pv_init.registerKeyword("IndexWeightConn", Factory::create<IndexWeightConn>);

   InfoLog() << "PID " << getpid() << ", global rank " << pv_init.getWorldRank() << ".\n";

   // Creating a checkpointer with the same constructor arguments as the
   // HyPerCol's checkpointer will have is the easiest way to get the
   // directory that outputState will write to, and the rank within the
   // MPIBlock.
   Checkpointer *tempCheckpoint = new Checkpointer(
         "column", pv_init.getCommunicator()->getGlobalMPIBlock(), pv_init.getArguments());
   tempCheckpoint->ioParams(PARAMS_IO_READ, pv_init.getParams());
   std::string outputDirectory(tempCheckpoint->getOutputPath());
   std::string const &blockDirectory = tempCheckpoint->getBlockDirectoryName();
   if (!blockDirectory.empty()) {
      outputDirectory.append("/").append(blockDirectory);
   }
   MPIBlock mpiBlock = *tempCheckpoint->getMPIBlock();

   int const rankInBlock = mpiBlock.getRank();
   delete tempCheckpoint;

   // If the directory already exists, delete it so that results aren't skewed
   // by results from a previous run.
   if (rankInBlock == 0) {
      std::string rmrfcommand = std::string("rm -rf \"") + outputDirectory + "\"";
      int rmrfstatus          = std::system(rmrfcommand.c_str());
      if (rmrfstatus > 0) {
         rmrfstatus = WEXITSTATUS(rmrfstatus);
      }
      FatalIf(
            rmrfstatus != 0,
            "Global rank %d failed running the command '%s' with exit value %d\n",
            pv_init.getWorldRank(),
            rmrfstatus);
   }

   HyPerCol *hc          = createHyPerCol(&pv_init);
   int processBatchWidth = hc->getNBatchGlobal() / mpiBlock.getGlobalBatchDimension();
   int status            = hc->run();

   if (rankInBlock == 0) {
      verifyOutputStateFiles(outputDirectory, mpiBlock, processBatchWidth);
   }

   return status == PV_SUCCESS ? EXIT_SUCCESS : EXIT_FAILURE;
}

void verifyOutputStateFiles(
      std::string const &blockDirectory,
      MPIBlock const &mpiBlock,
      int batchElementsPerProcess) {
   std::string outputStatePre = blockDirectory;
   if (!blockDirectory.empty()) {
      outputStatePre.append("/");
   }
   outputStatePre.append("Pre.pvp");
   verifyOutputStatePre(outputStatePre, mpiBlock, batchElementsPerProcess);

   std::string outputStatePost = blockDirectory;
   if (!blockDirectory.empty()) {
      outputStatePost.append("/");
   }
   outputStatePost.append("Post.pvp");
   verifyOutputStatePost(outputStatePost, mpiBlock, batchElementsPerProcess);

   std::string outputStateSharedWeights = blockDirectory;
   if (!blockDirectory.empty()) {
      outputStateSharedWeights.append("/");
   }
   outputStateSharedWeights.append("SharedWeights.pvp");
   verifyOutputStateSharedWeights(outputStateSharedWeights, mpiBlock);
}

void verifyOutputStatePre(
      std::string const &path,
      MPIBlock const &mpiBlock,
      int batchElementsPerProcess) {
   FileStream outputStatePreStream(path.c_str(), std::ios_base::in);
   auto header = BufferUtils::readActivityHeader(outputStatePreStream);
   FatalIf(header.fileType != PVP_NONSPIKING_ACT_FILE_TYPE, "%s is not a dense activity file.\n");
   FatalIf(header.dataType != BufferUtils::FLOAT, "%s does not have dataType=float.\n");

   int batchElementsPerBlock = batchElementsPerProcess * mpiBlock.getBatchDimension();

   int const numFrames  = header.nBands;
   int const numNeurons = header.nx * header.ny * header.nf;

   double frameTime    = std::strtod("NAN", nullptr);
   int localBatchIndex = 0;
   Buffer<float> buffer(header.nx, header.ny, header.nf);

   bool errorFound = false;
   for (int frame = 0; frame < numFrames; frame++) {
      double newTime  = BufferUtils::readFrame<float>(outputStatePreStream, &buffer);
      localBatchIndex = (newTime == frameTime) ? localBatchIndex + 1 : 0;
      if (localBatchIndex != frame % batchElementsPerBlock) {
         ErrorLog().printf(
               "%s, frame %d appears to be local batch index %d of time %f; expected local batch "
               "index %d of time %f.\n",
               path.c_str(),
               frame,
               localBatchIndex,
               newTime,
               frame % batchElementsPerBlock,
               (double)(frame / batchElementsPerBlock)); // Integer division
      }
      frameTime = newTime;
      for (int k = 0; k < numNeurons; k++) {
         int x          = kxPos(k, header.nx, header.ny, header.nf);
         int y          = kyPos(k, header.nx, header.ny, header.nf);
         int f          = featureIndex(k, header.nx, header.ny, header.nf);
         float observed = buffer.at(x, y, f);
         float expected = 1.0f;
         if (observed != expected) {
            ErrorLog().printf(
                  "%s, frame %d, t = %f, local batch index = %d, global batch index %d, x = %d, y "
                  "= %d, f = %d: expected %f, observed %f.\n",
                  path.c_str(),
                  frame,
                  frameTime,
                  localBatchIndex,
                  localBatchIndex + mpiBlock.getStartBatch() * batchElementsPerProcess,
                  x,
                  y,
                  f,
                  (double)expected,
                  (double)observed);
            errorFound = true;
         }
      }
   }
   FatalIf(errorFound, "Error in Pre.pvp\n");
}

void verifyOutputStatePost(
      std::string const &path,
      MPIBlock const &mpiBlock,
      int batchElementsPerProcess) {
   FileStream outputStatePostStream(path.c_str(), std::ios_base::in);
   auto header = BufferUtils::readActivityHeader(outputStatePostStream);
   FatalIf(header.fileType != PVP_NONSPIKING_ACT_FILE_TYPE, "%s is not a dense activity file.\n");
   FatalIf(header.dataType != BufferUtils::FLOAT, "%s does not have dataType=float.\n");

   int batchElementsPerBlock = batchElementsPerProcess * mpiBlock.getBatchDimension();

   int const numFrames = header.nBands;

   int numNeurons       = header.nx * header.ny * header.nf;
   int nxGlobal         = header.nx * (mpiBlock.getGlobalNumColumns() / mpiBlock.getNumColumns());
   int nyGlobal         = header.ny * (mpiBlock.getGlobalNumRows() / mpiBlock.getNumRows());
   int numNeuronsGlobal = nxGlobal * nyGlobal * header.nf;
   int kx0              = header.nx * (mpiBlock.getStartColumn() / mpiBlock.getNumColumns());
   int ky0              = header.ny * (mpiBlock.getStartRow() / mpiBlock.getNumRows());

   double frameTime    = std::strtod("NAN", nullptr);
   int localBatchIndex = 0;
   Buffer<float> buffer(header.nx, header.ny, header.nf);

   bool errorFound = false;
   for (int frame = 0; frame < numFrames; frame++) {
      double newTime  = BufferUtils::readFrame<float>(outputStatePostStream, &buffer);
      localBatchIndex = (newTime == frameTime) ? localBatchIndex + 1 : 0;
      if (localBatchIndex != frame % batchElementsPerBlock) {
         ErrorLog().printf(
               "%s, frame %d appears to be local batch index %d of time %f; expected local batch "
               "index %d of time %f.\n",
               path.c_str(),
               frame,
               localBatchIndex,
               newTime,
               frame % batchElementsPerBlock,
               (double)(frame / batchElementsPerBlock)); // Integer division
      }
      frameTime = newTime;
      for (int k = 0; k < numNeurons; k++) {
         int x                = kxPos(k, header.nx, header.ny, header.nf);
         int y                = kyPos(k, header.nx, header.ny, header.nf);
         int f                = featureIndex(k, header.nx, header.ny, header.nf);
         float observed       = buffer.at(x, y, f);
         int batchIndexOffset = mpiBlock.getStartBatch() * batchElementsPerProcess;
         int globalBatchIndex = localBatchIndex + batchIndexOffset;
         int xGlobal          = x + kx0;
         int yGlobal          = y + ky0;
         int kGlobal          = kIndex(x + kx0, y + ky0, f, nxGlobal, nyGlobal, header.nf);
         float expected = (float)frameTime * (float)(globalBatchIndex * numNeuronsGlobal + kGlobal);
         if (observed != expected) {
            ErrorLog().printf(
                  "%s, frame %d, t = %f, local batch index = %d, global batch index %d, local "
                  "coordinates (x,y,f) = (%d,%d,%d), global coordinates (x,y,f) = (%d,%d,%d), "
                  "local index %d, global index %d: expected %f, observed %f.\n",
                  path.c_str(),
                  frame,
                  frameTime,
                  localBatchIndex,
                  globalBatchIndex,
                  x,
                  y,
                  f,
                  xGlobal,
                  yGlobal,
                  f,
                  k,
                  kGlobal,
                  (double)expected,
                  (double)observed);
            errorFound = true;
         }
      }
   }
   FatalIf(errorFound, "Error in Post.pvp\n");
}

void verifyOutputStateSharedWeights(std::string const &path, MPIBlock const &mpiBlock) {

   // FileStream does not make the file size available, but calls Fatal() if you read past the end,
   // so we need to get the file size.
   struct stat fileStat;
   int statstatus = stat(path.c_str(), &fileStat);
   FatalIf(statstatus != 0, "stat \"%s\" failed: %s\n", path.c_str(), strerror(errno));
   FatalIf(!S_ISREG(fileStat.st_mode), "\"%s\" is not a regular file.\n", path.c_str());
   long const fileSize = (long)fileStat.st_size;

   FileStream fileStream(path.c_str(), std::ios_base::in);

   bool errorFound = false;
   while (fileStream.getInPos() < fileSize) {
      long frameStart = fileStream.getInPos();
      BufferUtils::WeightHeader weightHeader;
      fileStream.read(&weightHeader, sizeof(weightHeader));
      FatalIf(
            weightHeader.baseHeader.fileType != PVP_KERNEL_FILE_TYPE,
            "%s is not a shared-weights file.\n");
      FatalIf(
            weightHeader.baseHeader.dataType != BufferUtils::FLOAT,
            "%s does not have dataType=float.\n");

      int const nxp = weightHeader.nxp;
      int const nyp = weightHeader.nyp;
      int const nfp = weightHeader.nfp;
      int patchSize = nxp * nyp * nfp;
      std::vector<float> weightBuffer(patchSize);
      int const numPatches = weightHeader.numPatches;
      int const numArbors  = weightHeader.baseHeader.nBands;

      for (int a = 0; a < numArbors; a++) {
         for (int p = 0; p < numPatches; p++) {
            long patchStart = fileStream.getInPos();
            short patchDims[2];
            fileStream.read(patchDims, (size_t)2 * sizeof(*patchDims));
            int offset;
            fileStream.read(&offset, sizeof(offset));
            FatalIf(
                  (int)patchDims[0] != nxp,
                  "Shared-weights file %s: frame starting at %ld, "
                  "arbor %d, patch %d: nx is not header's nxp. (%d vs %d)\n",
                  path.c_str(),
                  frameStart,
                  a,
                  p,
                  (int)patchDims[0],
                  nxp);
            FatalIf(
                  (int)patchDims[1] != nyp,
                  "Shared-weights file %s: frame starting at %ld, "
                  "arbor %d, patch %d: ny is not header's nyp. (%d vs %d)\n",
                  path.c_str(),
                  frameStart,
                  a,
                  p,
                  (int)patchDims[1],
                  nyp);
            FatalIf(
                  offset != 0,
                  "Shared-weights file %s: frame starting at %ld, arbor %d, patch "
                  "%d: offset is not 0.\n");

            fileStream.read(weightBuffer.data(), weightBuffer.size() * sizeof(float));
            for (int index = 0; index < patchSize; index++) {
               float observed = weightBuffer[index];
               float expected = (float)index + (float)weightHeader.baseHeader.timestamp;
               if (observed != expected) {
                  ErrorLog().printf(
                        "%s, frame starting at %ld, patch starting at %ld, index %d: expected %f, "
                        "observed %f.\n",
                        path.c_str(),
                        frameStart,
                        patchStart,
                        index,
                        (double)expected,
                        (double)observed);
               }
            }
         }
      }
      Buffer<float> buffer(weightHeader.nxp, weightHeader.nyp, weightHeader.nfp);
   }
   FatalIf(errorFound, "Error in SharedWeights.pvp\n");
}
<|endoftext|>


<commit_before>// Copyright (c) 2010 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "chrome/browser/chromeos/setting_level_bubble_view.h"

#include <string>

#include "base/logging.h"
#include "third_party/skia/include/core/SkBitmap.h"
#include "ui/gfx/canvas.h"
#include "views/controls/progress_bar.h"

using views::Background;
using views::View;
using views::Widget;

namespace {

// Bubble metrics.
const int kWidth = 350, kHeight = 100;
const int kPadding = 20;
const int kProgressBarWidth = 211;
const int kProgressBarHeight = 17;

}  // namespace

namespace chromeos {

SettingLevelBubbleView::SettingLevelBubbleView()
    : progress_bar_(NULL),
      icon_(NULL) {
}

void SettingLevelBubbleView::Init(SkBitmap* icon, int level_percent) {
  DCHECK(icon);
  DCHECK(level_percent >= 0 && level_percent <= 100);
  icon_ = icon;
  progress_bar_ = new views::ProgressBar();
  AddChildView(progress_bar_);
  Update(level_percent);
}

void SettingLevelBubbleView::SetIcon(SkBitmap* icon) {
  DCHECK(icon);
  icon_ = icon;
  SchedulePaint();
}

void SettingLevelBubbleView::Update(int level_percent) {
  DCHECK(level_percent >= 0 && level_percent <= 100);
  progress_bar_->SetProgress(level_percent);
}

void SettingLevelBubbleView::OnPaint(gfx::Canvas* canvas) {
  views::View::OnPaint(canvas);
  canvas->DrawBitmapInt(*icon_, kPadding, (height() - icon_->height()) / 2);
}

void SettingLevelBubbleView::Layout() {
  progress_bar_->SetBounds(width() - kPadding - kProgressBarWidth,
                           (height() - kProgressBarHeight) / 2,
                           kProgressBarWidth, kProgressBarHeight);
}

gfx::Size SettingLevelBubbleView::GetPreferredSize() {
  return gfx::Size(kWidth, kHeight);
}

}  // namespace chromeos
<commit_msg>Mirror the volume/brightness level bubble views for right-to-left UIs.  Doing this also fixes the overlapping icon problem (see bug).<commit_after>// Copyright (c) 2011 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "chrome/browser/chromeos/setting_level_bubble_view.h"

#include <string>

#include "base/logging.h"
#include "third_party/skia/include/core/SkBitmap.h"
#include "ui/gfx/canvas.h"
#include "views/controls/progress_bar.h"

using views::Background;
using views::View;
using views::Widget;

namespace {

// Bubble metrics.
const int kWidth = 350, kHeight = 100;
const int kPadding = 20;
const int kProgressBarWidth = 211;
const int kProgressBarHeight = 17;

}  // namespace

namespace chromeos {

SettingLevelBubbleView::SettingLevelBubbleView()
    : progress_bar_(NULL),
      icon_(NULL) {
}

void SettingLevelBubbleView::Init(SkBitmap* icon, int level_percent) {
  DCHECK(icon);
  DCHECK(level_percent >= 0 && level_percent <= 100);
  icon_ = icon;
  progress_bar_ = new views::ProgressBar();
  AddChildView(progress_bar_);
  Update(level_percent);
  progress_bar_->EnableCanvasFlippingForRTLUI(true);
  EnableCanvasFlippingForRTLUI(true);
}

void SettingLevelBubbleView::SetIcon(SkBitmap* icon) {
  DCHECK(icon);
  icon_ = icon;
  SchedulePaint();
}

void SettingLevelBubbleView::Update(int level_percent) {
  DCHECK(level_percent >= 0 && level_percent <= 100);
  progress_bar_->SetProgress(level_percent);
}

void SettingLevelBubbleView::OnPaint(gfx::Canvas* canvas) {
  views::View::OnPaint(canvas);
  canvas->DrawBitmapInt(*icon_, kPadding, (height() - icon_->height()) / 2);
}

void SettingLevelBubbleView::Layout() {
  progress_bar_->SetBounds(width() - kPadding - kProgressBarWidth,
                           (height() - kProgressBarHeight) / 2,
                           kProgressBarWidth, kProgressBarHeight);
}

gfx::Size SettingLevelBubbleView::GetPreferredSize() {
  return gfx::Size(kWidth, kHeight);
}

}  // namespace chromeos
<|endoftext|>


<commit_before>// Copyright (c) 2010 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "chrome/browser/gtk/clear_browsing_data_dialog_gtk.h"

#include <string>

#include "app/l10n_util.h"
#include "app/resource_bundle.h"
#include "chrome/browser/browser.h"
#include "chrome/browser/browsing_data_remover.h"
#include "chrome/browser/gtk/accessible_widget_helper_gtk.h"
#include "chrome/browser/gtk/browser_window_gtk.h"
#include "chrome/browser/gtk/gtk_chrome_link_button.h"
#include "chrome/browser/gtk/gtk_util.h"
#include "chrome/browser/pref_service.h"
#include "chrome/browser/profile.h"
#include "chrome/common/pref_names.h"
#include "grit/generated_resources.h"
#include "grit/locale_settings.h"

namespace {

// Returns true if the checkbox is checked.
gboolean IsChecked(GtkWidget* widget) {
  return gtk_toggle_button_get_active(GTK_TOGGLE_BUTTON(widget));
}

}  // namespace

// static
void ClearBrowsingDataDialogGtk::Show(GtkWindow* parent, Profile* profile) {
  new ClearBrowsingDataDialogGtk(parent, profile);
}

ClearBrowsingDataDialogGtk::ClearBrowsingDataDialogGtk(GtkWindow* parent,
                                                       Profile* profile) :
    profile_(profile), remover_(NULL) {
  // Build the dialog.
  std::string dialog_name = l10n_util::GetStringUTF8(
      IDS_CLEAR_BROWSING_DATA_TITLE);
  dialog_ = gtk_dialog_new_with_buttons(
      dialog_name.c_str(),
      parent,
      (GtkDialogFlags) (GTK_DIALOG_MODAL | GTK_DIALOG_NO_SEPARATOR),
      GTK_STOCK_CLOSE,
      GTK_RESPONSE_REJECT,
      NULL);

  accessible_widget_helper_.reset(new AccessibleWidgetHelper(dialog_, profile));
  accessible_widget_helper_->SendOpenWindowNotification(dialog_name);

  gtk_util::AddButtonToDialog(dialog_,
      l10n_util::GetStringUTF8(IDS_CLEAR_BROWSING_DATA_COMMIT).c_str(),
      GTK_STOCK_APPLY, GTK_RESPONSE_ACCEPT);

  GtkWidget* content_area = GTK_DIALOG(dialog_)->vbox;
  gtk_box_set_spacing(GTK_BOX(content_area), gtk_util::kContentAreaSpacing);

  GtkWidget* vbox = gtk_vbox_new(FALSE, gtk_util::kControlSpacing);
  gtk_container_add(GTK_CONTAINER(content_area), vbox);

  // Label on top of the checkboxes.
  GtkWidget* description = gtk_label_new(
      l10n_util::GetStringUTF8(IDS_CLEAR_BROWSING_DATA_LABEL).c_str());
  gtk_misc_set_alignment(GTK_MISC(description), 0, 0);
  gtk_box_pack_start(GTK_BOX(vbox), description, FALSE, FALSE, 0);

  // History checkbox.
  del_history_checkbox_ = gtk_check_button_new_with_label(
      l10n_util::GetStringUTF8(IDS_DEL_BROWSING_HISTORY_CHKBOX).c_str());
  gtk_box_pack_start(GTK_BOX(vbox), del_history_checkbox_, FALSE, FALSE, 0);
  gtk_toggle_button_set_active(GTK_TOGGLE_BUTTON(del_history_checkbox_),
      profile_->GetPrefs()->GetBoolean(prefs::kDeleteBrowsingHistory));
  g_signal_connect(del_history_checkbox_, "toggled",
                   G_CALLBACK(OnDialogWidgetClickedThunk), this);

  // Downloads checkbox.
  del_downloads_checkbox_ = gtk_check_button_new_with_label(
      l10n_util::GetStringUTF8(IDS_DEL_DOWNLOAD_HISTORY_CHKBOX).c_str());
  gtk_box_pack_start(GTK_BOX(vbox), del_downloads_checkbox_, FALSE, FALSE, 0);
  gtk_toggle_button_set_active(GTK_TOGGLE_BUTTON(del_downloads_checkbox_),
      profile_->GetPrefs()->GetBoolean(prefs::kDeleteDownloadHistory));
  g_signal_connect(del_downloads_checkbox_, "toggled",
                   G_CALLBACK(OnDialogWidgetClickedThunk), this);

  // Cache checkbox.
  del_cache_checkbox_ = gtk_check_button_new_with_label(
      l10n_util::GetStringUTF8(IDS_DEL_CACHE_CHKBOX).c_str());
  gtk_box_pack_start(GTK_BOX(vbox), del_cache_checkbox_, FALSE, FALSE, 0);
  gtk_toggle_button_set_active(GTK_TOGGLE_BUTTON(del_cache_checkbox_),
      profile_->GetPrefs()->GetBoolean(prefs::kDeleteCache));
  g_signal_connect(del_cache_checkbox_, "toggled",
                   G_CALLBACK(OnDialogWidgetClickedThunk), this);

  // Cookies checkbox.
  del_cookies_checkbox_ = gtk_check_button_new_with_label(
      l10n_util::GetStringUTF8(IDS_DEL_COOKIES_CHKBOX).c_str());
  gtk_box_pack_start(GTK_BOX(vbox), del_cookies_checkbox_, FALSE, FALSE, 0);
  gtk_toggle_button_set_active(GTK_TOGGLE_BUTTON(del_cookies_checkbox_),
      profile_->GetPrefs()->GetBoolean(prefs::kDeleteCookies));
  g_signal_connect(del_cookies_checkbox_, "toggled",
                   G_CALLBACK(OnDialogWidgetClickedThunk), this);

  // Passwords checkbox.
  del_passwords_checkbox_ = gtk_check_button_new_with_label(
      l10n_util::GetStringUTF8(IDS_DEL_PASSWORDS_CHKBOX).c_str());
  gtk_box_pack_start(GTK_BOX(vbox), del_passwords_checkbox_, FALSE, FALSE, 0);
  gtk_toggle_button_set_active(GTK_TOGGLE_BUTTON(del_passwords_checkbox_),
      profile_->GetPrefs()->GetBoolean(prefs::kDeletePasswords));
  g_signal_connect(del_passwords_checkbox_, "toggled",
                   G_CALLBACK(OnDialogWidgetClickedThunk), this);

  // Form data checkbox.
  del_form_data_checkbox_ = gtk_check_button_new_with_label(
      l10n_util::GetStringUTF8(IDS_DEL_FORM_DATA_CHKBOX).c_str());
  gtk_box_pack_start(GTK_BOX(vbox), del_form_data_checkbox_, FALSE, FALSE, 0);
  gtk_toggle_button_set_active(GTK_TOGGLE_BUTTON(del_form_data_checkbox_),
      profile_->GetPrefs()->GetBoolean(prefs::kDeleteFormData));
  g_signal_connect(del_form_data_checkbox_, "toggled",
                   G_CALLBACK(OnDialogWidgetClickedThunk), this);

  // Create a horizontal layout for the combo box and label.
  GtkWidget* combo_hbox = gtk_hbox_new(FALSE, gtk_util::kLabelSpacing);
  GtkWidget* time_period_label_ = gtk_label_new(
      l10n_util::GetStringUTF8(IDS_CLEAR_BROWSING_DATA_TIME_LABEL).c_str());
  gtk_box_pack_start(GTK_BOX(combo_hbox), time_period_label_, FALSE, FALSE, 0);

  // Time period combo box items.
  time_period_combobox_ = gtk_combo_box_new_text();
  gtk_combo_box_append_text(GTK_COMBO_BOX(time_period_combobox_),
      l10n_util::GetStringUTF8(IDS_CLEAR_DATA_HOUR).c_str());
  gtk_combo_box_append_text(GTK_COMBO_BOX(time_period_combobox_),
      l10n_util::GetStringUTF8(IDS_CLEAR_DATA_DAY).c_str());
  gtk_combo_box_append_text(GTK_COMBO_BOX(time_period_combobox_),
      l10n_util::GetStringUTF8(IDS_CLEAR_DATA_WEEK).c_str());
  gtk_combo_box_append_text(GTK_COMBO_BOX(time_period_combobox_),
      l10n_util::GetStringUTF8(IDS_CLEAR_DATA_4WEEKS).c_str());
  gtk_combo_box_append_text(GTK_COMBO_BOX(time_period_combobox_),
      l10n_util::GetStringUTF8(IDS_CLEAR_DATA_EVERYTHING).c_str());
  gtk_combo_box_set_active(GTK_COMBO_BOX(time_period_combobox_),
      profile_->GetPrefs()->GetInteger(prefs::kDeleteTimePeriod));
  gtk_box_pack_start(GTK_BOX(combo_hbox),
                     time_period_combobox_, FALSE, FALSE, 0);
  g_signal_connect(time_period_combobox_, "changed",
                   G_CALLBACK(OnDialogWidgetClickedThunk), this);

  // Add the combo/label time period box to the vertical layout.
  gtk_box_pack_start(GTK_BOX(vbox), combo_hbox, FALSE, FALSE, 0);

  // Add widgets for the area below the accept buttons.
  GtkWidget* flash_link = gtk_chrome_link_button_new(
      l10n_util::GetStringUTF8(IDS_FLASH_STORAGE_SETTINGS).c_str());
  g_signal_connect(G_OBJECT(flash_link), "clicked",
                   G_CALLBACK(OnFlashLinkClickedThunk), this);
  GtkWidget* flash_link_hbox = gtk_hbox_new(FALSE, 0);
  gtk_box_pack_start(GTK_BOX(flash_link_hbox), flash_link, FALSE, FALSE, 0);
  gtk_box_pack_end(GTK_BOX(content_area), flash_link_hbox, FALSE, FALSE, 0);

  GtkWidget* separator = gtk_hseparator_new();
  gtk_box_pack_end(GTK_BOX(content_area), separator, FALSE, FALSE, 0);

  // Make sure we can move things around.
  DCHECK_EQ(GTK_DIALOG(dialog_)->action_area->parent, content_area);

  // Now rearrange those because they're *above* the accept buttons...there's
  // no way to place them in the correct position with gtk_box_pack_end() so
  // manually move things into the correct order.
  gtk_box_reorder_child(GTK_BOX(content_area), flash_link_hbox, -1);
  gtk_box_reorder_child(GTK_BOX(content_area), separator, -1);
  gtk_box_reorder_child(GTK_BOX(content_area), GTK_DIALOG(dialog_)->action_area,
                        -1);

  g_signal_connect(dialog_, "response",
                   G_CALLBACK(OnDialogResponseThunk), this);

  UpdateDialogButtons();

  gtk_util::ShowDialogWithLocalizedSize(dialog_,
                                        IDS_CLEARDATA_DIALOG_WIDTH_CHARS,
                                        -1,
                                        false);
}

ClearBrowsingDataDialogGtk::~ClearBrowsingDataDialogGtk() {
}

void ClearBrowsingDataDialogGtk::OnDialogResponse(GtkWidget* widget,
                                                  int response) {
  if (response == GTK_RESPONSE_ACCEPT) {
    int period_selected = gtk_combo_box_get_active(
        GTK_COMBO_BOX(time_period_combobox_));

    // BrowsingDataRemover deletes itself when done.
    remover_ = new BrowsingDataRemover(profile_,
        static_cast<BrowsingDataRemover::TimePeriod>(period_selected),
        base::Time());
    remover_->Remove(GetCheckedItems());
  }

  delete this;
  gtk_widget_destroy(GTK_WIDGET(widget));
}

void ClearBrowsingDataDialogGtk::OnDialogWidgetClicked(GtkWidget* widget) {
  if (widget == del_history_checkbox_) {
    profile_->GetPrefs()->SetBoolean(prefs::kDeleteBrowsingHistory,
                                     IsChecked(widget));
  } else if (widget == del_downloads_checkbox_) {
    profile_->GetPrefs()->SetBoolean(prefs::kDeleteDownloadHistory,
                                     IsChecked(widget));
  } else if (widget == del_cache_checkbox_) {
    profile_->GetPrefs()->SetBoolean(prefs::kDeleteCache,
                                     IsChecked(widget));
  } else if (widget == del_cookies_checkbox_) {
    profile_->GetPrefs()->SetBoolean(prefs::kDeleteCookies,
                                     IsChecked(widget));
  } else if (widget == del_passwords_checkbox_) {
    profile_->GetPrefs()->SetBoolean(prefs::kDeletePasswords,
                                     IsChecked(widget));
  } else if (widget == del_form_data_checkbox_) {
    profile_->GetPrefs()->SetBoolean(prefs::kDeleteFormData,
                                     IsChecked(widget));
  } else if (widget == time_period_combobox_) {
    profile_->GetPrefs()->SetInteger(prefs::kDeleteTimePeriod,
        gtk_combo_box_get_active(GTK_COMBO_BOX(widget)));
  }
  UpdateDialogButtons();
}

void ClearBrowsingDataDialogGtk::OnFlashLinkClicked(GtkWidget* button) {
  // We open a new browser window so the Options dialog doesn't get lost
  // behind other windows.
  Browser* browser = Browser::Create(profile_);
  browser->OpenURL(GURL(l10n_util::GetStringUTF8(IDS_FLASH_STORAGE_URL)),
                   GURL(), NEW_FOREGROUND_TAB, PageTransition::LINK);
  browser->window()->Show();
}

void ClearBrowsingDataDialogGtk::UpdateDialogButtons() {
  gtk_dialog_set_response_sensitive(GTK_DIALOG(dialog_), GTK_RESPONSE_ACCEPT,
                                    GetCheckedItems() != 0);
}

int ClearBrowsingDataDialogGtk::GetCheckedItems() {
  int items = 0;
  if (IsChecked(del_history_checkbox_))
    items |= BrowsingDataRemover::REMOVE_HISTORY;
  if (IsChecked(del_downloads_checkbox_))
    items |= BrowsingDataRemover::REMOVE_DOWNLOADS;
  if (IsChecked(del_cookies_checkbox_))
    items |= BrowsingDataRemover::REMOVE_COOKIES;
  if (IsChecked(del_passwords_checkbox_))
    items |= BrowsingDataRemover::REMOVE_PASSWORDS;
  if (IsChecked(del_form_data_checkbox_))
    items |= BrowsingDataRemover::REMOVE_FORM_DATA;
  if (IsChecked(del_cache_checkbox_))
    items |= BrowsingDataRemover::REMOVE_CACHE;
  return items;
}
<commit_msg>Make "Clear Browser Data" dialog wider for ja.<commit_after>// Copyright (c) 2010 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "chrome/browser/gtk/clear_browsing_data_dialog_gtk.h"

#include <string>

#include "app/l10n_util.h"
#include "app/resource_bundle.h"
#include "chrome/browser/browser.h"
#include "chrome/browser/browsing_data_remover.h"
#include "chrome/browser/gtk/accessible_widget_helper_gtk.h"
#include "chrome/browser/gtk/browser_window_gtk.h"
#include "chrome/browser/gtk/gtk_chrome_link_button.h"
#include "chrome/browser/gtk/gtk_util.h"
#include "chrome/browser/pref_service.h"
#include "chrome/browser/profile.h"
#include "chrome/common/pref_names.h"
#include "grit/generated_resources.h"
#include "grit/locale_settings.h"

namespace {

// Returns true if the checkbox is checked.
gboolean IsChecked(GtkWidget* widget) {
  return gtk_toggle_button_get_active(GTK_TOGGLE_BUTTON(widget));
}

}  // namespace

// static
void ClearBrowsingDataDialogGtk::Show(GtkWindow* parent, Profile* profile) {
  new ClearBrowsingDataDialogGtk(parent, profile);
}

ClearBrowsingDataDialogGtk::ClearBrowsingDataDialogGtk(GtkWindow* parent,
                                                       Profile* profile) :
    profile_(profile), remover_(NULL) {
  // Build the dialog.
  std::string dialog_name = l10n_util::GetStringUTF8(
      IDS_CLEAR_BROWSING_DATA_TITLE);
  dialog_ = gtk_dialog_new_with_buttons(
      dialog_name.c_str(),
      parent,
      (GtkDialogFlags) (GTK_DIALOG_MODAL | GTK_DIALOG_NO_SEPARATOR),
      GTK_STOCK_CLOSE,
      GTK_RESPONSE_REJECT,
      NULL);

  accessible_widget_helper_.reset(new AccessibleWidgetHelper(dialog_, profile));
  accessible_widget_helper_->SendOpenWindowNotification(dialog_name);

  gtk_util::AddButtonToDialog(dialog_,
      l10n_util::GetStringUTF8(IDS_CLEAR_BROWSING_DATA_COMMIT).c_str(),
      GTK_STOCK_APPLY, GTK_RESPONSE_ACCEPT);

  GtkWidget* content_area = GTK_DIALOG(dialog_)->vbox;
  gtk_box_set_spacing(GTK_BOX(content_area), gtk_util::kContentAreaSpacing);

  GtkWidget* vbox = gtk_vbox_new(FALSE, gtk_util::kControlSpacing);
  gtk_container_add(GTK_CONTAINER(content_area), vbox);

  // Label on top of the checkboxes.
  GtkWidget* description = gtk_label_new(
      l10n_util::GetStringUTF8(IDS_CLEAR_BROWSING_DATA_LABEL).c_str());
  gtk_misc_set_alignment(GTK_MISC(description), 0, 0);
  gtk_box_pack_start(GTK_BOX(vbox), description, FALSE, FALSE, 0);

  // History checkbox.
  del_history_checkbox_ = gtk_check_button_new_with_label(
      l10n_util::GetStringUTF8(IDS_DEL_BROWSING_HISTORY_CHKBOX).c_str());
  gtk_box_pack_start(GTK_BOX(vbox), del_history_checkbox_, FALSE, FALSE, 0);
  gtk_toggle_button_set_active(GTK_TOGGLE_BUTTON(del_history_checkbox_),
      profile_->GetPrefs()->GetBoolean(prefs::kDeleteBrowsingHistory));
  g_signal_connect(del_history_checkbox_, "toggled",
                   G_CALLBACK(OnDialogWidgetClickedThunk), this);

  // Downloads checkbox.
  del_downloads_checkbox_ = gtk_check_button_new_with_label(
      l10n_util::GetStringUTF8(IDS_DEL_DOWNLOAD_HISTORY_CHKBOX).c_str());
  gtk_box_pack_start(GTK_BOX(vbox), del_downloads_checkbox_, FALSE, FALSE, 0);
  gtk_toggle_button_set_active(GTK_TOGGLE_BUTTON(del_downloads_checkbox_),
      profile_->GetPrefs()->GetBoolean(prefs::kDeleteDownloadHistory));
  g_signal_connect(del_downloads_checkbox_, "toggled",
                   G_CALLBACK(OnDialogWidgetClickedThunk), this);

  // Cache checkbox.
  del_cache_checkbox_ = gtk_check_button_new_with_label(
      l10n_util::GetStringUTF8(IDS_DEL_CACHE_CHKBOX).c_str());
  gtk_box_pack_start(GTK_BOX(vbox), del_cache_checkbox_, FALSE, FALSE, 0);
  gtk_toggle_button_set_active(GTK_TOGGLE_BUTTON(del_cache_checkbox_),
      profile_->GetPrefs()->GetBoolean(prefs::kDeleteCache));
  g_signal_connect(del_cache_checkbox_, "toggled",
                   G_CALLBACK(OnDialogWidgetClickedThunk), this);

  // Cookies checkbox.
  del_cookies_checkbox_ = gtk_check_button_new_with_label(
      l10n_util::GetStringUTF8(IDS_DEL_COOKIES_CHKBOX).c_str());
  gtk_box_pack_start(GTK_BOX(vbox), del_cookies_checkbox_, FALSE, FALSE, 0);
  gtk_toggle_button_set_active(GTK_TOGGLE_BUTTON(del_cookies_checkbox_),
      profile_->GetPrefs()->GetBoolean(prefs::kDeleteCookies));
  g_signal_connect(del_cookies_checkbox_, "toggled",
                   G_CALLBACK(OnDialogWidgetClickedThunk), this);

  // Passwords checkbox.
  del_passwords_checkbox_ = gtk_check_button_new_with_label(
      l10n_util::GetStringUTF8(IDS_DEL_PASSWORDS_CHKBOX).c_str());
  gtk_box_pack_start(GTK_BOX(vbox), del_passwords_checkbox_, FALSE, FALSE, 0);
  gtk_toggle_button_set_active(GTK_TOGGLE_BUTTON(del_passwords_checkbox_),
      profile_->GetPrefs()->GetBoolean(prefs::kDeletePasswords));
  g_signal_connect(del_passwords_checkbox_, "toggled",
                   G_CALLBACK(OnDialogWidgetClickedThunk), this);

  // Form data checkbox.
  del_form_data_checkbox_ = gtk_check_button_new_with_label(
      l10n_util::GetStringUTF8(IDS_DEL_FORM_DATA_CHKBOX).c_str());
  gtk_box_pack_start(GTK_BOX(vbox), del_form_data_checkbox_, FALSE, FALSE, 0);
  gtk_toggle_button_set_active(GTK_TOGGLE_BUTTON(del_form_data_checkbox_),
      profile_->GetPrefs()->GetBoolean(prefs::kDeleteFormData));
  g_signal_connect(del_form_data_checkbox_, "toggled",
                   G_CALLBACK(OnDialogWidgetClickedThunk), this);

  // Create a horizontal layout for the combo box and label.
  GtkWidget* combo_hbox = gtk_hbox_new(FALSE, gtk_util::kLabelSpacing);
  GtkWidget* time_period_label_ = gtk_label_new(
      l10n_util::GetStringUTF8(IDS_CLEAR_BROWSING_DATA_TIME_LABEL).c_str());
  gtk_box_pack_start(GTK_BOX(combo_hbox), time_period_label_, FALSE, FALSE, 0);

  // Time period combo box items.
  time_period_combobox_ = gtk_combo_box_new_text();
  gtk_combo_box_append_text(GTK_COMBO_BOX(time_period_combobox_),
      l10n_util::GetStringUTF8(IDS_CLEAR_DATA_HOUR).c_str());
  gtk_combo_box_append_text(GTK_COMBO_BOX(time_period_combobox_),
      l10n_util::GetStringUTF8(IDS_CLEAR_DATA_DAY).c_str());
  gtk_combo_box_append_text(GTK_COMBO_BOX(time_period_combobox_),
      l10n_util::GetStringUTF8(IDS_CLEAR_DATA_WEEK).c_str());
  gtk_combo_box_append_text(GTK_COMBO_BOX(time_period_combobox_),
      l10n_util::GetStringUTF8(IDS_CLEAR_DATA_4WEEKS).c_str());
  gtk_combo_box_append_text(GTK_COMBO_BOX(time_period_combobox_),
      l10n_util::GetStringUTF8(IDS_CLEAR_DATA_EVERYTHING).c_str());
  gtk_combo_box_set_active(GTK_COMBO_BOX(time_period_combobox_),
      profile_->GetPrefs()->GetInteger(prefs::kDeleteTimePeriod));
  gtk_box_pack_start(GTK_BOX(combo_hbox),
                     time_period_combobox_, FALSE, FALSE, 0);
  g_signal_connect(time_period_combobox_, "changed",
                   G_CALLBACK(OnDialogWidgetClickedThunk), this);

  // Add the combo/label time period box to the vertical layout.
  gtk_box_pack_start(GTK_BOX(vbox), combo_hbox, FALSE, FALSE, 0);

  // Add widgets for the area below the accept buttons.
  GtkWidget* flash_link = gtk_chrome_link_button_new(
      l10n_util::GetStringUTF8(IDS_FLASH_STORAGE_SETTINGS).c_str());
  g_signal_connect(G_OBJECT(flash_link), "clicked",
                   G_CALLBACK(OnFlashLinkClickedThunk), this);
  GtkWidget* flash_link_hbox = gtk_hbox_new(FALSE, 0);
  gtk_box_pack_start(GTK_BOX(flash_link_hbox), flash_link, FALSE, FALSE, 0);
  gtk_box_pack_end(GTK_BOX(content_area), flash_link_hbox, FALSE, FALSE, 0);

  GtkWidget* separator = gtk_hseparator_new();
  gtk_box_pack_end(GTK_BOX(content_area), separator, FALSE, FALSE, 0);

  // Make sure we can move things around.
  DCHECK_EQ(GTK_DIALOG(dialog_)->action_area->parent, content_area);

  // Now rearrange those because they're *above* the accept buttons...there's
  // no way to place them in the correct position with gtk_box_pack_end() so
  // manually move things into the correct order.
  gtk_box_reorder_child(GTK_BOX(content_area), flash_link_hbox, -1);
  gtk_box_reorder_child(GTK_BOX(content_area), separator, -1);
  gtk_box_reorder_child(GTK_BOX(content_area), GTK_DIALOG(dialog_)->action_area,
                        -1);

  g_signal_connect(dialog_, "response",
                   G_CALLBACK(OnDialogResponseThunk), this);

  UpdateDialogButtons();

  gtk_util::ShowModalDialogWithMinLocalizedWidth(dialog_,
      IDS_CLEARDATA_DIALOG_WIDTH_CHARS);
}

ClearBrowsingDataDialogGtk::~ClearBrowsingDataDialogGtk() {
}

void ClearBrowsingDataDialogGtk::OnDialogResponse(GtkWidget* widget,
                                                  int response) {
  if (response == GTK_RESPONSE_ACCEPT) {
    int period_selected = gtk_combo_box_get_active(
        GTK_COMBO_BOX(time_period_combobox_));

    // BrowsingDataRemover deletes itself when done.
    remover_ = new BrowsingDataRemover(profile_,
        static_cast<BrowsingDataRemover::TimePeriod>(period_selected),
        base::Time());
    remover_->Remove(GetCheckedItems());
  }

  delete this;
  gtk_widget_destroy(GTK_WIDGET(widget));
}

void ClearBrowsingDataDialogGtk::OnDialogWidgetClicked(GtkWidget* widget) {
  if (widget == del_history_checkbox_) {
    profile_->GetPrefs()->SetBoolean(prefs::kDeleteBrowsingHistory,
                                     IsChecked(widget));
  } else if (widget == del_downloads_checkbox_) {
    profile_->GetPrefs()->SetBoolean(prefs::kDeleteDownloadHistory,
                                     IsChecked(widget));
  } else if (widget == del_cache_checkbox_) {
    profile_->GetPrefs()->SetBoolean(prefs::kDeleteCache,
                                     IsChecked(widget));
  } else if (widget == del_cookies_checkbox_) {
    profile_->GetPrefs()->SetBoolean(prefs::kDeleteCookies,
                                     IsChecked(widget));
  } else if (widget == del_passwords_checkbox_) {
    profile_->GetPrefs()->SetBoolean(prefs::kDeletePasswords,
                                     IsChecked(widget));
  } else if (widget == del_form_data_checkbox_) {
    profile_->GetPrefs()->SetBoolean(prefs::kDeleteFormData,
                                     IsChecked(widget));
  } else if (widget == time_period_combobox_) {
    profile_->GetPrefs()->SetInteger(prefs::kDeleteTimePeriod,
        gtk_combo_box_get_active(GTK_COMBO_BOX(widget)));
  }
  UpdateDialogButtons();
}

void ClearBrowsingDataDialogGtk::OnFlashLinkClicked(GtkWidget* button) {
  // We open a new browser window so the Options dialog doesn't get lost
  // behind other windows.
  Browser* browser = Browser::Create(profile_);
  browser->OpenURL(GURL(l10n_util::GetStringUTF8(IDS_FLASH_STORAGE_URL)),
                   GURL(), NEW_FOREGROUND_TAB, PageTransition::LINK);
  browser->window()->Show();
}

void ClearBrowsingDataDialogGtk::UpdateDialogButtons() {
  gtk_dialog_set_response_sensitive(GTK_DIALOG(dialog_), GTK_RESPONSE_ACCEPT,
                                    GetCheckedItems() != 0);
}

int ClearBrowsingDataDialogGtk::GetCheckedItems() {
  int items = 0;
  if (IsChecked(del_history_checkbox_))
    items |= BrowsingDataRemover::REMOVE_HISTORY;
  if (IsChecked(del_downloads_checkbox_))
    items |= BrowsingDataRemover::REMOVE_DOWNLOADS;
  if (IsChecked(del_cookies_checkbox_))
    items |= BrowsingDataRemover::REMOVE_COOKIES;
  if (IsChecked(del_passwords_checkbox_))
    items |= BrowsingDataRemover::REMOVE_PASSWORDS;
  if (IsChecked(del_form_data_checkbox_))
    items |= BrowsingDataRemover::REMOVE_FORM_DATA;
  if (IsChecked(del_cache_checkbox_))
    items |= BrowsingDataRemover::REMOVE_CACHE;
  return items;
}
<|endoftext|>


<commit_before>#pragma once

#include <string>
#include <map>
#include <functional>
#include <vector>

namespace search
{
    using Size = long;
    //
    //  Struct Coordinate
    //
    struct Coordinate { Size y, x; };
    inline auto operator==(Coordinate lhs, Coordinate rhs) -> bool
    {
        return lhs.x == rhs.x && lhs.y == rhs.y;
    }
    //
    //  Function map for 8 directions
    //
    using Functions = std::map< char, std::function< Coordinate(Coordinate) >>;
    struct Goes : public Functions
    {
        explicit Goes()
        {
            (*this)['1'] = [](Coordinate c) -> Coordinate { return{ c.y - 1, c.x - 1 }; };
            (*this)['2'] = [](Coordinate c) -> Coordinate { return{ c.y - 1, c.x - 0 }; };
            (*this)['3'] = [](Coordinate c) -> Coordinate { return{ c.y - 1, c.x + 1 }; };
            (*this)['4'] = [](Coordinate c) -> Coordinate { return{ c.y - 0, c.x - 1 }; };
            (*this)['5'] = [](Coordinate c) -> Coordinate { return{ c.y + 0, c.x + 1 }; };
            (*this)['6'] = [](Coordinate c) -> Coordinate { return{ c.y + 1, c.x - 1 }; };
            (*this)['7'] = [](Coordinate c) -> Coordinate { return{ c.y + 1, c.x - 0 }; };
            (*this)['8'] = [](Coordinate c) -> Coordinate { return{ c.y + 1, c.x + 1 }; };
        }
    } const GOES;
    //
    //  Class Node
    //
    class Node
    {
        friend auto operator==(Node const& lhs, Node const& rhs) -> bool
        {
            return lhs._path == rhs._path && lhs._start == rhs._start && lhs._goal == rhs._goal;
        }

    public:
        using Path = std::string;
        using Children = std::vector<Node>;
        Node(Path const& path, Coordinate start, Coordinate goal)
            : _path{ path }, _start{ start }, _goal{ goal }
        { }

        auto path() const& -> Path const&
        {
            return _path;
        }

        auto start() const& -> Coordinate
        {
            return _start;
        }

        auto goal() const& -> Coordinate
        {
            return _goal;
        }

        auto coordinate() const -> Coordinate
        {
            Coordinate c = _start;
            for (auto direction : _path)
                c = GOES.at(direction)(c);
            return c;
        }

        template<typename ValidateFunc>
        auto children() const -> Children
        {
            Children children;
            ValidateFunc validate;
            for(auto direction = '1'; direction <= '8'; ++direction)
            {
                auto child = Node{ _path + direction, _start, _goal };
                if(validate(child))
                    children.push_back(child);
            }
            return children;
        }

    private:
        Path const  _path;
        Coordinate const _start;
        Coordinate const _goal;
    };
}//end of namespace<commit_msg>remove const for data members<commit_after>#pragma once

#include <string>
#include <map>
#include <functional>
#include <vector>

namespace search
{
    using Size = long;
    //
    //  Struct Coordinate
    //
    struct Coordinate { Size y, x; };
    inline auto operator==(Coordinate lhs, Coordinate rhs) -> bool
    {
        return lhs.x == rhs.x && lhs.y == rhs.y;
    }
    //
    //  Function map for 8 directions
    //
    using Functions = std::map< char, std::function< Coordinate(Coordinate) >>;
    struct Goes : public Functions
    {
        explicit Goes()
        {
            (*this)['1'] = [](Coordinate c) -> Coordinate { return{ c.y - 1, c.x - 1 }; };
            (*this)['2'] = [](Coordinate c) -> Coordinate { return{ c.y - 1, c.x - 0 }; };
            (*this)['3'] = [](Coordinate c) -> Coordinate { return{ c.y - 1, c.x + 1 }; };
            (*this)['4'] = [](Coordinate c) -> Coordinate { return{ c.y - 0, c.x - 1 }; };
            (*this)['5'] = [](Coordinate c) -> Coordinate { return{ c.y + 0, c.x + 1 }; };
            (*this)['6'] = [](Coordinate c) -> Coordinate { return{ c.y + 1, c.x - 1 }; };
            (*this)['7'] = [](Coordinate c) -> Coordinate { return{ c.y + 1, c.x - 0 }; };
            (*this)['8'] = [](Coordinate c) -> Coordinate { return{ c.y + 1, c.x + 1 }; };
        }
    } const GOES;
    //
    //  Class Node
    //
    class Node
    {
        friend auto operator==(Node const& lhs, Node const& rhs) -> bool
        {
            return lhs._path == rhs._path && lhs._start == rhs._start && lhs._goal == rhs._goal;
        }

    public:
        using Path = std::string;
        using Children = std::vector<Node>;
        Node(Path const& path, Coordinate start, Coordinate goal)
            : _path{ path }, _start{ start }, _goal{ goal }
        { }

        Node(Node const& other)
            : _path{ other._path }, _start{ other._start }, _goal{ other._goal }
        {   }

        auto path() const& -> Path const&
        {
            return _path;
        }

        auto start() const& -> Coordinate
        {
            return _start;
        }

        auto goal() const& -> Coordinate
        {
            return _goal;
        }

        auto coordinate() const -> Coordinate
        {
            Coordinate c = _start;
            for (auto direction : _path)
                c = GOES.at(direction)(c);
            return c;
        }

        template<typename ValidateFunc>
        auto children() const -> Children
        {
            Children children;
            ValidateFunc validate;
            for(auto direction = '1'; direction <= '8'; ++direction)
            {
                auto child = Node{ _path + direction, _start, _goal };
                if(validate(child))
                    children.push_back(child);
            }
            return children;
        }

    private:
        Path _path;
        Coordinate _start;
        Coordinate _goal;
    };
}//end of namespace<|endoftext|>


<commit_before>/* ptptest.cc - PLIC Test Program
 * Copyright (C) 2008 Tim Janik
 *
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * A copy of the GNU Lesser General Public License should ship along
 * with this program; if not, see http://www.gnu.org/copyleft/.
 */
#include <stdio.h>
#include <stdint.h>

/* PLIC TypePackage Parser */
#include "../PlicTypePackage.cc"

#ifndef MAX
#define MIN(a,b)        ((a) <= (b) ? (a) : (b))
#define MAX(a,b)        ((a) >= (b) ? (a) : (b))
#endif

/* --- option parsing --- */
static bool
parse_str_option (char       **argv,
                  uint        &i,
                  const char  *arg,
                  const char **strp,
                  uint         argc)
{
  uint length = strlen (arg);
  if (strncmp (argv[i], arg, length) == 0)
    {
      const char *equal = argv[i] + length;
      if (*equal == '=')              /* -x=Arg */
        *strp = equal + 1;
      else if (*equal)                /* -xArg */
        *strp = equal;
      else if (i + 1 < argc)          /* -x Arg */
        {
          argv[i++] = NULL;
          *strp = argv[i];
        }
      argv[i] = NULL;
      if (*strp)
        return true;
    }
  return false;
}

static bool
parse_bool_option (char       **argv,
                   uint        &i,
                   const char  *arg)
{
  uint length = strlen (arg);
  if (strncmp (argv[i], arg, length) == 0)
    {
      argv[i] = NULL;
      return true;
    }
  return false;
}

/* --- test program --- */
int
main (int   argc,
      char *argv[])
{
  vector<String> auxtests;
  /* parse args */
  for (uint i = 1; i < argc; i++)
    {
      const char *str = NULL;
      if (strcmp (argv[i], "--") == 0)
        {
          argv[i] = NULL;
          break;
        }
      else if (parse_bool_option (argv, i, "--help"))
        {
          printf ("Usage: %s [options] TypePackage.out\n", argv[0]);
          printf ("Options:\n");
          printf ("  --help        Print usage summary\n");
          printf ("  --aux-test=x  Find 'x' in auxillary type data\n");
          exit (0);
        }
      else if (parse_str_option (argv, i, "--aux-test", &str, argc))
        auxtests.push_back (str);
    }
  /* collapse parsed args */
  uint e = 1;
  for (uint i = 1; i < argc; i++)
    if (argv[i])
      {
        argv[e++] = argv[i];
        if (i >= e)
          argv[i] = NULL;
      }
  argc = e;
  /* validate mandatory arg */
  if (argc < 2)
    error ("Usage: %s TypePackage.out\n", argv[0]);

  /* parse input file */
  int fd = open (argv[1], 0);
  if (fd < 0)
    error ("%s: open failed: %s", argv[1], strerror (errno));
  uint8 buffer[1024 * 1024];
  int l = read (fd, buffer, sizeof (buffer));
  if (l < 0)
    error ("%s: IO error: %s", argv[1], strerror (errno));
  close (fd);
  TypeRegistry tr;
  String err = tr.register_type_package (l, buffer);
  error_if (err != "", err);

  // check for intermediate \0 in type package data
  error_if (memchr (buffer, 0, l) != NULL, "embedded \\000 in type package");

  /* print types and match auxtests */
  vector<TypeNamespace> namespaces = tr.list_namespaces();
  for (uint i = 0; i < namespaces.size(); i++)
    {
      vector<TypeInfo> types = namespaces[i].list_types ();
      for (uint j = 0; j < types.size(); j++)
        {
          printf ("%c %s::%s;\n",
                  types[j].storage,
                  namespaces[i].fullname().c_str(),
                  types[j].name().c_str());
          uint ad = types[j].n_aux_strings();
          for (uint k = 0; k < ad; k++)
            {
              uint l = 0;
              const char *s = types[j].aux_string (k, &l);
              String astring = String (s, l);
              uint c = ' ';
              for (uint q = 0; q < auxtests.size(); q++)
                if (strstr (astring.c_str(), auxtests[q].c_str()))
                  {
                    auxtests.erase (auxtests.begin() + q);
                    c = '*';
                    break;
                  }
              printf ("  %c %s\n", c, astring.c_str());
            }
        }
    }

  /* fail for unmatched auxtests */
  if (auxtests.size())
    printf ("ERROR: unmatched aux-tests:\n");
  for (uint q = 0; q < auxtests.size(); q++)
    printf ("  %s\n", auxtests[q].c_str());
  return auxtests.size() != 0;
}
// g++ -Wall -Os ptptest.cc && ./a.out plic.out
<commit_msg>ptptest.cc: print errors to stderr so they aren't captured as regular output<commit_after>/* ptptest.cc - PLIC Test Program
 * Copyright (C) 2008 Tim Janik
 *
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * A copy of the GNU Lesser General Public License should ship along
 * with this program; if not, see http://www.gnu.org/copyleft/.
 */
#include <stdio.h>
#include <stdint.h>

/* PLIC TypePackage Parser */
#include "../PlicTypePackage.cc"

#ifndef MAX
#define MIN(a,b)        ((a) <= (b) ? (a) : (b))
#define MAX(a,b)        ((a) >= (b) ? (a) : (b))
#endif

/* --- option parsing --- */
static bool
parse_str_option (char       **argv,
                  uint        &i,
                  const char  *arg,
                  const char **strp,
                  uint         argc)
{
  uint length = strlen (arg);
  if (strncmp (argv[i], arg, length) == 0)
    {
      const char *equal = argv[i] + length;
      if (*equal == '=')              /* -x=Arg */
        *strp = equal + 1;
      else if (*equal)                /* -xArg */
        *strp = equal;
      else if (i + 1 < argc)          /* -x Arg */
        {
          argv[i++] = NULL;
          *strp = argv[i];
        }
      argv[i] = NULL;
      if (*strp)
        return true;
    }
  return false;
}

static bool
parse_bool_option (char       **argv,
                   uint        &i,
                   const char  *arg)
{
  uint length = strlen (arg);
  if (strncmp (argv[i], arg, length) == 0)
    {
      argv[i] = NULL;
      return true;
    }
  return false;
}

/* --- test program --- */
int
main (int   argc,
      char *argv[])
{
  vector<String> auxtests;
  /* parse args */
  for (uint i = 1; i < argc; i++)
    {
      const char *str = NULL;
      if (strcmp (argv[i], "--") == 0)
        {
          argv[i] = NULL;
          break;
        }
      else if (parse_bool_option (argv, i, "--help"))
        {
          printf ("Usage: %s [options] TypePackage.out\n", argv[0]);
          printf ("Options:\n");
          printf ("  --help        Print usage summary\n");
          printf ("  --aux-test=x  Find 'x' in auxillary type data\n");
          exit (0);
        }
      else if (parse_str_option (argv, i, "--aux-test", &str, argc))
        auxtests.push_back (str);
    }
  /* collapse parsed args */
  uint e = 1;
  for (uint i = 1; i < argc; i++)
    if (argv[i])
      {
        argv[e++] = argv[i];
        if (i >= e)
          argv[i] = NULL;
      }
  argc = e;
  /* validate mandatory arg */
  if (argc < 2)
    error ("Usage: %s TypePackage.out\n", argv[0]);

  /* parse input file */
  int fd = open (argv[1], 0);
  if (fd < 0)
    error ("%s: open failed: %s", argv[1], strerror (errno));
  uint8 buffer[1024 * 1024];
  int l = read (fd, buffer, sizeof (buffer));
  if (l < 0)
    error ("%s: IO error: %s", argv[1], strerror (errno));
  close (fd);
  TypeRegistry tr;
  String err = tr.register_type_package (l, buffer);
  error_if (err != "", err);

  // check for intermediate \0 in type package data
  error_if (memchr (buffer, 0, l) != NULL, "embedded \\000 in type package");

  /* print types and match auxtests */
  vector<TypeNamespace> namespaces = tr.list_namespaces();
  for (uint i = 0; i < namespaces.size(); i++)
    {
      vector<TypeInfo> types = namespaces[i].list_types ();
      for (uint j = 0; j < types.size(); j++)
        {
          printf ("%c %s::%s;\n",
                  types[j].storage,
                  namespaces[i].fullname().c_str(),
                  types[j].name().c_str());
          uint ad = types[j].n_aux_strings();
          for (uint k = 0; k < ad; k++)
            {
              uint l = 0;
              const char *s = types[j].aux_string (k, &l);
              String astring = String (s, l);
              uint c = ' ';
              for (uint q = 0; q < auxtests.size(); q++)
                if (strstr (astring.c_str(), auxtests[q].c_str()))
                  {
                    auxtests.erase (auxtests.begin() + q);
                    c = '*';
                    break;
                  }
              printf ("  %c %s\n", c, astring.c_str());
            }
        }
    }

  /* fail for unmatched auxtests */
  if (auxtests.size())
    fprintf (stderr, "ERROR: unmatched aux-tests:\n");
  for (uint q = 0; q < auxtests.size(); q++)
    fprintf (stderr, "  %s\n", auxtests[q].c_str());
  return auxtests.size() != 0;
}
// g++ -Wall -Os ptptest.cc && ./a.out plic.out
<|endoftext|>


<commit_before>#include <string>

#include <ros/ros.h>
#include <geometry_msgs/Twist.h>

#include "../include/hmmwv/gpio.hpp"
#include "../include/hmmwv/engine.hpp"

using namespace ros;
using namespace std;

GPIO gpio;
						// enable	direction		speed
Engine driveLeft(&gpio, GPIO::P8_10, GPIO::P8_12, GPIO::P8_13);
Engine driveRight(&gpio, GPIO::P9_23, GPIO::P9_21, GPIO::P9_14);
//Engine rotatorLeft(..);
//Engine rotatorRight(..);

void velocityCallback(const geometry_msgs::Twist& msg) {
	//ROS_INFO("%f", msg.linear.x);

	if (msg.linear.x > .1) {
		// drive forward
		ROS_INFO("Forward");
		driveLeft.start(1, msg.linear.x);
		driveRight.start(-1, msg.linear.x);
	}
	else if (msg.linear.x < -.1) {
		ROS_INFO("Backward");
		// drive backward
		driveLeft.start(-1, msg.linear.x * -1.0); // The speed value must be in range [0, 1]
		driveRight.start(1, msg.linear.x * -1.0);
	}
	else {
		// stop
		driveLeft.start(0);
		driveRight.start(0);
	}
}

int main(int argc, char **argv) {
	driveLeft.start(0);
	driveRight.start(0);

	// init ros
	init(argc, argv, "enginecontrol");
	NodeHandle n;
	Subscriber sub = n.subscribe("turtle1/cmd_vel", 1, velocityCallback);
	ROS_INFO("enginecontrol up and running.");

	// enter ros loop and wait for callbacks
	spin();
	return 0;
}
<commit_msg>enginecontrol: don't make motors go in different directions (something else already covers that oO)<commit_after>#include <string>

#include <ros/ros.h>
#include <geometry_msgs/Twist.h>

#include "../include/hmmwv/gpio.hpp"
#include "../include/hmmwv/engine.hpp"

using namespace ros;
using namespace std;

GPIO gpio;
						// enable	direction		speed
Engine driveLeft(&gpio, GPIO::P8_10, GPIO::P8_12, GPIO::P8_13);
Engine driveRight(&gpio, GPIO::P9_23, GPIO::P9_21, GPIO::P9_14);
//Engine rotatorLeft(..);
//Engine rotatorRight(..);

void velocityCallback(const geometry_msgs::Twist& msg) {
	//ROS_INFO("%f", msg.linear.x);

	if (msg.linear.x > .1) {
		// drive forward
		ROS_INFO("Forward");
		driveLeft.start(-1, msg.linear.x);
		driveRight.start(-1, msg.linear.x);
	}
	else if (msg.linear.x < -.1) {
		// drive backward
		ROS_INFO("Backward");
		driveLeft.start(1, msg.linear.x * -1.0); // The speed value must be in range [0, 1]
		driveRight.start(1, msg.linear.x * -1.0);
	}
	else {
		// stop
		driveLeft.start(0);
		driveRight.start(0);
	}
}

int main(int argc, char **argv) {
	//driveLeft.start(0); // Why were we doing that? oO
	//driveRight.start(0);

	// init ros
	init(argc, argv, "enginecontrol");
	NodeHandle n;
	Subscriber sub = n.subscribe("turtle1/cmd_vel", 1, velocityCallback);
	ROS_INFO("enginecontrol up and running.");

	// enter ros loop and wait for callbacks
	spin();
	return 0;
}
<|endoftext|>