<commit_before>/*=========================================================================

 Program:   ORFEO Toolbox
 Language:  C++
 Date:      $Date$
 Version:   $Revision$

 Copyright (c) Centre National d'Etudes Spatiales. All rights reserved.
 See OTBCopyright.txt for details.

 This software is distributed WITHOUT ANY WARRANTY; without even
 the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
 PURPOSE.  See the above copyright notices for more information.

 =========================================================================*/
#include "otbSuperimpose.h"

#include <iostream>

#include "otbImageFileReader.h"
#include "otbStreamingImageFileWriter.h"
#include "otbImage.h"
#include "otbVectorImage.h"
#include "otbGenericRSResampleImageFilter.h"
#include "otbBCOInterpolateImageFunction.h"
#include "itkExceptionObject.h"
#include "otbStandardWriterWatcher.h"
#include "otbPipelineMemoryPrintCalculator.h"

namespace otb
{

int Superimpose::Describe(ApplicationDescriptor* descriptor)
{
  descriptor->SetName("Superimpose");
  descriptor->SetDescription("Using available image metadata, project one image onto another one");
  descriptor->AddOption("DEMDirectory","Directory were to find the DEM tiles","dem", 1, false, otb::ApplicationDescriptor::DirectoryName);
  descriptor->AddOption("NumStreamDivisions","Number of streaming divisions (optional)","stream", 1, false, otb::ApplicationDescriptor::Integer);
  descriptor->AddOption("LocMapSpacing","Generate a coarser deformation field with the given spacing.","lmSpacing", 1, false, otb::ApplicationDescriptor::Real);
  descriptor->AddOption("ReferenceInput","The reference input","inR", 1, true, otb::ApplicationDescriptor::InputImage);
  descriptor->AddOption("MovingInput","The image to reproject","inM", 1, true, otb::ApplicationDescriptor::InputImage);
  descriptor->AddOutputImage();

  return EXIT_SUCCESS;
}

int Superimpose::Execute(otb::ApplicationOptionsResult* parseResult)
{
  try
    {

    typedef unsigned short int PixelType;

    typedef otb::VectorImage<PixelType, 2>                ImageType;
    typedef otb::ImageFileReader<ImageType>               ReaderType;
    typedef otb::StreamingImageFileWriter<ImageType>      WriterType;
    typedef otb::BCOInterpolateImageFunction<ImageType>   InterpolatorType;

    typedef otb::GenericRSResampleImageFilter<ImageType, ImageType>  ResamplerType;

    // Read input images information
    ReaderType::Pointer refReader = ReaderType::New();
    refReader->SetFileName(parseResult->GetParameterString("ReferenceInput"));
    refReader->GenerateOutputInformation();

    ReaderType::Pointer movingReader = ReaderType::New();
    movingReader->SetFileName(parseResult->GetParameterString("MovingInput"));
    movingReader->GenerateOutputInformation();

    // Resample filter
    ResamplerType::Pointer    resampler = ResamplerType::New();
    InterpolatorType::Pointer interpolator = InterpolatorType::New();
    resampler->SetInterpolator(interpolator);

    // Add DEM if any
    if(parseResult->IsOptionPresent("DEMDirectory"))
      {
      resampler->SetDEMDirectory(parseResult->GetParameterString("DEMDirectory", 0));
      }

    // Set up output image informations
    ImageType::SpacingType spacing = refReader->GetOutput()->GetSpacing();
    ImageType::IndexType start = refReader->GetOutput()->GetLargestPossibleRegion().GetIndex();
    ImageType::SizeType size = refReader->GetOutput()->GetLargestPossibleRegion().GetSize();
    ImageType::PointType origin = refReader->GetOutput()->GetOrigin();

    if(parseResult->IsOptionPresent("LocMapSpacing"))
      {
      double defScalarSpacing = parseResult->GetParameterFloat("LocMapSpacing");
      std::cout<<"Generating coarse deformation field (spacing="<<defScalarSpacing<<")"<<std::endl;
      ImageType::SpacingType defSpacing;

      defSpacing[0] = defScalarSpacing;
      defSpacing[1] = defScalarSpacing;

      resampler->SetDeformationFieldSpacing(defSpacing);
      }
    else
      {
      ImageType::SpacingType defSpacing;
      defSpacing[0]=10*spacing[0];
      defSpacing[1]=10*spacing[1];
      resampler->SetDeformationFieldSpacing(defSpacing);
      }

    ImageType::PixelType defaultValue;
    itk::PixelBuilder<ImageType::PixelType>::Zero(defaultValue,
                                                  movingReader->GetOutput()->GetNumberOfComponentsPerPixel());

    resampler->SetInput(movingReader->GetOutput());
    resampler->SetOutputOrigin(origin);
    resampler->SetOutputSpacing(spacing);
    resampler->SetOutputSize(size);
    resampler->SetOutputStartIndex(start);
    resampler->SetOutputKeywordList(refReader->GetOutput()->GetImageKeywordlist());
    resampler->SetOutputProjectionRef(refReader->GetOutput()->GetProjectionRef());
    resampler->SetEdgePaddingValue(defaultValue);

    WriterType::Pointer writer = WriterType::New();
    writer->SetFileName(parseResult->GetOutputImage());
    writer->SetInput(resampler->GetOutput());
    writer->SetWriteGeomFile(true);

    otb::StandardWriterWatcher w4(writer, resampler,"Superimposition");

    otb::PipelineMemoryPrintCalculator::Pointer memoryPrintCalculator = otb::PipelineMemoryPrintCalculator::New();
    const double byteToMegabyte = 1./vcl_pow(2.0, 20);
    memoryPrintCalculator->SetDataToWrite(resampler->GetOutput());
    memoryPrintCalculator->SetAvailableMemory(256 / byteToMegabyte);

    if (parseResult->IsOptionPresent("AvailableMemory"))
      {
      long long int memory = static_cast <long long int> (parseResult->GetParameterUInt("AvailableMemory"));
      memoryPrintCalculator->SetAvailableMemory(memory / byteToMegabyte);
      }

    memoryPrintCalculator->SetBiasCorrectionFactor(1.27);
    memoryPrintCalculator->Compute();

    writer->SetTilingStreamDivisions(memoryPrintCalculator->GetOptimalNumberOfStreamDivisions());

    writer->Update();
    }
  catch ( itk::ExceptionObject & err )
    {
    std::cout << "Exception itk::ExceptionObject raised !" << std::endl;
    std::cout << err << std::endl;
    return EXIT_FAILURE;
    }
  catch ( std::bad_alloc & err )
    {
    std::cout << "Exception bad_alloc : "<<(char*)err.what()<< std::endl;
    return EXIT_FAILURE;
    }
  catch ( ... )
    {
    std::cout << "Unknown exception raised !" << std::endl;
    return EXIT_FAILURE;
    }
  return EXIT_SUCCESS;

}

}
<commit_msg>ENH: replace direct use of MemoryPrintEstimator by integrated functionnality in StreamingFileWriter<commit_after>/*=========================================================================

 Program:   ORFEO Toolbox
 Language:  C++
 Date:      $Date$
 Version:   $Revision$

 Copyright (c) Centre National d'Etudes Spatiales. All rights reserved.
 See OTBCopyright.txt for details.

 This software is distributed WITHOUT ANY WARRANTY; without even
 the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
 PURPOSE.  See the above copyright notices for more information.

 =========================================================================*/
#include "otbSuperimpose.h"

#include <iostream>

#include "otbImageFileReader.h"
#include "otbStreamingImageFileWriter.h"
#include "otbImage.h"
#include "otbVectorImage.h"
#include "otbGenericRSResampleImageFilter.h"
#include "otbBCOInterpolateImageFunction.h"
#include "itkExceptionObject.h"
#include "otbStandardWriterWatcher.h"

namespace otb
{

int Superimpose::Describe(ApplicationDescriptor* descriptor)
{
  descriptor->SetName("Superimpose");
  descriptor->SetDescription("Using available image metadata, project one image onto another one");
  descriptor->AddOption("DEMDirectory","Directory were to find the DEM tiles","dem", 1, false, otb::ApplicationDescriptor::DirectoryName);
  descriptor->AddOption("NumStreamDivisions","Number of streaming divisions (optional)","stream", 1, false, otb::ApplicationDescriptor::Integer);
  descriptor->AddOption("LocMapSpacing","Generate a coarser deformation field with the given spacing.","lmSpacing", 1, false, otb::ApplicationDescriptor::Real);
  descriptor->AddOption("ReferenceInput","The reference input","inR", 1, true, otb::ApplicationDescriptor::InputImage);
  descriptor->AddOption("MovingInput","The image to reproject","inM", 1, true, otb::ApplicationDescriptor::InputImage);
  descriptor->AddOption("AvailableMemory","Set the maximum of available memory for the pipeline execution in mega bytes (optional, 256 by default)","ram", 1, false, otb::ApplicationDescriptor::Integer);
  descriptor->AddOutputImage();

  return EXIT_SUCCESS;
}

int Superimpose::Execute(otb::ApplicationOptionsResult* parseResult)
{
  try
    {

    typedef unsigned short int PixelType;

    typedef otb::VectorImage<PixelType, 2>                ImageType;
    typedef otb::ImageFileReader<ImageType>               ReaderType;
    typedef otb::StreamingImageFileWriter<ImageType>      WriterType;
    typedef otb::BCOInterpolateImageFunction<ImageType>   InterpolatorType;

    typedef otb::GenericRSResampleImageFilter<ImageType, ImageType>  ResamplerType;

    // Read input images information
    ReaderType::Pointer refReader = ReaderType::New();
    refReader->SetFileName(parseResult->GetParameterString("ReferenceInput"));
    refReader->GenerateOutputInformation();

    ReaderType::Pointer movingReader = ReaderType::New();
    movingReader->SetFileName(parseResult->GetParameterString("MovingInput"));
    movingReader->GenerateOutputInformation();

    // Resample filter
    ResamplerType::Pointer    resampler = ResamplerType::New();
    InterpolatorType::Pointer interpolator = InterpolatorType::New();
    resampler->SetInterpolator(interpolator);

    // Add DEM if any
    if(parseResult->IsOptionPresent("DEMDirectory"))
      {
      resampler->SetDEMDirectory(parseResult->GetParameterString("DEMDirectory", 0));
      }

    // Set up output image informations
    ImageType::SpacingType spacing = refReader->GetOutput()->GetSpacing();
    ImageType::IndexType start = refReader->GetOutput()->GetLargestPossibleRegion().GetIndex();
    ImageType::SizeType size = refReader->GetOutput()->GetLargestPossibleRegion().GetSize();
    ImageType::PointType origin = refReader->GetOutput()->GetOrigin();

    if(parseResult->IsOptionPresent("LocMapSpacing"))
      {
      double defScalarSpacing = parseResult->GetParameterFloat("LocMapSpacing");
      std::cout<<"Generating coarse deformation field (spacing="<<defScalarSpacing<<")"<<std::endl;
      ImageType::SpacingType defSpacing;

      defSpacing[0] = defScalarSpacing;
      defSpacing[1] = defScalarSpacing;

      resampler->SetDeformationFieldSpacing(defSpacing);
      }
    else
      {
      ImageType::SpacingType defSpacing;
      defSpacing[0]=10*spacing[0];
      defSpacing[1]=10*spacing[1];
      resampler->SetDeformationFieldSpacing(defSpacing);
      }

    ImageType::PixelType defaultValue;
    itk::PixelBuilder<ImageType::PixelType>::Zero(defaultValue,
                                                  movingReader->GetOutput()->GetNumberOfComponentsPerPixel());

    resampler->SetInput(movingReader->GetOutput());
    resampler->SetOutputOrigin(origin);
    resampler->SetOutputSpacing(spacing);
    resampler->SetOutputSize(size);
    resampler->SetOutputStartIndex(start);
    resampler->SetOutputKeywordList(refReader->GetOutput()->GetImageKeywordlist());
    resampler->SetOutputProjectionRef(refReader->GetOutput()->GetProjectionRef());
    resampler->SetEdgePaddingValue(defaultValue);

    WriterType::Pointer writer = WriterType::New();
    writer->SetFileName(parseResult->GetOutputImage());
    writer->SetInput(resampler->GetOutput());
    writer->SetWriteGeomFile(true);

    unsigned int ram = 256;
    if (parseResult->IsOptionPresent("AvailableMemory"))
      {
      ram = parseResult->GetParameterUInt("AvailableMemory");
      }
    writer->SetAutomaticTiledStreaming(ram);

    otb::StandardWriterWatcher w4(writer, resampler,"Superimposition");
    writer->Update();
    }
  catch ( itk::ExceptionObject & err )
    {
    std::cout << "Exception itk::ExceptionObject raised !" << std::endl;
    std::cout << err << std::endl;
    return EXIT_FAILURE;
    }
  catch ( std::bad_alloc & err )
    {
    std::cout << "Exception bad_alloc : "<<(char*)err.what()<< std::endl;
    return EXIT_FAILURE;
    }
  catch ( ... )
    {
    std::cout << "Unknown exception raised !" << std::endl;
    return EXIT_FAILURE;
    }
  return EXIT_SUCCESS;

}

}
<|endoftext|>


<commit_before>/*
 * GAMS - General Algebraic Modeling System C++ API
 *
 * Copyright (c) 2017-2021 GAMS Software GmbH <support@gams.com>
 * Copyright (c) 2017-2021 GAMS Development Corp. <support@gams.com>
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in all
 * copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
 */

#ifdef _WIN32
#include <windows.h>
#include <direct.h>
#include <wchar.h>
#pragma comment(lib, "advapi32")
#endif

#include "gamsplatform.h"
#include <string>
#include <stdlib.h>
#include <iostream>
#include <sstream>
#include <array>
#include <thread>

#include "gamspath.h"
#include "gamsenum.h"
#include "gamslog.h"
#include "gamsexception.h"

namespace gams {

using namespace std;

#ifdef __linux__ // Linux
const char cEnvSep = ':';
const char *cPathSep = "/";
const char *cCmpFileName = "gmscmpun.txt";
const int cExitCodeDiv = 256;
const char *cExeSuffix = "";
const char *cLibPrefix = "lib";
const char *cLibSuffix = ".so";
const char *cLibEnv = "LD_LIBRARY_PATH";
#elif __APPLE__ // Apple iOS
const char cEnvSep = ':';
const char *cPathSep = "/";
const char *cCmpFileName = "gmscmpun.txt";
const int cExitCodeDiv = 256;
const char *cExeSuffix = "";
const char *cLibPrefix = "lib";
const char *cLibSuffix = ".dylib";
const char *cLibEnv = "DYLD_LIBRARY_PATH";
#elif __unix__ // other *nix
const char cEnvSep = ':';
const char *cPathSep = "/";
const char *cCmpFileName = "gmscmpun.txt";
const int cExitCodeDiv = 256;
const char *cExeSuffix = "";
const char *cLibPrefix = "lib";
const char *cLibSuffix = ".so";
const char *cLibEnv = "LD_LIBRARY_PATH";
#else // Windows
const char cEnvSep = ';';
const char *cLibEnv = "";
const char *cPathSep = "\\";
const char *cCmpFileName = "gmscmpnt.txt";
const int cExitCodeDiv = 1;
const char *cExeSuffix = ".exe";
const char *cLibPrefix = "";
const char *cLibSuffix = ".dll";
#endif

string GAMSPlatform::findGams(LogId logId)
{
#ifdef _WIN32
    return findGamsOnWindows(logId);
#elif __APPLE__
    return findGamsOnApple(logId);
#else
    return findGamsOnUnix(logId);
#endif
}

void GAMSPlatform::ensureEnvPathContains(const char *dirName)
{
#ifdef _WIN32
    ensureEnvPathSetOnWindows(dirName);
#elif __APPLE__
    ensureEnvPathSetOnApple(dirName);
#else
    ensureEnvPathSetOnUnix(dirName);
#endif
}

bool GAMSPlatform::interrupt(long pid)
{
#ifdef _WIN32
    return interruptOnWindows(pid);
#else
    return interruptOnNonWindows(pid);
#endif
}

string GAMSPlatform::findGamsOnApple(LogId logId)
{
    string path = findGamsOnUnix(logId);
    if (!path.empty())
        return path;
    return "/Library/Frameworks/GAMS.framework/Versions/Current/Resources";
}

string GAMSPlatform::findGamsOnUnix(LogId logId)
{
    string gamsDir;
    string gamsDirLD;

    string s;
    stringstream ss(getenv("PATH"));
    while (getline(ss, s, cEnvSep)) {
        GAMSPath g(s + "/gams");
        if (g.exists() && filesystem::is_regular_file(g)) {
            gamsDir = s;
            break;
        }
    }
    if (!gamsDir.empty() && LoggerPool::instance().debug(logId) == GAMSEnum::DebugLevel::Off)
        return gamsDir;

    s.clear();
    ss.str(getenv(cLibEnv));
    while (getline(ss, s, cEnvSep)) {
        GAMSPath g(s + "/gams");
        if (g.exists() && filesystem::is_regular_file(g)) {
            gamsDirLD = s;
            break;
        }
    }
    if (gamsDir.empty())
        return gamsDirLD;
    else if (!gamsDirLD.empty() && gamsDir != gamsDirLD) {
        DEB_S(logId) << "--- Warning: Found GAMS system directory " << gamsDir << " in PATH and a different one" << endl
                     << "---          in (DY)LD_LIBRARY_PATH (" << gamsDirLD << "). The latter is ignored.";
    }
    return gamsDir;
}

void GAMSPlatform::ensureEnvPathSetOnUnix(const char *dirName)
{
    // TODO?
}

void GAMSPlatform::ensureEnvPathSetOnApple(const char *dirName)
{
    // TODO?
}

bool GAMSPlatform::interruptOnNonWindows(long pid)
{
    string result;
    runProcess("", "/bin/bash", "-c -kill -2 " + to_string(pid), result);
    return true;
}

string GAMSPlatform::findGamsOnWindows(LogId logId)
{
#ifdef _WIN32
#ifdef NO_WINDOWS_REGISTRY
    string s;
    stringstream ss(getenv("PATH"));
    while (getline(ss, s, cEnvSep)) {
        if (GAMSPath(s + "/gams.exe").exists()) {
            return s;
        }
    }
    return "";
#else
    const DWORD SIZE = 1024;
    string firstFound;

    vector<HKEY> locations = {HKEY_CURRENT_USER, HKEY_LOCAL_MACHINE};
    for (HKEY hkey : locations) {

        // TODO(RG): these should be wchars when we decided how to handle paths with gams
        char inputVal[SIZE];
        DWORD bufferSize = SIZE;
        long retCode;

        retCode = RegOpenKeyA(hkey, "Software\\Classes", &hkey);
        if (retCode != ERROR_SUCCESS) continue;

        retCode = RegGetValueA(hkey, "gams.location", 0, RRF_RT_REG_SZ, nullptr, (LPBYTE) inputVal, &bufferSize);
        RegCloseKey(hkey);
        if (retCode != ERROR_SUCCESS) continue;

        // second run, already found something
        if (!firstFound.empty()) {
            DEB_S(logId) << "--- Warning: Found GAMS system directory " << firstFound.c_str()
                         << "at HKEY_CURRENT_USER and a different one\n ---          in "
                         << "HKEY_LOCAL_MACHINE (" << inputVal << "). The latter is ignored.";
        } else {
            firstFound = inputVal;
        }
    }
    return firstFound;
#endif
#else
    throw GAMSException("interruptOnWindows only impemented on Windows");
#endif
}

void GAMSPlatform::ensureEnvPathSetOnWindows(const char *dirName)
{
#ifdef _WIN32
    string g = findGams();
    if (!g.empty()) {
        ostringstream ps;
        ps << "PATH=" << getenv("PATH") << ";" << dirName;
        const char* p = ps.str().c_str();

        _putenv(p);
    }
#else
    throw GAMSException("ensureEnvPathSetOnWindows only impemented on Windows");
#endif
}

bool GAMSPlatform::interruptOnWindows(long pid)
{
#ifdef _WIN32
    COPYDATASTRUCT cds;

    string stem = "___GAMSMSGWINDOW___";
    string pidStr = std::to_string(pid);
    string windowName = stem + pidStr;

    HWND receiver = FindWindow(nullptr, windowName.c_str());
    if (!receiver)
        return false;

    char lpData[] = "GAMS Message Interrupt";
    cds.dwData = 1;
    cds.lpData = lpData;
    cds.cbData = sizeof(lpData);

    SendMessageA(receiver, WM_COPYDATA, 0, (LPARAM)(LPVOID)&cds);

    return true;
#else
    throw GAMSException("interruptOnWindows only impemented on Windows");
#endif
}

int GAMSPlatform::runProcess(const string where, const string what, const string args, string& output)
{
    ostringstream ssp;
    string result;
    FILE* out;

#ifdef _WIN32
    filesystem::path p = filesystem::current_path();

    ssp << "\"" << what << "\"" << " " << args ;
    _chdir(where.c_str()); // for some reason we need to do this on windows
    out = _popen(ssp.str().c_str(), "r");

    _chdir(p.string().c_str()); // change back to old working dir
#else
    ssp << "cd " << where << " && " << what << " " << args;
    out = popen(ssp.str().c_str(), "r");
#endif
    if (!out) {
        std::cerr << "Couldn't start command: " << ssp.str() << std::endl;
        return -1;
    }
    std::array<char, 128> buffer;
    while (fgets(buffer.data(), 128, out))
        result += buffer.data();

    output = result;

    int exitCode;
#ifdef _WIN32
    exitCode = _pclose(out);
#else
    exitCode = pclose(out);
#endif

    return exitCode;
}

thread GAMSPlatform::runProcessParallel(const string executable, const string args) {
    string call = executable;
    if (!args.empty()) call += " " + args;

    thread t(system, call.c_str());
    t.detach();
    return t;
}

} // namespace gams
<commit_msg>escape paths for run process<commit_after>/*
 * GAMS - General Algebraic Modeling System C++ API
 *
 * Copyright (c) 2017-2021 GAMS Software GmbH <support@gams.com>
 * Copyright (c) 2017-2021 GAMS Development Corp. <support@gams.com>
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in all
 * copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
 */

#ifdef _WIN32
#include <windows.h>
#include <direct.h>
#include <wchar.h>
#pragma comment(lib, "advapi32")
#endif

#include "gamsplatform.h"
#include <string>
#include <stdlib.h>
#include <iostream>
#include <sstream>
#include <array>
#include <thread>

#include "gamspath.h"
#include "gamsenum.h"
#include "gamslog.h"
#include "gamsexception.h"

namespace gams {

using namespace std;

#ifdef __linux__ // Linux
const char cEnvSep = ':';
const char *cPathSep = "/";
const char *cCmpFileName = "gmscmpun.txt";
const int cExitCodeDiv = 256;
const char *cExeSuffix = "";
const char *cLibPrefix = "lib";
const char *cLibSuffix = ".so";
const char *cLibEnv = "LD_LIBRARY_PATH";
#elif __APPLE__ // Apple iOS
const char cEnvSep = ':';
const char *cPathSep = "/";
const char *cCmpFileName = "gmscmpun.txt";
const int cExitCodeDiv = 256;
const char *cExeSuffix = "";
const char *cLibPrefix = "lib";
const char *cLibSuffix = ".dylib";
const char *cLibEnv = "DYLD_LIBRARY_PATH";
#elif __unix__ // other *nix
const char cEnvSep = ':';
const char *cPathSep = "/";
const char *cCmpFileName = "gmscmpun.txt";
const int cExitCodeDiv = 256;
const char *cExeSuffix = "";
const char *cLibPrefix = "lib";
const char *cLibSuffix = ".so";
const char *cLibEnv = "LD_LIBRARY_PATH";
#else // Windows
const char cEnvSep = ';';
const char *cLibEnv = "";
const char *cPathSep = "\\";
const char *cCmpFileName = "gmscmpnt.txt";
const int cExitCodeDiv = 1;
const char *cExeSuffix = ".exe";
const char *cLibPrefix = "";
const char *cLibSuffix = ".dll";
#endif

string GAMSPlatform::findGams(LogId logId)
{
#ifdef _WIN32
    return findGamsOnWindows(logId);
#elif __APPLE__
    return findGamsOnApple(logId);
#else
    return findGamsOnUnix(logId);
#endif
}

void GAMSPlatform::ensureEnvPathContains(const char *dirName)
{
#ifdef _WIN32
    ensureEnvPathSetOnWindows(dirName);
#elif __APPLE__
    ensureEnvPathSetOnApple(dirName);
#else
    ensureEnvPathSetOnUnix(dirName);
#endif
}

bool GAMSPlatform::interrupt(long pid)
{
#ifdef _WIN32
    return interruptOnWindows(pid);
#else
    return interruptOnNonWindows(pid);
#endif
}

string GAMSPlatform::findGamsOnApple(LogId logId)
{
    string path = findGamsOnUnix(logId);
    if (!path.empty())
        return path;
    return "/Library/Frameworks/GAMS.framework/Versions/Current/Resources";
}

string GAMSPlatform::findGamsOnUnix(LogId logId)
{
    string gamsDir;
    string gamsDirLD;

    string s;
    stringstream ss(getenv("PATH"));
    while (getline(ss, s, cEnvSep)) {
        GAMSPath g(s + "/gams");
        if (g.exists() && filesystem::is_regular_file(g)) {
            gamsDir = s;
            break;
        }
    }
    if (!gamsDir.empty() && LoggerPool::instance().debug(logId) == GAMSEnum::DebugLevel::Off)
        return gamsDir;

    s.clear();
    ss.str(getenv(cLibEnv));
    while (getline(ss, s, cEnvSep)) {
        GAMSPath g(s + "/gams");
        if (g.exists() && filesystem::is_regular_file(g)) {
            gamsDirLD = s;
            break;
        }
    }
    if (gamsDir.empty())
        return gamsDirLD;
    else if (!gamsDirLD.empty() && gamsDir != gamsDirLD) {
        DEB_S(logId) << "--- Warning: Found GAMS system directory " << gamsDir << " in PATH and a different one" << endl
                     << "---          in (DY)LD_LIBRARY_PATH (" << gamsDirLD << "). The latter is ignored.";
    }
    return gamsDir;
}

void GAMSPlatform::ensureEnvPathSetOnUnix(const char *dirName)
{
    // TODO?
}

void GAMSPlatform::ensureEnvPathSetOnApple(const char *dirName)
{
    // TODO?
}

bool GAMSPlatform::interruptOnNonWindows(long pid)
{
    string result;
    runProcess("", "/bin/bash", "-c -kill -2 " + to_string(pid), result);
    return true;
}

string GAMSPlatform::findGamsOnWindows(LogId logId)
{
#ifdef _WIN32
#ifdef NO_WINDOWS_REGISTRY
    string s;
    stringstream ss(getenv("PATH"));
    while (getline(ss, s, cEnvSep)) {
        if (GAMSPath(s + "/gams.exe").exists()) {
            return s;
        }
    }
    return "";
#else
    const DWORD SIZE = 1024;
    string firstFound;

    vector<HKEY> locations = {HKEY_CURRENT_USER, HKEY_LOCAL_MACHINE};
    for (HKEY hkey : locations) {

        // TODO(RG): these should be wchars when we decided how to handle paths with gams
        char inputVal[SIZE];
        DWORD bufferSize = SIZE;
        long retCode;

        retCode = RegOpenKeyA(hkey, "Software\\Classes", &hkey);
        if (retCode != ERROR_SUCCESS) continue;

        retCode = RegGetValueA(hkey, "gams.location", 0, RRF_RT_REG_SZ, nullptr, (LPBYTE) inputVal, &bufferSize);
        RegCloseKey(hkey);
        if (retCode != ERROR_SUCCESS) continue;

        // second run, already found something
        if (!firstFound.empty()) {
            DEB_S(logId) << "--- Warning: Found GAMS system directory " << firstFound.c_str()
                         << "at HKEY_CURRENT_USER and a different one\n ---          in "
                         << "HKEY_LOCAL_MACHINE (" << inputVal << "). The latter is ignored.";
        } else {
            firstFound = inputVal;
        }
    }
    return firstFound;
#endif
#else
    throw GAMSException("interruptOnWindows only impemented on Windows");
#endif
}

void GAMSPlatform::ensureEnvPathSetOnWindows(const char *dirName)
{
#ifdef _WIN32
    string g = findGams();
    if (!g.empty()) {
        ostringstream ps;
        ps << "PATH=" << getenv("PATH") << ";" << dirName;
        const char* p = ps.str().c_str();

        _putenv(p);
    }
#else
    throw GAMSException("ensureEnvPathSetOnWindows only impemented on Windows");
#endif
}

bool GAMSPlatform::interruptOnWindows(long pid)
{
#ifdef _WIN32
    COPYDATASTRUCT cds;

    string stem = "___GAMSMSGWINDOW___";
    string pidStr = std::to_string(pid);
    string windowName = stem + pidStr;

    HWND receiver = FindWindow(nullptr, windowName.c_str());
    if (!receiver)
        return false;

    char lpData[] = "GAMS Message Interrupt";
    cds.dwData = 1;
    cds.lpData = lpData;
    cds.cbData = sizeof(lpData);

    SendMessageA(receiver, WM_COPYDATA, 0, (LPARAM)(LPVOID)&cds);

    return true;
#else
    throw GAMSException("interruptOnWindows only impemented on Windows");
#endif
}

int GAMSPlatform::runProcess(const string where, const string what, const string args, string& output)
{
    ostringstream ssp;
    string result;
    FILE* out;

#ifdef _WIN32
    filesystem::path p = filesystem::current_path();

    ssp << "\"" << what << "\"" << " " << args ;
    _chdir(where.c_str()); // for some reason we need to do this on windows
    out = _popen(ssp.str().c_str(), "r");

    _chdir(p.string().c_str()); // change back to old working dir
#else
    ssp << "cd \"" << where << "\" && \"" << what << "\" " << args;
    out = popen(ssp.str().c_str(), "r");
#endif
    if (!out) {
        std::cerr << "Couldn't start command: " << ssp.str() << std::endl;
        return -1;
    }
    std::array<char, 128> buffer;
    while (fgets(buffer.data(), 128, out))
        result += buffer.data();

    output = result;

    int exitCode;
#ifdef _WIN32
    exitCode = _pclose(out);
#else
    exitCode = pclose(out);
#endif

    return exitCode;
}

thread GAMSPlatform::runProcessParallel(const string executable, const string args) {
    string call = executable;
    if (!args.empty()) call += " " + args;

    thread t(system, call.c_str());
    t.detach();
    return t;
}

} // namespace gams
<|endoftext|>


<commit_before>// Fundamentals
#include <iostream>

// Windows headers
#include <Windows.h>

// Kinect Api
#include "NuiApi.h"

#include "Kinect.h"

ozansKinect::Kinect::Kinect()
	:pNuiSensor(NULL),
	kinectWorkingStatus(true),
	coordinateX(0), coordinateY(0)
{
}

ozansKinect::Kinect::~Kinect()
{
	pNuiSensor->NuiShutdown();
	//pNuiSensor = nullptr; // neden olmuyor ?
}

HRESULT ozansKinect::Kinect::Initialize()
{
	INuiSensor* tempNuiSensor;

	int iSensorCount = 0;
	HRESULT hr = NuiGetSensorCount(&iSensorCount);
	if (FAILED(hr))
	{
		return hr;
	}

	// Look at each Kinect sensor
	for (int i = 0; i < iSensorCount; i++)
	{
		// Create the sensor so we can check status,
		// if we can't create it, move on
		hr = NuiCreateSensorByIndex(i, &tempNuiSensor);
		if (FAILED(hr))
		{
			return hr;
		}

		// Get the status of the sensor, and if connected
		// then we can initialize it
		hr = tempNuiSensor->NuiStatus();
		if (S_OK == hr)
		{
			pNuiSensor = tempNuiSensor;
			break;
		}

		// This sensor wasn't OK,
		// so release it since we're not using it
		tempNuiSensor->Release();
	}

	if (pNuiSensor != NULL)
	{
		hr = pNuiSensor->NuiInitialize(NUI_INITIALIZE_FLAG_USES_SKELETON);
		if (SUCCEEDED(hr))
		{
			return hr;
		}
	}

	// Always success for create kinect
	return hr;
}

void ozansKinect::Kinect::ProcessSkeleton()
{
	// Create skeleton frame
	NUI_SKELETON_FRAME skeletonFrame = { 0 };

	HRESULT hr = pNuiSensor->NuiSkeletonGetNextFrame(LATECY, &skeletonFrame);
	if (FAILED(hr))
	{
		return;
	}

	// Smooth skeleton data
	//pNuiSensor->NuiTransformSmooth(&skeletonFrame, NULL);

	for (int i = 0; i < NUI_SKELETON_COUNT; i++)
	{
		NUI_SKELETON_TRACKING_STATE trackingState = skeletonFrame.SkeletonData[i].eTrackingState;

		if (NUI_SKELETON_TRACKED == trackingState)
		{
			// We're traking the skeleton, write coordinate
			setCoordinate2Sens(skeletonFrame.SkeletonData[i].SkeletonPositions[NUI_SKELETON_POSITION_HAND_RIGHT].x, skeletonFrame.SkeletonData[i].SkeletonPositions[NUI_SKELETON_POSITION_HAND_RIGHT].y);
			std::cout << getCoordinateX() << std::endl << getCoordinateY() << std::endl;
			if (getCoordinateY() == 0 && getCoordinateX() == 0)
			{
				setKinectExit(false);
			}
			// setCoordinate2Sens() BURADAN DEVAM *********************
		}
	}

	return;
}

void ozansKinect::Kinect::setKinectExit(const bool x)
{
	kinectWorkingStatus = x;
}

bool ozansKinect::Kinect::getKinectExit() const
{
	return kinectWorkingStatus;
}

void ozansKinect::Kinect::setCoordinate2Sens(const double x, const double y)
{
	coordinateX = x * 100;
	coordinateY = y * 100;
}

void ozansKinect::Kinect::setCoordinate3Sens(const double x, const double y)
{
	coordinateX = x * 1000;
	coordinateY = y * 1000;

}

int ozansKinect::Kinect::getCoordinateX() const
{
	return coordinateX;
}

int ozansKinect::Kinect::getCoordinateY() const
{
	return coordinateY;
}
<commit_msg>deneme branch için<commit_after>// Fundamentals
#include <iostream>

// Windows headers
#include <Windows.h>

// Kinect Api
#include "NuiApi.h"

#include "Kinect.h"

ozansKinect::Kinect::Kinect()
	:pNuiSensor(NULL),
	kinectWorkingStatus(true),
	coordinateX(0), coordinateY(0)
{
}

ozansKinect::Kinect::~Kinect()
{
	pNuiSensor->NuiShutdown();
	//pNuiSensor = nullptr; // neden olmuyor ? df
}

HRESULT ozansKinect::Kinect::Initialize()
{
	INuiSensor* tempNuiSensor;

	int iSensorCount = 0;
	HRESULT hr = NuiGetSensorCount(&iSensorCount);
	if (FAILED(hr))
	{
		return hr;
	}

	// Look at each Kinect sensor
	for (int i = 0; i < iSensorCount; i++)
	{
		// Create the sensor so we can check status,
		// if we can't create it, move on
		hr = NuiCreateSensorByIndex(i, &tempNuiSensor);
		if (FAILED(hr))
		{
			return hr;
		}

		// Get the status of the sensor, and if connected
		// then we can initialize it
		hr = tempNuiSensor->NuiStatus();
		if (S_OK == hr)
		{
			pNuiSensor = tempNuiSensor;
			break;
		}

		// This sensor wasn't OK,
		// so release it since we're not using it
		tempNuiSensor->Release();
	}

	if (pNuiSensor != NULL)
	{
		hr = pNuiSensor->NuiInitialize(NUI_INITIALIZE_FLAG_USES_SKELETON);
		if (SUCCEEDED(hr))
		{
			return hr;
		}
	}

	// Always success for create kinect
	return hr;
}

void ozansKinect::Kinect::ProcessSkeleton()
{
	// Create skeleton frame
	NUI_SKELETON_FRAME skeletonFrame = { 0 };

	HRESULT hr = pNuiSensor->NuiSkeletonGetNextFrame(LATECY, &skeletonFrame);
	if (FAILED(hr))
	{
		return;
	}

	// Smooth skeleton data
	//pNuiSensor->NuiTransformSmooth(&skeletonFrame, NULL);

	for (int i = 0; i < NUI_SKELETON_COUNT; i++)
	{
		NUI_SKELETON_TRACKING_STATE trackingState = skeletonFrame.SkeletonData[i].eTrackingState;

		if (NUI_SKELETON_TRACKED == trackingState)
		{
			// We're traking the skeleton, write coordinate
			setCoordinate2Sens(skeletonFrame.SkeletonData[i].SkeletonPositions[NUI_SKELETON_POSITION_HAND_RIGHT].x, skeletonFrame.SkeletonData[i].SkeletonPositions[NUI_SKELETON_POSITION_HAND_RIGHT].y);
			std::cout << getCoordinateX() << std::endl << getCoordinateY() << std::endl;
			if (getCoordinateY() == 0 && getCoordinateX() == 0)
			{
				setKinectExit(false);
			}
			// setCoordinate2Sens() BURADAN DEVAM *********************
		}
	}

	return;
}

void ozansKinect::Kinect::setKinectExit(const bool x)
{
	kinectWorkingStatus = x;
}

bool ozansKinect::Kinect::getKinectExit() const
{
	return kinectWorkingStatus;
}

void ozansKinect::Kinect::setCoordinate2Sens(const double x, const double y)
{
	coordinateX = x * 100;
	coordinateY = y * 100;
}

void ozansKinect::Kinect::setCoordinate3Sens(const double x, const double y)
{
	coordinateX = x * 1000;
	coordinateY = y * 1000;

}

int ozansKinect::Kinect::getCoordinateX() const
{
	return coordinateX;
}

int ozansKinect::Kinect::getCoordinateY() const
{
	return coordinateY;
}
<|endoftext|>


<commit_before>// $Id: face_tri6.C,v 1.29 2007-02-06 23:54:22 roystgnr Exp $

// The libMesh Finite Element Library.
// Copyright (C) 2002-2005  Benjamin S. Kirk, John W. Peterson

// This library 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 library 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.

// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA

// C++ includes

// Local includes
#include "side.h"
#include "edge_edge3.h"
#include "face_tri6.h"

// ------------------------------------------------------------
// Tri6 class static member initializations
const unsigned int Tri6::side_nodes_map[3][3] =
{
  {0, 1, 3}, // Side 0
  {1, 2, 4}, // Side 1
  {2, 0, 5}  // Side 2
};

#ifdef ENABLE_AMR

const float Tri6::_embedding_matrix[4][6][6] =
{
  // embedding matrix for child 0
  {
    //  0      1      2    3    4    5
    { 1.0,   0.0,   0.0, 0.0, 0.0, 0.0}, // 0
    { 0.0,   0.0,   0.0, 1.0, 0.0, 0.0}, // 1
    { 0.0,   0.0,   0.0, 0.0, 0.0, 1.0}, // 2
    {.375, -.125,   0.0, .75, 0.0, 0.0}, // 3
    { 0.0, -.125, -.125, 0.5, .25, 0.5}, // 4
    {.375,   0.0, -.125, 0.0, 0.0, .75}  // 5
  },

  // embedding matrix for child 1
  {
    //  0      1      2    3    4    5
    {  0.0,  0.0,   0.0, 1.0, 0.0, 0.0}, // 0
    {  0.0,  1.0,   0.0, 0.0, 0.0, 0.0}, // 1
    {  0.0,  0.0,   0.0, 0.0, 1.0, 0.0}, // 2
    {-.125, .375,   0.0, .75, 0.0, 0.0}, // 3
    {  0.0, .375, -.125, 0.0, .75, 0.0}, // 4
    {-.125,  0.0, -.125, 0.5, 0.5, .25}  // 5
  },

  // embedding matrix for child 2
  {
    //  0       1     2    3    4    5
    {  0.0,   0.0,  0.0, 0.0, 0.0, 1.0}, // 0
    {  0.0,   0.0,  0.0, 0.0, 1.0, 0.0}, // 1
    {  0.0,   0.0,  1.0, 0.0, 0.0, 0.0}, // 2
    {-.125, -.125,  0.0, .25, 0.5, 0.5}, // 3
    {  0.0, -.125, .375, 0.0, .75, 0.0}, // 4
    {-.125,   0.0, .375, 0.0, 0.0, .75}  // 5
  },

  // embedding matrix for child 3
  {
    //  0       1      2    3    4    5
    {  0.0,   0.0,   0.0, 1.0, 0.0, 0.0}, // 0
    {  0.0,   0.0,   0.0, 0.0, 1.0, 0.0}, // 1
    {  0.0,   0.0,   0.0, 0.0, 0.0, 1.0}, // 2
    {-.125,   0.0, -.125, 0.5, 0.5, .25}, // 3
    {-.125, -.125,   0.0, .25, 0.5, 0.5}, // 4
    {  0.0, -.125, -.125, 0.5, .25, 0.5}  // 5
  }
};

#endif

// ------------------------------------------------------------
// Tri6 class member functions

bool Tri6::is_vertex(const unsigned int i) const
{
  if (i < 3)
    return true;
  return false;
}

bool Tri6::is_edge(const unsigned int i) const
{
  if (i < 3)
    return false;
  return true;
}

bool Tri6::is_face(const unsigned int) const
{
  return false;
}

bool Tri6::is_node_on_side(const unsigned int n,
			   const unsigned int s) const
{
  assert(s < n_sides());
  for (unsigned int i = 0; i != 3; ++i)
    if (side_nodes_map[s][i] == n)
      return true;
  return false;
}

bool Tri6::has_affine_map() const
{
  // Make sure edges are straight
  if (!this->point(3).relative_fuzzy_equals
      ((this->point(0) + this->point(1))/2.))
    return false;
  if (!this->point(4).relative_fuzzy_equals
      ((this->point(1) + this->point(2))/2.))
    return false;
  if (!this->point(5).relative_fuzzy_equals
      ((this->point(2) + this->point(0))/2.))
    return false;

  return false;
}

unsigned int Tri6::key (const unsigned int s) const
{
  assert (s < this->n_sides());

  switch (s)
    {
    case 0:

      return
	this->compute_key (this->node(3));

    case 1:

      return
	this->compute_key (this->node(4));

    case 2:

      return
	this->compute_key (this->node(5));
    }

  // We will never get here...  Look at the code above.
  error();
  return 0;
}

AutoPtr<Elem> Tri6::build_side (const unsigned int i) const
{
  assert (i < this->n_sides());

  AutoPtr<Elem> ap(new Side<Edge3,Tri6>(this,i));
  return ap;

//   Edge3* edge = new Edge3;

//   switch (i)
//     {
//     case 0:
//       {
// 	edge->set_node(0) = this->get_node(0);
// 	edge->set_node(1) = this->get_node(1);
// 	edge->set_node(2) = this->get_node(3);

// 	AutoPtr<Elem> ap(edge);  return ap;
//       }
//     case 1:
//       {
// 	edge->set_node(0) = this->get_node(1);
// 	edge->set_node(1) = this->get_node(2);
// 	edge->set_node(2) = this->get_node(4);

// 	AutoPtr<Elem> ap(edge);  return ap;
//       }
//     case 2:
//       {
// 	edge->set_node(0) = this->get_node(2);
// 	edge->set_node(1) = this->get_node(0);
// 	edge->set_node(2) = this->get_node(5);

// 	AutoPtr<Elem> ap(edge);  return ap;
//       }
//     default:
//       {
// 	error();
//       }
//     }

//   // We will never get here...  Look at the code above.
//   error();
//   AutoPtr<Elem> ap(NULL);  return ap;
}

void Tri6::connectivity(const unsigned int sf,
			const IOPackage iop,
			std::vector<unsigned int>& conn) const
{
  assert (sf < this->n_sub_elem());
  assert (iop != INVALID_IO_PACKAGE);

  switch (iop)
    {
    case TECPLOT:
      {
	conn.resize(4);
	switch(sf)
	  {
	  case 0:
	    // linear sub-triangle 0
	    conn[0] = this->node(0)+1;
	    conn[1] = this->node(3)+1;
	    conn[2] = this->node(5)+1;
	    conn[3] = this->node(5)+1;

	    return;

	  case 1:
	    // linear sub-triangle 1
	    conn[0] = this->node(3)+1;
	    conn[1] = this->node(1)+1;
	    conn[2] = this->node(4)+1;
	    conn[3] = this->node(4)+1;

	    return;

	  case 2:
	    // linear sub-triangle 2
	    conn[0] = this->node(5)+1;
	    conn[1] = this->node(4)+1;
	    conn[2] = this->node(2)+1;
	    conn[3] = this->node(2)+1;

	    return;

	  case 3:
	    // linear sub-triangle 3
	    conn[0] = this->node(3)+1;
	    conn[1] = this->node(4)+1;
	    conn[2] = this->node(5)+1;
	    conn[3] = this->node(5)+1;

	    return;

	  default:
	    error();
	  }
      }

    case VTK:
      {
	conn.resize(3);
	switch(sf)
	  {
	  case 0:
	    // linear sub-triangle 0
	    conn[0] = this->node(0);
	    conn[1] = this->node(3);
	    conn[2] = this->node(5);

	    return;

	  case 1:
	    // linear sub-triangle 1
	    conn[0] = this->node(3);
	    conn[1] = this->node(1);
	    conn[2] = this->node(4);

	    return;

	  case 2:
	    // linear sub-triangle 2
	    conn[0] = this->node(5);
	    conn[1] = this->node(4);
	    conn[2] = this->node(2);

	    return;

	  case 3:
	    // linear sub-triangle 3
	    conn[0] = this->node(3);
	    conn[1] = this->node(4);
	    conn[2] = this->node(5);

	    return;

	  default:
	    error();
	  }
      }

    default:
      error();
    }

  error();
}

unsigned short int Tri6::second_order_adjacent_vertex (const unsigned int n,
						       const unsigned int v) const
{
  assert (n >= this->n_vertices());
  assert (n <  this->n_nodes());
  assert (v < 2);
  return _second_order_adjacent_vertices[n-this->n_vertices()][v];
}

const unsigned short int Tri6::_second_order_adjacent_vertices[3][2] =
{
  {0, 1}, // vertices adjacent to node 3
  {1, 2}, // vertices adjacent to node 4
  {0, 2}  // vertices adjacent to node 5
};

std::pair<unsigned short int, unsigned short int>
Tri6::second_order_child_vertex (const unsigned int n) const
{
  assert (n >= this->n_vertices());
  assert (n < this->n_nodes());
  return std::pair<unsigned short int, unsigned short int>
    (_second_order_vertex_child_number[n],
     _second_order_vertex_child_index[n]);
}

const unsigned short int Tri6::_second_order_vertex_child_number[6] =
{
  99,99,99, // Vertices
  0,1,0     // Edges
};

const unsigned short int Tri6::_second_order_vertex_child_index[6] =
{
  99,99,99, // Vertices
  1,2,2     // Edges
};
<commit_msg>The people responsible for sacking the previous bug have just been sacked.<commit_after>// $Id: face_tri6.C,v 1.30 2007-02-07 00:11:05 roystgnr Exp $

// The libMesh Finite Element Library.
// Copyright (C) 2002-2005  Benjamin S. Kirk, John W. Peterson

// This library 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 library 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.

// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA

// C++ includes

// Local includes
#include "side.h"
#include "edge_edge3.h"
#include "face_tri6.h"

// ------------------------------------------------------------
// Tri6 class static member initializations
const unsigned int Tri6::side_nodes_map[3][3] =
{
  {0, 1, 3}, // Side 0
  {1, 2, 4}, // Side 1
  {2, 0, 5}  // Side 2
};

#ifdef ENABLE_AMR

const float Tri6::_embedding_matrix[4][6][6] =
{
  // embedding matrix for child 0
  {
    //  0      1      2    3    4    5
    { 1.0,   0.0,   0.0, 0.0, 0.0, 0.0}, // 0
    { 0.0,   0.0,   0.0, 1.0, 0.0, 0.0}, // 1
    { 0.0,   0.0,   0.0, 0.0, 0.0, 1.0}, // 2
    {.375, -.125,   0.0, .75, 0.0, 0.0}, // 3
    { 0.0, -.125, -.125, 0.5, .25, 0.5}, // 4
    {.375,   0.0, -.125, 0.0, 0.0, .75}  // 5
  },

  // embedding matrix for child 1
  {
    //  0      1      2    3    4    5
    {  0.0,  0.0,   0.0, 1.0, 0.0, 0.0}, // 0
    {  0.0,  1.0,   0.0, 0.0, 0.0, 0.0}, // 1
    {  0.0,  0.0,   0.0, 0.0, 1.0, 0.0}, // 2
    {-.125, .375,   0.0, .75, 0.0, 0.0}, // 3
    {  0.0, .375, -.125, 0.0, .75, 0.0}, // 4
    {-.125,  0.0, -.125, 0.5, 0.5, .25}  // 5
  },

  // embedding matrix for child 2
  {
    //  0       1     2    3    4    5
    {  0.0,   0.0,  0.0, 0.0, 0.0, 1.0}, // 0
    {  0.0,   0.0,  0.0, 0.0, 1.0, 0.0}, // 1
    {  0.0,   0.0,  1.0, 0.0, 0.0, 0.0}, // 2
    {-.125, -.125,  0.0, .25, 0.5, 0.5}, // 3
    {  0.0, -.125, .375, 0.0, .75, 0.0}, // 4
    {-.125,   0.0, .375, 0.0, 0.0, .75}  // 5
  },

  // embedding matrix for child 3
  {
    //  0       1      2    3    4    5
    {  0.0,   0.0,   0.0, 1.0, 0.0, 0.0}, // 0
    {  0.0,   0.0,   0.0, 0.0, 1.0, 0.0}, // 1
    {  0.0,   0.0,   0.0, 0.0, 0.0, 1.0}, // 2
    {-.125,   0.0, -.125, 0.5, 0.5, .25}, // 3
    {-.125, -.125,   0.0, .25, 0.5, 0.5}, // 4
    {  0.0, -.125, -.125, 0.5, .25, 0.5}  // 5
  }
};

#endif

// ------------------------------------------------------------
// Tri6 class member functions

bool Tri6::is_vertex(const unsigned int i) const
{
  if (i < 3)
    return true;
  return false;
}

bool Tri6::is_edge(const unsigned int i) const
{
  if (i < 3)
    return false;
  return true;
}

bool Tri6::is_face(const unsigned int) const
{
  return false;
}

bool Tri6::is_node_on_side(const unsigned int n,
			   const unsigned int s) const
{
  assert(s < n_sides());
  for (unsigned int i = 0; i != 3; ++i)
    if (side_nodes_map[s][i] == n)
      return true;
  return false;
}

bool Tri6::has_affine_map() const
{
  // Make sure edges are straight
  if (!this->point(3).relative_fuzzy_equals
      ((this->point(0) + this->point(1))/2.))
    return false;
  if (!this->point(4).relative_fuzzy_equals
      ((this->point(1) + this->point(2))/2.))
    return false;
  if (!this->point(5).relative_fuzzy_equals
      ((this->point(2) + this->point(0))/2.))
    return false;

  return true;
}

unsigned int Tri6::key (const unsigned int s) const
{
  assert (s < this->n_sides());

  switch (s)
    {
    case 0:

      return
	this->compute_key (this->node(3));

    case 1:

      return
	this->compute_key (this->node(4));

    case 2:

      return
	this->compute_key (this->node(5));
    }

  // We will never get here...  Look at the code above.
  error();
  return 0;
}

AutoPtr<Elem> Tri6::build_side (const unsigned int i) const
{
  assert (i < this->n_sides());

  AutoPtr<Elem> ap(new Side<Edge3,Tri6>(this,i));
  return ap;

//   Edge3* edge = new Edge3;

//   switch (i)
//     {
//     case 0:
//       {
// 	edge->set_node(0) = this->get_node(0);
// 	edge->set_node(1) = this->get_node(1);
// 	edge->set_node(2) = this->get_node(3);

// 	AutoPtr<Elem> ap(edge);  return ap;
//       }
//     case 1:
//       {
// 	edge->set_node(0) = this->get_node(1);
// 	edge->set_node(1) = this->get_node(2);
// 	edge->set_node(2) = this->get_node(4);

// 	AutoPtr<Elem> ap(edge);  return ap;
//       }
//     case 2:
//       {
// 	edge->set_node(0) = this->get_node(2);
// 	edge->set_node(1) = this->get_node(0);
// 	edge->set_node(2) = this->get_node(5);

// 	AutoPtr<Elem> ap(edge);  return ap;
//       }
//     default:
//       {
// 	error();
//       }
//     }

//   // We will never get here...  Look at the code above.
//   error();
//   AutoPtr<Elem> ap(NULL);  return ap;
}

void Tri6::connectivity(const unsigned int sf,
			const IOPackage iop,
			std::vector<unsigned int>& conn) const
{
  assert (sf < this->n_sub_elem());
  assert (iop != INVALID_IO_PACKAGE);

  switch (iop)
    {
    case TECPLOT:
      {
	conn.resize(4);
	switch(sf)
	  {
	  case 0:
	    // linear sub-triangle 0
	    conn[0] = this->node(0)+1;
	    conn[1] = this->node(3)+1;
	    conn[2] = this->node(5)+1;
	    conn[3] = this->node(5)+1;

	    return;

	  case 1:
	    // linear sub-triangle 1
	    conn[0] = this->node(3)+1;
	    conn[1] = this->node(1)+1;
	    conn[2] = this->node(4)+1;
	    conn[3] = this->node(4)+1;

	    return;

	  case 2:
	    // linear sub-triangle 2
	    conn[0] = this->node(5)+1;
	    conn[1] = this->node(4)+1;
	    conn[2] = this->node(2)+1;
	    conn[3] = this->node(2)+1;

	    return;

	  case 3:
	    // linear sub-triangle 3
	    conn[0] = this->node(3)+1;
	    conn[1] = this->node(4)+1;
	    conn[2] = this->node(5)+1;
	    conn[3] = this->node(5)+1;

	    return;

	  default:
	    error();
	  }
      }

    case VTK:
      {
	conn.resize(3);
	switch(sf)
	  {
	  case 0:
	    // linear sub-triangle 0
	    conn[0] = this->node(0);
	    conn[1] = this->node(3);
	    conn[2] = this->node(5);

	    return;

	  case 1:
	    // linear sub-triangle 1
	    conn[0] = this->node(3);
	    conn[1] = this->node(1);
	    conn[2] = this->node(4);

	    return;

	  case 2:
	    // linear sub-triangle 2
	    conn[0] = this->node(5);
	    conn[1] = this->node(4);
	    conn[2] = this->node(2);

	    return;

	  case 3:
	    // linear sub-triangle 3
	    conn[0] = this->node(3);
	    conn[1] = this->node(4);
	    conn[2] = this->node(5);

	    return;

	  default:
	    error();
	  }
      }

    default:
      error();
    }

  error();
}

unsigned short int Tri6::second_order_adjacent_vertex (const unsigned int n,
						       const unsigned int v) const
{
  assert (n >= this->n_vertices());
  assert (n <  this->n_nodes());
  assert (v < 2);
  return _second_order_adjacent_vertices[n-this->n_vertices()][v];
}

const unsigned short int Tri6::_second_order_adjacent_vertices[3][2] =
{
  {0, 1}, // vertices adjacent to node 3
  {1, 2}, // vertices adjacent to node 4
  {0, 2}  // vertices adjacent to node 5
};

std::pair<unsigned short int, unsigned short int>
Tri6::second_order_child_vertex (const unsigned int n) const
{
  assert (n >= this->n_vertices());
  assert (n < this->n_nodes());
  return std::pair<unsigned short int, unsigned short int>
    (_second_order_vertex_child_number[n],
     _second_order_vertex_child_index[n]);
}

const unsigned short int Tri6::_second_order_vertex_child_number[6] =
{
  99,99,99, // Vertices
  0,1,0     // Edges
};

const unsigned short int Tri6::_second_order_vertex_child_index[6] =
{
  99,99,99, // Vertices
  1,2,2     // Edges
};
<|endoftext|>


<commit_before>#include "GETSTUFF.H"

#include "SPECIFIC.H"

long DIVFP(long A, long B)
{
	return (A / (B >> 8)) << 8;
}

long MULFP(long A, long B)
{
	if (A && B != 0)
	{
		return ((A % B) << 16) | ((A * B) >> 16);
	}
	else
	{
		return ((A * B) >> 16);
	}
}

int xLOS(struct GAME_VECTOR* start, struct GAME_VECTOR* target)
{
	UNIMPLEMENTED();
	return 0;
}

int zLOS(struct GAME_VECTOR* start, struct GAME_VECTOR* target)
{
	UNIMPLEMENTED();
	return 0;
}
<commit_msg>Correct MULFP (PSXPC_N)<commit_after>#include "GETSTUFF.H"

#include "SPECIFIC.H"

long DIVFP(long A, long B)
{
	return (A / (B >> 8)) << 8;
}

long MULFP(long A, long B)
{
	unsigned long long result = (long long)((long long)(int)A * (long long)(int)B);
	return ((result >> 32) << 16) | ((result & 0xFFFFFFFF) >> 16);
}

int xLOS(struct GAME_VECTOR* start, struct GAME_VECTOR* target)
{
	UNIMPLEMENTED();
	return 0;
}

int zLOS(struct GAME_VECTOR* start, struct GAME_VECTOR* target)
{
	UNIMPLEMENTED();
	return 0;
}
<|endoftext|>


<commit_before>#include "Sampler.hpp"

#include <cstdlib>
#include <cstring>
#include <iostream>
#include <sstream>
#include <iterator>
#include <complex>

#ifdef PAPI
#include <papi.h>
#endif

#include CFG_H
#include "sample.h"

using namespace std;

void Sampler::set_counters(const vector<string> &tokens) {
#ifdef PAPI
    // ignore excess counters
    const int maxcounters = PAPI_num_counters();
    size_t ncounters = tokens.size() - 1;
    if (ncounters > maxcounters) {
        cerr << "Too many counters specified: given " << ncounters;
        cerr << " maximum " << maxcounters << " (truncating counter list)" << endl;
        ncounters = maxcounters;
    }

    // clear old counters
    counters.clear();

    // register new counters individually
    for (size_t i = 0; i < ncounters; i++) {

        // convert string to code
        int code;
        char str[PAPI_MAX_STR_LEN];  // need to pass a non-const *
        strcpy(str, tokens[i + 1].c_str());
        const int check = PAPI_event_name_to_code(str, &code);

        // check for errors
        if (check == PAPI_OK)
            counters.push_back(code);
        else if (check == PAPI_ENOTPRESET)
            cerr << "Counter unknown: " << tokens[i + 1] << " (counter ignored)" << endl;
        else if (check == PAPI_ENOEVNT)
            cerr << "Counter unavailable: " << tokens[i + 1] << " (counter ignored)" << endl;
    }
#else
    cerr << "PAPI support not enabled (command ignored)" << endl;
#endif
}

template <typename T>
void Sampler::named_malloc(const vector<string> &tokens) {
    // require 2 arguments: name, size
    if (tokens.size() < 3) {
        cerr << "Too few arguments for " << tokens[0] << " (command ignored)" << endl;
        cerr << "usage (example): " << tokens[0] << " A 10000" << endl;
        return;
    }
    if (tokens.size() > 3) {
        cerr << "Ignoring excess arguments for " << tokens[0] << endl;
        cerr << "usage (example): " << tokens[0] << " A 10000" << endl;
    }

    // parse arguments
    const string &name = tokens[1];
    const size_t size = atoi(tokens[2].c_str());

    // variable must not exist yet
    if (mem.named_exists(name)) {
        cerr << "Variable already exists: " << name << " (command ignored)" << endl;
        return;
    }
    // name must beginn with letter
    if (!isalpha(name[0])) {
        cerr << "Variable name must begin with a letter: " << name << " (command ignored)" << endl;
        return;
    }

    //TODO: check size conversion error
    // size must be > 0
    if (size < 0) {
        cerr << "Cannot allocate variable of negative size " << size << " (command ignored)" << endl;
        return;
    }

    // malloc the variabel
    mem.named_malloc<T>(name, size);
}

template <typename T>
void Sampler::named_offset(const vector<string> &tokens) {
    // require 3 arguments: oldname, offset, newname
    if (tokens.size() < 4) {
        cerr << "Too few arguments for " << tokens[0] << " (command ignored)" << endl;
        cerr << "usage (example): " << tokens[0] << " Old 10000 New" << endl;
        return;
    }
    if (tokens.size() > 4) {
        cerr << "Ignoring excess arguments for " << tokens[0] << endl;
        cerr << "usage (example): " << tokens[0] << " Old 10000 New" << endl;
    }

    // parse arguments
    const string &oldname = tokens[1];
    const ssize_t offset = atoi(tokens[2].c_str());
    const string &newname = tokens[3];

    // oldname must exist
    if (!mem.named_exists(oldname)) {
        cerr << "Unknown variable: " << oldname << " (command ignored)" << endl;
        return;
    }
    // TODO: check offset conversion errors
    // newname must not exist yet
    if (mem.named_exists(newname)) {
        cerr << "Variable already exists: " << newname << " (command ignored)" << endl;
        return;
    }

    // alias a new offset
    mem.named_offset<T>(oldname, offset, newname);
}

void Sampler::named_free(const vector<string> &tokens) {
    // require 1 argument: name
    if (tokens.size() < 2) {
        cerr << "Too few arguments for " << tokens[0] << " (command ignored)" << endl;
        cerr << "usage (example): " << tokens[0] << " A" << endl;
        return;
    }
    if (tokens.size() > 2) {
        cerr << "Ignoring excess arguments for " << tokens[0] << endl;
        cerr << "usage (example): " << tokens[0] << " A" << endl;
    }

    // parse arguments
    const string &name = tokens[1];

    // check existence
    if (!mem.named_exists(name)) {
        cerr << "Unknown variable: " << name << " (command ignored)" << endl;
        return;
    }

    // free the variabel
    mem.named_free(name);
}

void Sampler::add_call(const vector<string> &tokens) {
    const string &routine = tokens[0];

    // catch unknown routines
    if (signatures.find(routine) == signatures.end()) {
        cerr << "Uknown kernel: " << routine << " (call ignored)" << endl;
        return;
    }

    // (try to) set up a call parser for the kernel
    const Signature &signature = signatures[routine];
    try {
        CallParser callparser(tokens, signature, mem);
        callparsers.push_back(callparser);
    } catch (CallParserException &e) {
        // the call could not be parserd
        // (failure already reported)
    }
}

void Sampler::go(const vector<string> &tokens) {
    size_t ncalls = callparsers.size();
    KernelCall *calls = new KernelCall[ncalls];

    // construct KernelCalls (C structs)
    for (size_t i = 0; i < ncalls; i++)
        calls[i] = callparsers[i].get_call();

    // run measurements
#ifdef PAPI
    sample(calls, ncalls, &counters[0], counters.size());
#else
    sample(calls, ncalls);
#endif

    // print results
    for (size_t i = 0; i < ncalls; i++) {
        cout << calls[i].rdtsc;
#ifdef PAPI
        for (size_t j = 0; j < counters.size(); j++)
            cout << "\t" << calls[i].counters[j];
#endif
        cout << endl;
    }

    // clean up
    delete [] calls;
    callparsers.clear();
    mem.static_reset();
}

void Sampler::add_signature(const Signature &signature) {
    signatures[signature.name] = signature;
}

void Sampler::start() {
    map<string, void (Sampler:: *)(const vector<string> &)> commands;
    commands["go"] = &Sampler::go;
    commands["set_counters"] = &Sampler::set_counters;
    commands["malloc"] = &Sampler::named_malloc<char>;
    commands["imalloc"] = &Sampler::named_malloc<int>;
    commands["smalloc"] = &Sampler::named_malloc<float>;
    commands["dmalloc"] = &Sampler::named_malloc<double>;
    commands["cmalloc"] = &Sampler::named_malloc<complex<float> >;
    commands["zmalloc"] = &Sampler::named_malloc<complex<double> >;
    commands["offset"] = &Sampler::named_offset<char>;
    commands["ioffset"] = &Sampler::named_offset<int>;
    commands["soffset"] = &Sampler::named_offset<float>;
    commands["doffset"] = &Sampler::named_offset<double>;
    commands["coffset"] = &Sampler::named_offset<complex<float> >;
    commands["zoffset"] = &Sampler::named_offset<complex<double> >;
    commands["free"] = &Sampler::named_free;

    // read stdin by lines
    string line;
    while (getline(cin, line)) {

        // clear comments
        line = line.substr(0, line.find_first_of("#"));

        // ignore empty lines
        if (line.size() == 0)
            continue;

        // remove leading spaces
        line = line.substr(line.find_first_not_of(" \t\n\v\f\r"));

        // ignore empty lines
        if (line.size() == 0)
            continue;

        // tokenize line
        vector<string> tokens;
        istringstream iss(line);
        copy(istream_iterator<string>(iss), istream_iterator<string>(), back_inserter(tokens));

        // check for commands
        map<string, void (Sampler:: *)(const vector<string> &)>::iterator command = commands.find(tokens[0]);
        if (command != commands.end())
            (this->*(command->second))(tokens);
        else
            add_call(tokens);
    }

    // process remaining calls
    go(vector<string>());
}
<commit_msg>add print/date commands<commit_after>#include "Sampler.hpp"

#include <cstdlib>
#include <cstring>
#include <iostream>
#include <sstream>
#include <iterator>
#include <complex>

#ifdef PAPI
#include <papi.h>
#endif

#include CFG_H
#include "sample.h"

using namespace std;

void Sampler::set_counters(const vector<string> &tokens) {
#ifdef PAPI
    // ignore excess counters
    const int maxcounters = PAPI_num_counters();
    size_t ncounters = tokens.size() - 1;
    if (ncounters > maxcounters) {
        cerr << "Too many counters specified: given " << ncounters;
        cerr << " maximum " << maxcounters << " (truncating counter list)" << endl;
        ncounters = maxcounters;
    }

    // clear old counters
    counters.clear();

    // register new counters individually
    for (size_t i = 0; i < ncounters; i++) {

        // convert string to code
        int code;
        char str[PAPI_MAX_STR_LEN];  // need to pass a non-const *
        strcpy(str, tokens[i + 1].c_str());
        const int check = PAPI_event_name_to_code(str, &code);

        // check for errors
        if (check == PAPI_OK)
            counters.push_back(code);
        else if (check == PAPI_ENOTPRESET)
            cerr << "Counter unknown: " << tokens[i + 1] << " (counter ignored)" << endl;
        else if (check == PAPI_ENOEVNT)
            cerr << "Counter unavailable: " << tokens[i + 1] << " (counter ignored)" << endl;
    }
#else
    cerr << "PAPI support not enabled (command ignored)" << endl;
#endif
}

template <typename T>
void Sampler::named_malloc(const vector<string> &tokens) {
    // require 2 arguments: name, size
    if (tokens.size() < 3) {
        cerr << "Too few arguments for " << tokens[0] << " (command ignored)" << endl;
        cerr << "usage (example): " << tokens[0] << " A 10000" << endl;
        return;
    }
    if (tokens.size() > 3) {
        cerr << "Ignoring excess arguments for " << tokens[0] << endl;
        cerr << "usage (example): " << tokens[0] << " A 10000" << endl;
    }

    // parse arguments
    const string &name = tokens[1];
    const size_t size = atoi(tokens[2].c_str());

    // variable must not exist yet
    if (mem.named_exists(name)) {
        cerr << "Variable already exists: " << name << " (command ignored)" << endl;
        return;
    }
    // name must beginn with letter
    if (!isalpha(name[0])) {
        cerr << "Variable name must begin with a letter: " << name << " (command ignored)" << endl;
        return;
    }

    //TODO: check size conversion error
    // size must be > 0
    if (size < 0) {
        cerr << "Cannot allocate variable of negative size " << size << " (command ignored)" << endl;
        return;
    }

    // malloc the variabel
    mem.named_malloc<T>(name, size);
}

template <typename T>
void Sampler::named_offset(const vector<string> &tokens) {
    // require 3 arguments: oldname, offset, newname
    if (tokens.size() < 4) {
        cerr << "Too few arguments for " << tokens[0] << " (command ignored)" << endl;
        cerr << "usage (example): " << tokens[0] << " Old 10000 New" << endl;
        return;
    }
    if (tokens.size() > 4) {
        cerr << "Ignoring excess arguments for " << tokens[0] << endl;
        cerr << "usage (example): " << tokens[0] << " Old 10000 New" << endl;
    }

    // parse arguments
    const string &oldname = tokens[1];
    const ssize_t offset = atoi(tokens[2].c_str());
    const string &newname = tokens[3];

    // oldname must exist
    if (!mem.named_exists(oldname)) {
        cerr << "Unknown variable: " << oldname << " (command ignored)" << endl;
        return;
    }
    // TODO: check offset conversion errors
    // newname must not exist yet
    if (mem.named_exists(newname)) {
        cerr << "Variable already exists: " << newname << " (command ignored)" << endl;
        return;
    }

    // alias a new offset
    mem.named_offset<T>(oldname, offset, newname);
}

void Sampler::named_free(const vector<string> &tokens) {
    // require 1 argument: name
    if (tokens.size() < 2) {
        cerr << "Too few arguments for " << tokens[0] << " (command ignored)" << endl;
        cerr << "usage (example): " << tokens[0] << " A" << endl;
        return;
    }
    if (tokens.size() > 2) {
        cerr << "Ignoring excess arguments for " << tokens[0] << endl;
        cerr << "usage (example): " << tokens[0] << " A" << endl;
    }

    // parse arguments
    const string &name = tokens[1];

    // check existence
    if (!mem.named_exists(name)) {
        cerr << "Unknown variable: " << name << " (command ignored)" << endl;
        return;
    }

    // free the variabel
    mem.named_free(name);
}

void Sampler::add_call(const vector<string> &tokens) {
    const string &routine = tokens[0];

    // catch unknown routines
    if (signatures.find(routine) == signatures.end()) {
        cerr << "Uknown kernel: " << routine << " (call ignored)" << endl;
        return;
    }

    // (try to) set up a call parser for the kernel
    const Signature &signature = signatures[routine];
    try {
        CallParser callparser(tokens, signature, mem);
        callparsers.push_back(callparser);
    } catch (CallParserException &e) {
        // the call could not be parserd
        // (failure already reported)
    }
}

void Sampler::go(const vector<string> &tokens) {
    size_t ncalls = callparsers.size();
    KernelCall *calls = new KernelCall[ncalls];

    // construct KernelCalls (C structs)
    for (size_t i = 0; i < ncalls; i++)
        calls[i] = callparsers[i].get_call();

    // run measurements
#ifdef PAPI
    sample(calls, ncalls, &counters[0], counters.size());
#else
    sample(calls, ncalls);
#endif

    // print results
    for (size_t i = 0; i < ncalls; i++) {
        cout << calls[i].rdtsc;
#ifdef PAPI
        for (size_t j = 0; j < counters.size(); j++)
            cout << "\t" << calls[i].counters[j];
#endif
        cout << endl;
    }

    // clean up
    delete [] calls;
    callparsers.clear();
    mem.static_reset();
}

void Sampler::add_signature(const Signature &signature) {
    signatures[signature.name] = signature;
}

void Sampler::start() {
    map<string, void (Sampler:: *)(const vector<string> &)> commands;
    commands["go"] = &Sampler::go;
    commands["set_counters"] = &Sampler::set_counters;
    commands["malloc"] = &Sampler::named_malloc<char>;
    commands["imalloc"] = &Sampler::named_malloc<int>;
    commands["smalloc"] = &Sampler::named_malloc<float>;
    commands["dmalloc"] = &Sampler::named_malloc<double>;
    commands["cmalloc"] = &Sampler::named_malloc<complex<float> >;
    commands["zmalloc"] = &Sampler::named_malloc<complex<double> >;
    commands["offset"] = &Sampler::named_offset<char>;
    commands["ioffset"] = &Sampler::named_offset<int>;
    commands["soffset"] = &Sampler::named_offset<float>;
    commands["doffset"] = &Sampler::named_offset<double>;
    commands["coffset"] = &Sampler::named_offset<complex<float> >;
    commands["zoffset"] = &Sampler::named_offset<complex<double> >;
    commands["free"] = &Sampler::named_free;
    commands["print"] = &Sampler::print;
    commands["date"] = &Sampler::date;

    // read stdin by lines
    string line;
    while (getline(cin, line)) {

        // clear comments
        line = line.substr(0, line.find_first_of("#"));

        // ignore empty lines
        if (line.size() == 0)
            continue;

        // remove leading spaces
        line = line.substr(line.find_first_not_of(" \t\n\v\f\r"));

        // ignore empty lines
        if (line.size() == 0)
            continue;

        // tokenize line
        vector<string> tokens;
        istringstream iss(line);
        copy(istream_iterator<string>(iss), istream_iterator<string>(), back_inserter(tokens));

        // check for commands
        map<string, void (Sampler:: *)(const vector<string> &)>::iterator command = commands.find(tokens[0]);
        if (command != commands.end())
            (this->*(command->second))(tokens);
        else
            add_call(tokens);
    }

    // process remaining calls
    go(vector<string>());
}
<|endoftext|>


<commit_before>/*
    KNode, the KDE newsreader
    Copyright (c) 1999-2006 the KNode authors.
    See file AUTHORS for details
    Copyright (c) 2005 Rafal Rzepecki <divide@users.sourceforge.net>

    This program is free software; you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation; either version 2 of the License, or
    (at your option) any later version.
    You should have received a copy of the GNU General Public License
    along with this program; if not, write to the Free Software Foundation,
    Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, US
*/

#include <QDrag>
#include <QPainter>
#include <QPixmap>

#include <kdebug.h>

#include <libkdepim/kdepimprotocols.h>

#include "knglobals.h"
#include "knconfigmanager.h"
#include "knhdrviewitem.h"
#include "knarticle.h"
#include "headerview.h"
#include "settings.h"

KNHdrViewItem::KNHdrViewItem( KNHeaderView *ref, KNArticle *a ) :
  K3ListViewItem( ref )
{
  init( a );
}

KNHdrViewItem::KNHdrViewItem( KNHdrViewItem *ref, KNArticle *a ) :
  K3ListViewItem( ref )
{
  init( a );
}

void KNHdrViewItem::init( KNArticle *a )
{
  art = a;
  mActive = false;
  for ( int i = 0; i < 5; ++i) // FIXME hardcoded column count
    mShowToolTip[i] = false;
}

KNHdrViewItem::~KNHdrViewItem()
{
  if (mActive) {
    Q3ListView *lv = listView();
    if (lv)
      static_cast<KNHeaderView*>( lv )->activeRemoved();
  }

  if (art) art->setListItem( 0 );
}

void KNHdrViewItem::expandChildren()
{
  Q3ListViewItemIterator it( firstChild() );
  for ( ; it.current(); ++it) {
    if (it.current()->depth() <= depth())
      break;
    it.current()->setOpen( true );
  }
}

int KNHdrViewItem::compare( Q3ListViewItem *i, int col, bool ) const
{
  KNArticle *otherArticle = static_cast<KNHdrViewItem*>( i )->art;
  int diff = 0;
  time_t date1 = 0, date2 = 0;

  switch (col) {
    case 0:
    case 1:
       return text( col ).localeAwareCompare( i->text(col) );

    case 2:
       if (art->type() == KNArticle::ATremote) {
         diff = static_cast<KNRemoteArticle*>( art )->score() - static_cast<KNRemoteArticle*>( otherArticle )->score();
         return (diff < 0 ? -1 : diff > 0 ? 1 : 0);
       } else
         return 0;

    case 3:
       diff = art->lines()->numberOfLines() - otherArticle->lines()->numberOfLines();
       return (diff < 0 ? -1 : diff > 0 ? 1 : 0);

    case 4:
       date1 = art->date()->dateTime().toTime_t();
       date2 = otherArticle->date()->dateTime().toTime_t();
       if (art->type() == KNArticle::ATremote && static_cast<KNHeaderView*>( listView() )->sortByThreadChangeDate()) {
         if (static_cast<KNRemoteArticle*>( art )->subThreadChangeDate() > date1)
           date1 = static_cast<KNRemoteArticle*>( art )->subThreadChangeDate();
         if (static_cast<KNRemoteArticle*>( otherArticle )->subThreadChangeDate() > date2)
           date2 = static_cast<KNRemoteArticle*>( otherArticle )->subThreadChangeDate();
       }
       diff = date1 - date2;
       return (diff < 0 ? -1 : diff > 0 ? 1 : 0);

    default:
       return 0;
  }
}

void KNHdrViewItem::paintCell( QPainter *p, const QColorGroup &cg, int column, int width, int alignment )
{
  int xText = 0, xPM = 3, yPM = 0;
  QColor base;
  const KPaintInfo *paintInfo = static_cast<KNHeaderView*>( listView() )->paintInfo();

  QPen pen = p->pen();
  if (isSelected() || mActive) {
    pen.setColor( cg.color( QPalette::HighlightedText ) );
    base = cg.color( QPalette::Highlight );
  } else {
    if (greyOut())
      pen.setColor( greyColor() );
    else
      pen.setColor( normalColor() );
    base = backgroundColor( column );
  }

  p->setPen( pen );

  p->fillRect( 0, 0, width, height(), QBrush(base) );

  if ( column == paintInfo->subCol ) {
    QFont font = p->font();
    font.setBold( firstColBold() );
    p->setFont( font );
    const QPixmap *pm;

    for (int i = 0; i < 4; i++) {
      pm = pixmap( i );
      if (pm && !pm->isNull()) {
        yPM = (height() - pm->height()) / 2;
        p->drawPixmap( xPM, yPM, *pm );
        xPM += pm->width() + 3;
      }
    }

    xText = xPM;
  }

  if (width - xText - 5 > 0) {
    int cntWidth = 0;
    QString t2;
    QFont f2;
    if (countUnreadInThread() > 0 && column == paintInfo->subCol && !isOpen()) {
      t2 = QString( " (%1)" ).arg( countUnreadInThread() );
      f2 = p->font();
      f2.setBold( true );
      cntWidth = QFontMetrics( f2 ).width( t2, -1 );
    }
    QString t = p->fontMetrics().elidedText( text( column ), Qt::ElideRight, width - xText - cntWidth - 5  );

    // show tooltip if we have to squeeze the text
    if ( t != text( column ) )
      mShowToolTip[column] = true;
    else
      mShowToolTip[column] = false;

    p->drawText( xText, 0, width - xText - 5, height(), alignment | Qt::AlignVCenter,  t );
    if (cntWidth) {
      QFont orig = p->font();
      p->setFont( f2 );
      QPen pen = p->pen();
      if (isSelected() || mActive) {
        pen.setColor( cg.color( QPalette::HighlightedText ) );
      } else {
        pen.setColor( cg.color( QPalette::Link ) );
      }
      p->setPen( pen );
      p->drawText( xText + QFontMetrics( orig ).width( t, -1 ), 0, width - xText - 5, height(), alignment | Qt::AlignVCenter,  t2 );
    }
  }
}

int KNHdrViewItem::width( const QFontMetrics &fm, const Q3ListView *, int column ) const
{
  int ret = fm.boundingRect( text(column) ).width();
  const KPaintInfo *paintInfo = static_cast<KNHeaderView*>( listView() )->paintInfo();

  // all pixmaps are drawn in the first column
  if ( column == paintInfo->subCol ) {
    const QPixmap *pm;
    for (int i = 0; i < 4; ++i) {
      pm = pixmap( i );
      if (pm && !pm->isNull())
        ret += pm->width() + 3;
    }
  }

  return ret;
}

QString KNHdrViewItem::text( int col ) const
{
  if ( !art )
    return QString();
  KNHeaderView *hv = static_cast<KNHeaderView*>( listView() );

  if ( col == hv->paintInfo()->subCol ) {
    return art->subject()->asUnicodeString();
  }

  if ( col == hv->paintInfo()->sizeCol ) {
    if ( art->lines()->numberOfLines() != -1 )
      return QString::number( art->lines()->numberOfLines() );
    else
      return QString();
  }

  if ( col == hv->paintInfo()->scoreCol ) {
    if ( art->type() == KNArticle::ATremote )
      return QString::number( static_cast<KNRemoteArticle*>( art )->score() );
    else
      return QString();
  }

  if ( col == hv->paintInfo()->dateCol ) {
    return hv->mDateFormatter.dateString( art->date()->dateTime().toTime_t() );
  } else
    return K3ListViewItem::text( col );
}

Q3DragObject* KNHdrViewItem::dragObject()
{
#ifdef __GNUC__
#warning Enable this section again, once KNHdrView does not derive from K3ListView any more and can process QDrag (not Q3DragObject)
#endif
return 0;
#if 0
  QDrag *drag = new QDrag( listView()->viewport() );
  QMimeData *md = new QMimeData;
  drag->setMimeData( md );

  KUrl::List list;
  QString mid = art->messageID()->asUnicodeString();
  // for some obscure reason it returns messageid in <>s
  mid = mid.mid( 1, mid.length() - 2 );
  list.append( KDEPIMPROTOCOL_NEWSARTICLE + mid );
  QMap<QString,QString> metadata;
  metadata["labels"] = KUrl::toPercentEncoding( art->subject()->asUnicodeString() );
  list.populateMimeData( md, metadata );
  md->setData( "x-knode-drag/article" , QByteArray() );

  drag->setPixmap( knGlobals.configManager()->appearance()->icon( KNode::Appearance::posting ) );
  return drag;
#endif
}

int KNHdrViewItem::countUnreadInThread()
{
  int count = 0;
  if ( knGlobals.settings()->showUnread() ) {
    if (art->type() == KNArticle::ATremote) {
      count = static_cast<KNRemoteArticle*>( art )->unreadFollowUps();
    }
  }
  return count;
}

bool KNHdrViewItem::greyOut()
{
  if (art->type() == KNArticle::ATremote) {
    return !static_cast<KNRemoteArticle*>( art )->hasUnreadFollowUps()
        && static_cast<KNRemoteArticle*>( art )->isRead();
  } else
    return false;
}

bool KNHdrViewItem::firstColBold()
{
  if(art->type() == KNArticle::ATremote)
    return static_cast<KNRemoteArticle*>( art )->isNew();
  else
    return false;
}

QColor KNHdrViewItem::normalColor()
{
  if (art->type()==KNArticle::ATremote)
    return static_cast<KNRemoteArticle*>( art )->color();
  else
    return knGlobals.settings()->unreadThreadColor();
}

QColor KNHdrViewItem::greyColor()
{
  return knGlobals.settings()->readThreadColor();
}

<commit_msg>Do not display a 0 line count when the Lines: header is missing<commit_after>/*
    KNode, the KDE newsreader
    Copyright (c) 1999-2006 the KNode authors.
    See file AUTHORS for details
    Copyright (c) 2005 Rafal Rzepecki <divide@users.sourceforge.net>

    This program is free software; you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation; either version 2 of the License, or
    (at your option) any later version.
    You should have received a copy of the GNU General Public License
    along with this program; if not, write to the Free Software Foundation,
    Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, US
*/

#include <QDrag>
#include <QPainter>
#include <QPixmap>

#include <kdebug.h>

#include <libkdepim/kdepimprotocols.h>

#include "knglobals.h"
#include "knconfigmanager.h"
#include "knhdrviewitem.h"
#include "knarticle.h"
#include "headerview.h"
#include "settings.h"

KNHdrViewItem::KNHdrViewItem( KNHeaderView *ref, KNArticle *a ) :
  K3ListViewItem( ref )
{
  init( a );
}

KNHdrViewItem::KNHdrViewItem( KNHdrViewItem *ref, KNArticle *a ) :
  K3ListViewItem( ref )
{
  init( a );
}

void KNHdrViewItem::init( KNArticle *a )
{
  art = a;
  mActive = false;
  for ( int i = 0; i < 5; ++i) // FIXME hardcoded column count
    mShowToolTip[i] = false;
}

KNHdrViewItem::~KNHdrViewItem()
{
  if (mActive) {
    Q3ListView *lv = listView();
    if (lv)
      static_cast<KNHeaderView*>( lv )->activeRemoved();
  }

  if (art) art->setListItem( 0 );
}

void KNHdrViewItem::expandChildren()
{
  Q3ListViewItemIterator it( firstChild() );
  for ( ; it.current(); ++it) {
    if (it.current()->depth() <= depth())
      break;
    it.current()->setOpen( true );
  }
}

int KNHdrViewItem::compare( Q3ListViewItem *i, int col, bool ) const
{
  KNArticle *otherArticle = static_cast<KNHdrViewItem*>( i )->art;
  int diff = 0;
  time_t date1 = 0, date2 = 0;

  switch (col) {
    case 0:
    case 1:
       return text( col ).localeAwareCompare( i->text(col) );

    case 2:
       if (art->type() == KNArticle::ATremote) {
         diff = static_cast<KNRemoteArticle*>( art )->score() - static_cast<KNRemoteArticle*>( otherArticle )->score();
         return (diff < 0 ? -1 : diff > 0 ? 1 : 0);
       } else
         return 0;

    case 3:
       diff = art->lines()->numberOfLines() - otherArticle->lines()->numberOfLines();
       return (diff < 0 ? -1 : diff > 0 ? 1 : 0);

    case 4:
       date1 = art->date()->dateTime().toTime_t();
       date2 = otherArticle->date()->dateTime().toTime_t();
       if (art->type() == KNArticle::ATremote && static_cast<KNHeaderView*>( listView() )->sortByThreadChangeDate()) {
         if (static_cast<KNRemoteArticle*>( art )->subThreadChangeDate() > date1)
           date1 = static_cast<KNRemoteArticle*>( art )->subThreadChangeDate();
         if (static_cast<KNRemoteArticle*>( otherArticle )->subThreadChangeDate() > date2)
           date2 = static_cast<KNRemoteArticle*>( otherArticle )->subThreadChangeDate();
       }
       diff = date1 - date2;
       return (diff < 0 ? -1 : diff > 0 ? 1 : 0);

    default:
       return 0;
  }
}

void KNHdrViewItem::paintCell( QPainter *p, const QColorGroup &cg, int column, int width, int alignment )
{
  int xText = 0, xPM = 3, yPM = 0;
  QColor base;
  const KPaintInfo *paintInfo = static_cast<KNHeaderView*>( listView() )->paintInfo();

  QPen pen = p->pen();
  if (isSelected() || mActive) {
    pen.setColor( cg.color( QPalette::HighlightedText ) );
    base = cg.color( QPalette::Highlight );
  } else {
    if (greyOut())
      pen.setColor( greyColor() );
    else
      pen.setColor( normalColor() );
    base = backgroundColor( column );
  }

  p->setPen( pen );

  p->fillRect( 0, 0, width, height(), QBrush(base) );

  if ( column == paintInfo->subCol ) {
    QFont font = p->font();
    font.setBold( firstColBold() );
    p->setFont( font );
    const QPixmap *pm;

    for (int i = 0; i < 4; i++) {
      pm = pixmap( i );
      if (pm && !pm->isNull()) {
        yPM = (height() - pm->height()) / 2;
        p->drawPixmap( xPM, yPM, *pm );
        xPM += pm->width() + 3;
      }
    }

    xText = xPM;
  }

  if (width - xText - 5 > 0) {
    int cntWidth = 0;
    QString t2;
    QFont f2;
    if (countUnreadInThread() > 0 && column == paintInfo->subCol && !isOpen()) {
      t2 = QString( " (%1)" ).arg( countUnreadInThread() );
      f2 = p->font();
      f2.setBold( true );
      cntWidth = QFontMetrics( f2 ).width( t2, -1 );
    }
    QString t = p->fontMetrics().elidedText( text( column ), Qt::ElideRight, width - xText - cntWidth - 5  );

    // show tooltip if we have to squeeze the text
    if ( t != text( column ) )
      mShowToolTip[column] = true;
    else
      mShowToolTip[column] = false;

    p->drawText( xText, 0, width - xText - 5, height(), alignment | Qt::AlignVCenter,  t );
    if (cntWidth) {
      QFont orig = p->font();
      p->setFont( f2 );
      QPen pen = p->pen();
      if (isSelected() || mActive) {
        pen.setColor( cg.color( QPalette::HighlightedText ) );
      } else {
        pen.setColor( cg.color( QPalette::Link ) );
      }
      p->setPen( pen );
      p->drawText( xText + QFontMetrics( orig ).width( t, -1 ), 0, width - xText - 5, height(), alignment | Qt::AlignVCenter,  t2 );
    }
  }
}

int KNHdrViewItem::width( const QFontMetrics &fm, const Q3ListView *, int column ) const
{
  int ret = fm.boundingRect( text(column) ).width();
  const KPaintInfo *paintInfo = static_cast<KNHeaderView*>( listView() )->paintInfo();

  // all pixmaps are drawn in the first column
  if ( column == paintInfo->subCol ) {
    const QPixmap *pm;
    for (int i = 0; i < 4; ++i) {
      pm = pixmap( i );
      if (pm && !pm->isNull())
        ret += pm->width() + 3;
    }
  }

  return ret;
}

QString KNHdrViewItem::text( int col ) const
{
  if ( !art )
    return QString();
  KNHeaderView *hv = static_cast<KNHeaderView*>( listView() );

  if ( col == hv->paintInfo()->subCol ) {
    return art->subject()->asUnicodeString();
  }

  if ( col == hv->paintInfo()->sizeCol ) {
    if ( art->lines()->numberOfLines() != 0 ) { // invalid values are read as '0' in KNGroup::insortHeaders()
      return QString::number( art->lines()->numberOfLines() );
    } else {
      return QString();
    }
  }

  if ( col == hv->paintInfo()->scoreCol ) {
    if ( art->type() == KNArticle::ATremote )
      return QString::number( static_cast<KNRemoteArticle*>( art )->score() );
    else
      return QString();
  }

  if ( col == hv->paintInfo()->dateCol ) {
    return hv->mDateFormatter.dateString( art->date()->dateTime().toTime_t() );
  } else
    return K3ListViewItem::text( col );
}

Q3DragObject* KNHdrViewItem::dragObject()
{
#ifdef __GNUC__
#warning Enable this section again, once KNHdrView does not derive from K3ListView any more and can process QDrag (not Q3DragObject)
#endif
return 0;
#if 0
  QDrag *drag = new QDrag( listView()->viewport() );
  QMimeData *md = new QMimeData;
  drag->setMimeData( md );

  KUrl::List list;
  QString mid = art->messageID()->asUnicodeString();
  // for some obscure reason it returns messageid in <>s
  mid = mid.mid( 1, mid.length() - 2 );
  list.append( KDEPIMPROTOCOL_NEWSARTICLE + mid );
  QMap<QString,QString> metadata;
  metadata["labels"] = KUrl::toPercentEncoding( art->subject()->asUnicodeString() );
  list.populateMimeData( md, metadata );
  md->setData( "x-knode-drag/article" , QByteArray() );

  drag->setPixmap( knGlobals.configManager()->appearance()->icon( KNode::Appearance::posting ) );
  return drag;
#endif
}

int KNHdrViewItem::countUnreadInThread()
{
  int count = 0;
  if ( knGlobals.settings()->showUnread() ) {
    if (art->type() == KNArticle::ATremote) {
      count = static_cast<KNRemoteArticle*>( art )->unreadFollowUps();
    }
  }
  return count;
}

bool KNHdrViewItem::greyOut()
{
  if (art->type() == KNArticle::ATremote) {
    return !static_cast<KNRemoteArticle*>( art )->hasUnreadFollowUps()
        && static_cast<KNRemoteArticle*>( art )->isRead();
  } else
    return false;
}

bool KNHdrViewItem::firstColBold()
{
  if(art->type() == KNArticle::ATremote)
    return static_cast<KNRemoteArticle*>( art )->isNew();
  else
    return false;
}

QColor KNHdrViewItem::normalColor()
{
  if (art->type()==KNArticle::ATremote)
    return static_cast<KNRemoteArticle*>( art )->color();
  else
    return knGlobals.settings()->unreadThreadColor();
}

QColor KNHdrViewItem::greyColor()
{
  return knGlobals.settings()->readThreadColor();
}

<|endoftext|>