<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 "otbWrapperApplication.h"

#include "otbWrapperChoiceParameter.h"
#include "otbWrapperDirectoryParameter.h"
#include "otbWrapperEmptyParameter.h"
#include "otbWrapperFilenameParameter.h"
#include "otbWrapperInputComplexImageParameter.h"
#include "otbWrapperInputImageParameter.h"
#include "otbWrapperInputVectorDataParameter.h"
#include "otbWrapperNumericalParameter.h"
#include "otbWrapperOutputImageParameter.h"
#include "otbWrapperOutputVectorDataParameter.h"
#include "otbWrapperRadiusParameter.h"
#include "otbWrapperStringParameter.h"

#include "otbWrapperParameterGroup.h"

namespace otb
{
namespace Wrapper
{

Application::Application()
 : m_Name(""),
   m_Description("")
{
  // Don't call Init from the constructor, since it calls a virtual method !
}

Application::~Application()
{
}

ParameterGroup* Application::GetParameterList()
{
  if (!m_ParameterList)
    {
    Init();
    }

  return m_ParameterList;
}

Parameter* Application::GetParameterByKey(std::string name)
{
  return GetParameterList()->GetParameterByKey(name);
}

const Parameter* Application::GetParameterByKey(std::string name) const
{
  // GetParameterList is non const...
  Application* _this = const_cast<Application*>(this);
  return _this->GetParameterByKey(name);
}

void Application::Init()
{
  m_ParameterList = ParameterGroup::New();
  this->DoCreateParameters();
}

void Application::UpdateParameters()
{
  this->DoUpdateParameters();
}

void Application::Execute()
{
  this->DoExecute();
}

/* Enable the use of an optional parameter. Returns the previous state */
void Application::EnableParameter(std::string paramKey)
{
  Parameter* param = GetParameterByKey(paramKey);
  param->SetActive(true);
}

/* Disable the use of an optional parameter. Returns the previous state  */
void Application::DisableParameter(std::string paramKey)
{
  GetParameterByKey(paramKey)->SetActive(false);
}

/* Return the enable state of an optional parameter  */
bool Application::IsParameterEnabled(std::string paramKey) const
{
  return GetParameterByKey(paramKey)->GetActive();
}

/* Return true if the specified parameter is mandatory */
bool Application::IsMandatory(std::string paramKey) const
{
  return GetParameterByKey(paramKey)->GetMandatory();
}

/* Returns true if the parameter has an associated value provided externally
 *  (not automatically computed by the application) */
bool Application::HasUserValue(std::string paramKey) const
{
  return GetParameterByKey(paramKey)->HasUserValue();
}

/* If a user value was provided clear it and update the other parameters */
void Application::ClearValue(std::string paramKey)
{
  GetParameterByKey(paramKey)->ClearValue();
}

/* Returns true if the parameter has an associated value.
 * This value can be an automatically computed value or default value,
 * or a value set externally by user */
bool Application::HasValue(std::string paramKey) const
{
  return GetParameterByKey(paramKey)->HasValue();
}

/* Return the user level of access to a parameter */
UserLevel Application::GetParameterUserLevel(std::string paramKey) const
{
  return GetParameterByKey(paramKey)->GetUserLevel();
}

/* Get the parameter type from its name */
ParameterType Application::GetParameterType(std::string paramKey) const
{
  const Parameter* param = GetParameterByKey(paramKey);
  ParameterType type;

  if (dynamic_cast<const IntParameter*>(param))
    {
    type = ParameterType_Int;
    }
  else if (dynamic_cast<const FloatParameter*>(param))
    {
    type = ParameterType_Float;
    }
  else if (dynamic_cast<const RadiusParameter*>(param))
    {
    type = ParameterType_String;
    }
  else if (dynamic_cast<const FilenameParameter*>(param))
    {
    type = ParameterType_Filename;
    }
  else if (dynamic_cast<const DirectoryParameter*>(param))
    {
    type = ParameterType_Directory;
    }
  else if (dynamic_cast<const InputImageParameter*>(param))
    {
    type = ParameterType_InputImage;
    }
  else if (dynamic_cast<const InputComplexImageParameter*>(param))
    {
    type = ParameterType_InputComplexImage;
    }
  else if (dynamic_cast<const InputVectorDataParameter*>(param))
    {
    type = ParameterType_InputVectorData;
    }
  else if (dynamic_cast<const OutputImageParameter*>(param))
    {
    type = ParameterType_OutputImage;
    }
  else if (dynamic_cast<const OutputVectorDataParameter*>(param))
    {
    type = ParameterType_OutputVectorData;
    }
  else if (dynamic_cast<const RadiusParameter*>(param))
    {
    type = ParameterType_Radius;
    }
  else if (dynamic_cast<const ParameterGroup*>(param))
    {
    type = ParameterType_Group;
    }
  else
    {
    itkExceptionMacro(<< "Unknown parameter : " << paramKey);
    }

  return type;
}

void Application::SetParameterInt(std::string parameter, int value)
{
  Parameter* param = GetParameterByKey(parameter);

  if (dynamic_cast<IntParameter*>(param))
    {
    IntParameter* paramInt = dynamic_cast<IntParameter*>(param);
    paramInt->SetValue(value);
    }
  else if (dynamic_cast<FloatParameter*>(param))
    {
    FloatParameter* paramFloat = dynamic_cast<FloatParameter*>(param);
    paramFloat->SetValue(static_cast<float>(value));
    }
  else if (dynamic_cast<RadiusParameter*>(param))
    {
    RadiusParameter* paramRadius = dynamic_cast<RadiusParameter*>(param);
    paramRadius->SetValue(value);
    }
  else if (dynamic_cast<ChoiceParameter*>(param))
    {
    ChoiceParameter* paramChoice = dynamic_cast<ChoiceParameter*>(param);
    paramChoice->SetValue(value);
    }
}

void Application::SetParameterFloat(std::string parameter, float value)
{
  Parameter* param = GetParameterByKey(parameter);

  if (dynamic_cast<FloatParameter*>(param))
    {
    FloatParameter* paramFloat = dynamic_cast<FloatParameter*>(param);
    paramFloat->SetValue(value);
    }
}

void Application::SetParameterString(std::string parameter, std::string value)
{
  Parameter* param = GetParameterByKey(parameter);

  if (dynamic_cast<FilenameParameter*>(param))
    {
    FilenameParameter* paramDown = dynamic_cast<FilenameParameter*>(param);
    paramDown->SetValue(value);
    }
  else if (dynamic_cast<DirectoryParameter*>(param))
    {
    DirectoryParameter* paramDown = dynamic_cast<DirectoryParameter*>(param);
    paramDown->SetValue(value);
    }
  else if (dynamic_cast<InputImageParameter*>(param))
    {
    InputImageParameter* paramDown = dynamic_cast<InputImageParameter*>(param);
    paramDown->SetFromFileName(value);
    }
  else if (dynamic_cast<InputComplexImageParameter*>(param))
    {
    InputComplexImageParameter* paramDown = dynamic_cast<InputComplexImageParameter*>(param);
    paramDown->SetFromFileName(value);
    }
  else if (dynamic_cast<InputVectorDataParameter*>(param))
    {
    InputVectorDataParameter* paramDown = dynamic_cast<InputVectorDataParameter*>(param);
    paramDown->SetFromFileName(value);
    }
  else if (dynamic_cast<OutputImageParameter*>(param))
    {
    OutputImageParameter* paramDown = dynamic_cast<OutputImageParameter*>(param);
    paramDown->SetFileName(value);
    }
  else if (dynamic_cast<OutputVectorDataParameter*>(param))
    {
    OutputVectorDataParameter* paramDown = dynamic_cast<OutputVectorDataParameter*>(param);
    paramDown->SetFileName(value);
    }
  else if (dynamic_cast<StringParameter*>(param))
    {
    StringParameter* paramDown = dynamic_cast<StringParameter*>(param);
    paramDown->SetValue(value);
    }
}

void Application::SetParameterOutputImage(std::string parameter, OutputImageParameter::VectorImageType* value)
{
  Parameter* param = GetParameterByKey(parameter);

  if (dynamic_cast<OutputImageParameter*>(param))
    {
    OutputImageParameter* paramDown = dynamic_cast<OutputImageParameter*>(param);
    paramDown->SetValue(value);
    }
}

void Application::SetParameterOutputVectorData(std::string parameter, OutputVectorDataParameter::VectorDataType* value)
{
  Parameter* param = GetParameterByKey(parameter);

  if (dynamic_cast<OutputVectorDataParameter*>(param))
    {
    OutputVectorDataParameter* paramDown = dynamic_cast<OutputVectorDataParameter*>(param);
    paramDown->SetValue(value);
    }
}

int Application::GetParameterInt(std::string parameter)
{
  int ret = 0;
  Parameter* param = GetParameterByKey(parameter);

  if (dynamic_cast<IntParameter*>(param))
    {
    IntParameter* paramInt = dynamic_cast<IntParameter*>(param);
    ret = paramInt->GetValue();
    }
  else if (dynamic_cast<FloatParameter*>(param))
    {
    FloatParameter* paramFloat = dynamic_cast<FloatParameter*>(param);
    ret = static_cast<int>(paramFloat->GetValue());
    }
  else if (dynamic_cast<RadiusParameter*>(param))
    {
    RadiusParameter* paramRadius = dynamic_cast<RadiusParameter*>(param);
    ret = paramRadius->GetValue();
    }
  else if (dynamic_cast<ChoiceParameter*>(param))
    {
    ChoiceParameter* paramChoice = dynamic_cast<ChoiceParameter*>(param);
    ret = paramChoice->GetValue();
    }

  //TODO: exception if not found ?
  return ret;
}

float Application::GetParameterFloat(std::string parameter)
{
  float ret = 0;
  Parameter* param = GetParameterByKey(parameter);

  if (dynamic_cast<FloatParameter*>(param))
    {
    FloatParameter* paramFloat = dynamic_cast<FloatParameter*>(param);
    ret = paramFloat->GetValue();
    }

  //TODO: exception if not found ?
  return ret;
}

std::string Application::GetParameterString(std::string parameter)
{
  std::string ret;
  Parameter* param = GetParameterByKey(parameter);

  if (dynamic_cast<FilenameParameter*>(param))
    {
    FilenameParameter* paramDown = dynamic_cast<FilenameParameter*>(param);
    ret = paramDown->GetValue();
    }
  else if (dynamic_cast<DirectoryParameter*>(param))
    {
    DirectoryParameter* paramDown = dynamic_cast<DirectoryParameter*>(param);
    ret = paramDown->GetValue();
    }
  else if (dynamic_cast<InputImageParameter*>(param))
    {
    InputImageParameter* paramDown = dynamic_cast<InputImageParameter*>(param);
    ret = paramDown->GetFileName();
    }
  else if (dynamic_cast<InputComplexImageParameter*>(param))
    {
    InputComplexImageParameter* paramDown = dynamic_cast<InputComplexImageParameter*>(param);
    ret = paramDown->GetFileName();
    }
  else if (dynamic_cast<InputVectorDataParameter*>(param))
    {
    InputVectorDataParameter* paramDown = dynamic_cast<InputVectorDataParameter*>(param);
    ret = paramDown->GetFileName();
    }
  else if (dynamic_cast<OutputImageParameter*>(param))
    {
    OutputImageParameter* paramDown = dynamic_cast<OutputImageParameter*>(param);
    ret = paramDown->GetFileName();
    }
  else if (dynamic_cast<OutputVectorDataParameter*>(param))
    {
    OutputVectorDataParameter* paramDown = dynamic_cast<OutputVectorDataParameter*>(param);
    ret = paramDown->GetFileName();
    }

  //TODO: exception if not found ?
  return ret;
}

VectorImageType* Application::GetParameterImage(std::string parameter)
{
  VectorImageType::Pointer ret;
  Parameter* param = GetParameterByKey(parameter);

  if (dynamic_cast<InputImageParameter*>(param))
    {
    InputImageParameter* paramDown = dynamic_cast<InputImageParameter*>(param);
    ret = paramDown->GetImage();
    }

  //TODO: exception if not found ?
  return ret;
}

VectorImageType* Application::GetParameterComplexImage(std::string parameter)
{
  VectorImageType::Pointer ret;
  Parameter* param = GetParameterByKey(parameter);

  if (dynamic_cast<InputComplexImageParameter*>(param))
    {
    InputComplexImageParameter* paramDown = dynamic_cast<InputComplexImageParameter*>(param);
    ret = paramDown->GetImage();
    }

  //TODO: exception if not found ?
  return ret;

}

VectorDataType* Application::GetParameterVectorData(std::string parameter)
{
  VectorDataType::Pointer ret;
  Parameter* param = GetParameterByKey(parameter);

  if (dynamic_cast<InputVectorDataParameter*>(param))
    {
    InputVectorDataParameter* paramDown = dynamic_cast<InputVectorDataParameter*>(param);
    ret = paramDown->GetVectorData();
    }

  //TODO: exception if not found ?
  return ret;
}

void
Application::AddChoice(std::string paramKey, std::string paramName)
{
  GetParameterList()->AddChoice(paramKey, paramName);
}

void
Application::AddParameter(ParameterType type, std::string paramKey, std::string paramName)
{
  GetParameterList()->AddParameter(type, paramKey, paramName);
}

}
}

<commit_msg>ENH: add support for Choice in SetParameterString<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 "otbWrapperApplication.h"

#include "otbWrapperChoiceParameter.h"
#include "otbWrapperDirectoryParameter.h"
#include "otbWrapperEmptyParameter.h"
#include "otbWrapperFilenameParameter.h"
#include "otbWrapperInputComplexImageParameter.h"
#include "otbWrapperInputImageParameter.h"
#include "otbWrapperInputVectorDataParameter.h"
#include "otbWrapperNumericalParameter.h"
#include "otbWrapperOutputImageParameter.h"
#include "otbWrapperOutputVectorDataParameter.h"
#include "otbWrapperRadiusParameter.h"
#include "otbWrapperStringParameter.h"

#include "otbWrapperParameterGroup.h"

namespace otb
{
namespace Wrapper
{

Application::Application()
 : m_Name(""),
   m_Description("")
{
  // Don't call Init from the constructor, since it calls a virtual method !
}

Application::~Application()
{
}

ParameterGroup* Application::GetParameterList()
{
  if (!m_ParameterList)
    {
    Init();
    }

  return m_ParameterList;
}

Parameter* Application::GetParameterByKey(std::string name)
{
  return GetParameterList()->GetParameterByKey(name);
}

const Parameter* Application::GetParameterByKey(std::string name) const
{
  // GetParameterList is non const...
  Application* _this = const_cast<Application*>(this);
  return _this->GetParameterByKey(name);
}

void Application::Init()
{
  m_ParameterList = ParameterGroup::New();
  this->DoCreateParameters();
}

void Application::UpdateParameters()
{
  this->DoUpdateParameters();
}

void Application::Execute()
{
  this->DoExecute();
}

void Application::ExecuteAndWriteOutput()
{
  this->Execute();

}

/* Enable the use of an optional parameter. Returns the previous state */
void Application::EnableParameter(std::string paramKey)
{
  Parameter* param = GetParameterByKey(paramKey);
  param->SetActive(true);
}

/* Disable the use of an optional parameter. Returns the previous state  */
void Application::DisableParameter(std::string paramKey)
{
  GetParameterByKey(paramKey)->SetActive(false);
}

/* Return the enable state of an optional parameter  */
bool Application::IsParameterEnabled(std::string paramKey) const
{
  return GetParameterByKey(paramKey)->GetActive();
}

/* Return true if the specified parameter is mandatory */
bool Application::IsMandatory(std::string paramKey) const
{
  return GetParameterByKey(paramKey)->GetMandatory();
}

/* Returns true if the parameter has an associated value provided externally
 *  (not automatically computed by the application) */
bool Application::HasUserValue(std::string paramKey) const
{
  return GetParameterByKey(paramKey)->HasUserValue();
}

/* If a user value was provided clear it and update the other parameters */
void Application::ClearValue(std::string paramKey)
{
  GetParameterByKey(paramKey)->ClearValue();
}

/* Returns true if the parameter has an associated value.
 * This value can be an automatically computed value or default value,
 * or a value set externally by user */
bool Application::HasValue(std::string paramKey) const
{
  return GetParameterByKey(paramKey)->HasValue();
}

/* Return the user level of access to a parameter */
UserLevel Application::GetParameterUserLevel(std::string paramKey) const
{
  return GetParameterByKey(paramKey)->GetUserLevel();
}

/* Get the parameter type from its name */
ParameterType Application::GetParameterType(std::string paramKey) const
{
  const Parameter* param = GetParameterByKey(paramKey);
  ParameterType type;

  if (dynamic_cast<const IntParameter*>(param))
    {
    type = ParameterType_Int;
    }
  else if (dynamic_cast<const FloatParameter*>(param))
    {
    type = ParameterType_Float;
    }
  else if (dynamic_cast<const RadiusParameter*>(param))
    {
    type = ParameterType_String;
    }
  else if (dynamic_cast<const FilenameParameter*>(param))
    {
    type = ParameterType_Filename;
    }
  else if (dynamic_cast<const DirectoryParameter*>(param))
    {
    type = ParameterType_Directory;
    }
  else if (dynamic_cast<const InputImageParameter*>(param))
    {
    type = ParameterType_InputImage;
    }
  else if (dynamic_cast<const InputComplexImageParameter*>(param))
    {
    type = ParameterType_InputComplexImage;
    }
  else if (dynamic_cast<const InputVectorDataParameter*>(param))
    {
    type = ParameterType_InputVectorData;
    }
  else if (dynamic_cast<const OutputImageParameter*>(param))
    {
    type = ParameterType_OutputImage;
    }
  else if (dynamic_cast<const OutputVectorDataParameter*>(param))
    {
    type = ParameterType_OutputVectorData;
    }
  else if (dynamic_cast<const RadiusParameter*>(param))
    {
    type = ParameterType_Radius;
    }
  else if (dynamic_cast<const ParameterGroup*>(param))
    {
    type = ParameterType_Group;
    }
  else
    {
    itkExceptionMacro(<< "Unknown parameter : " << paramKey);
    }

  return type;
}

void Application::SetParameterInt(std::string parameter, int value)
{
  Parameter* param = GetParameterByKey(parameter);

  if (dynamic_cast<IntParameter*>(param))
    {
    IntParameter* paramInt = dynamic_cast<IntParameter*>(param);
    paramInt->SetValue(value);
    }
  else if (dynamic_cast<FloatParameter*>(param))
    {
    FloatParameter* paramFloat = dynamic_cast<FloatParameter*>(param);
    paramFloat->SetValue(static_cast<float>(value));
    }
  else if (dynamic_cast<RadiusParameter*>(param))
    {
    RadiusParameter* paramRadius = dynamic_cast<RadiusParameter*>(param);
    paramRadius->SetValue(value);
    }
  else if (dynamic_cast<ChoiceParameter*>(param))
    {
    ChoiceParameter* paramChoice = dynamic_cast<ChoiceParameter*>(param);
    paramChoice->SetValue(value);
    }
}

void Application::SetParameterFloat(std::string parameter, float value)
{
  Parameter* param = GetParameterByKey(parameter);

  if (dynamic_cast<FloatParameter*>(param))
    {
    FloatParameter* paramFloat = dynamic_cast<FloatParameter*>(param);
    paramFloat->SetValue(value);
    }
}

void Application::SetParameterString(std::string parameter, std::string value)
{
  Parameter* param = GetParameterByKey(parameter);

  if (dynamic_cast<ChoiceParameter*>(param))
    {
    ChoiceParameter* paramDown = dynamic_cast<ChoiceParameter*>(param);
    paramDown->SetValue(value);
    }
  else if (dynamic_cast<StringParameter*>(param))
    {
    StringParameter* paramDown = dynamic_cast<StringParameter*>(param);
    paramDown->SetValue(value);
    }
  else if (dynamic_cast<FilenameParameter*>(param))
    {
    FilenameParameter* paramDown = dynamic_cast<FilenameParameter*>(param);
    paramDown->SetValue(value);
    }
  else if (dynamic_cast<DirectoryParameter*>(param))
    {
    DirectoryParameter* paramDown = dynamic_cast<DirectoryParameter*>(param);
    paramDown->SetValue(value);
    }
  else if (dynamic_cast<InputImageParameter*>(param))
    {
    InputImageParameter* paramDown = dynamic_cast<InputImageParameter*>(param);
    paramDown->SetFromFileName(value);
    }
  else if (dynamic_cast<InputComplexImageParameter*>(param))
    {
    InputComplexImageParameter* paramDown = dynamic_cast<InputComplexImageParameter*>(param);
    paramDown->SetFromFileName(value);
    }
  else if (dynamic_cast<InputVectorDataParameter*>(param))
    {
    InputVectorDataParameter* paramDown = dynamic_cast<InputVectorDataParameter*>(param);
    paramDown->SetFromFileName(value);
    }
  else if (dynamic_cast<OutputImageParameter*>(param))
    {
    OutputImageParameter* paramDown = dynamic_cast<OutputImageParameter*>(param);
    paramDown->SetFileName(value);
    }
  else if (dynamic_cast<OutputVectorDataParameter*>(param))
    {
    OutputVectorDataParameter* paramDown = dynamic_cast<OutputVectorDataParameter*>(param);
    paramDown->SetFileName(value);
    }
}

void Application::SetParameterOutputImage(std::string parameter, OutputImageParameter::VectorImageType* value)
{
  Parameter* param = GetParameterByKey(parameter);

  if (dynamic_cast<OutputImageParameter*>(param))
    {
    OutputImageParameter* paramDown = dynamic_cast<OutputImageParameter*>(param);
    paramDown->SetValue(value);
    }
}

void Application::SetParameterOutputVectorData(std::string parameter, OutputVectorDataParameter::VectorDataType* value)
{
  Parameter* param = GetParameterByKey(parameter);

  if (dynamic_cast<OutputVectorDataParameter*>(param))
    {
    OutputVectorDataParameter* paramDown = dynamic_cast<OutputVectorDataParameter*>(param);
    paramDown->SetValue(value);
    }
}

int Application::GetParameterInt(std::string parameter)
{
  int ret = 0;
  Parameter* param = GetParameterByKey(parameter);

  if (dynamic_cast<IntParameter*>(param))
    {
    IntParameter* paramInt = dynamic_cast<IntParameter*>(param);
    ret = paramInt->GetValue();
    }
  else if (dynamic_cast<FloatParameter*>(param))
    {
    FloatParameter* paramFloat = dynamic_cast<FloatParameter*>(param);
    ret = static_cast<int>(paramFloat->GetValue());
    }
  else if (dynamic_cast<RadiusParameter*>(param))
    {
    RadiusParameter* paramRadius = dynamic_cast<RadiusParameter*>(param);
    ret = paramRadius->GetValue();
    }
  else if (dynamic_cast<ChoiceParameter*>(param))
    {
    ChoiceParameter* paramChoice = dynamic_cast<ChoiceParameter*>(param);
    ret = paramChoice->GetValue();
    }

  //TODO: exception if not found ?
  return ret;
}

float Application::GetParameterFloat(std::string parameter)
{
  float ret = 0;
  Parameter* param = GetParameterByKey(parameter);

  if (dynamic_cast<FloatParameter*>(param))
    {
    FloatParameter* paramFloat = dynamic_cast<FloatParameter*>(param);
    ret = paramFloat->GetValue();
    }

  //TODO: exception if not found ?
  return ret;
}

std::string Application::GetParameterString(std::string parameter)
{
  std::string ret;
  Parameter* param = GetParameterByKey(parameter);

  if (dynamic_cast<FilenameParameter*>(param))
    {
    FilenameParameter* paramDown = dynamic_cast<FilenameParameter*>(param);
    ret = paramDown->GetValue();
    }
  else if (dynamic_cast<DirectoryParameter*>(param))
    {
    DirectoryParameter* paramDown = dynamic_cast<DirectoryParameter*>(param);
    ret = paramDown->GetValue();
    }
  else if (dynamic_cast<InputImageParameter*>(param))
    {
    InputImageParameter* paramDown = dynamic_cast<InputImageParameter*>(param);
    ret = paramDown->GetFileName();
    }
  else if (dynamic_cast<InputComplexImageParameter*>(param))
    {
    InputComplexImageParameter* paramDown = dynamic_cast<InputComplexImageParameter*>(param);
    ret = paramDown->GetFileName();
    }
  else if (dynamic_cast<InputVectorDataParameter*>(param))
    {
    InputVectorDataParameter* paramDown = dynamic_cast<InputVectorDataParameter*>(param);
    ret = paramDown->GetFileName();
    }
  else if (dynamic_cast<OutputImageParameter*>(param))
    {
    OutputImageParameter* paramDown = dynamic_cast<OutputImageParameter*>(param);
    ret = paramDown->GetFileName();
    }
  else if (dynamic_cast<OutputVectorDataParameter*>(param))
    {
    OutputVectorDataParameter* paramDown = dynamic_cast<OutputVectorDataParameter*>(param);
    ret = paramDown->GetFileName();
    }

  //TODO: exception if not found ?
  return ret;
}

VectorImageType* Application::GetParameterImage(std::string parameter)
{
  VectorImageType::Pointer ret;
  Parameter* param = GetParameterByKey(parameter);

  if (dynamic_cast<InputImageParameter*>(param))
    {
    InputImageParameter* paramDown = dynamic_cast<InputImageParameter*>(param);
    ret = paramDown->GetImage();
    }

  //TODO: exception if not found ?
  return ret;
}

VectorImageType* Application::GetParameterComplexImage(std::string parameter)
{
  VectorImageType::Pointer ret;
  Parameter* param = GetParameterByKey(parameter);

  if (dynamic_cast<InputComplexImageParameter*>(param))
    {
    InputComplexImageParameter* paramDown = dynamic_cast<InputComplexImageParameter*>(param);
    ret = paramDown->GetImage();
    }

  //TODO: exception if not found ?
  return ret;

}

VectorDataType* Application::GetParameterVectorData(std::string parameter)
{
  VectorDataType::Pointer ret;
  Parameter* param = GetParameterByKey(parameter);

  if (dynamic_cast<InputVectorDataParameter*>(param))
    {
    InputVectorDataParameter* paramDown = dynamic_cast<InputVectorDataParameter*>(param);
    ret = paramDown->GetVectorData();
    }

  //TODO: exception if not found ?
  return ret;
}

void
Application::AddChoice(std::string paramKey, std::string paramName)
{
  GetParameterList()->AddChoice(paramKey, paramName);
}

void
Application::AddParameter(ParameterType type, std::string paramKey, std::string paramName)
{
  GetParameterList()->AddParameter(type, paramKey, paramName);
}

}
}

<|endoftext|>


<commit_before>/**
 * Copyright (c) 2013 MasterWallet developers (see AUTHORS)
 *
 * This file is part of MasterWallet <https://github.com/duzy/masterwallet>.
 *
 * libwallet is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License as
 * published by the Free Software Foundation, either version 3 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 Affero General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with this program. If not, see <http://www.gnu.org/licenses/>.
 */
#include "logging.h"

namespace mastercoin {

    static void log(std::ostream &out, bitcoin::log_level level, const std::string& domain, const std::string& body)
    {
	out << level_repr(level);
	if (!domain.empty()) out << " [" << domain << "]";
	out << ": " << body << std::endl;
    }

    logger::logger(std::ostream & debug, std::ostream & error)
	: debug_(debug), error_(error)
    {
    }

    logger::~logger()
    {
    }

    void logger::setup(std::ostream & outdebug, std::ostream & outerror)
    {
	logger log(outdebug, outerror);
	bitcoin::log_info()   .set_output_function(log);
	bitcoin::log_debug()  .set_output_function(log);
	bitcoin::log_warning().set_output_function(log);
	bitcoin::log_error()  .set_output_function(log);
	bitcoin::log_fatal()  .set_output_function(log);
    }

    void logger::operator()(bitcoin::log_level level, const std::string& domain, const std::string& body)
    {
	if (body.empty()) return;
	switch (level) {
	case bitcoin::log_level::debug:	  this->debug  (level, domain, body);
	case bitcoin::log_level::info:    this->info   (level, domain, body);
	case bitcoin::log_level::warning: this->warning(level, domain, body);
	case bitcoin::log_level::error:	  this->error  (level, domain, body);
	case bitcoin::log_level::fatal:	  this->fatal  (level, domain, body);
	}
    }

    void logger::info(bitcoin::log_level level, const std::string& domain, const std::string& body)
    {
	log(debug_, level, domain, body);
    }

    void logger::debug(bitcoin::log_level level, const std::string& domain, const std::string& body)
    {
	log(debug_, level, domain, body);
    }

    void logger::warning(bitcoin::log_level level, const std::string& domain, const std::string& body)
    {
	log(error_, level, domain, body);
    }

    void logger::error(bitcoin::log_level level, const std::string& domain, const std::string& body)
    {
	log(error_, level, domain, body);
    }

    void logger::fatal(bitcoin::log_level level, const std::string& domain, const std::string& body)
    {
	log(error_, level, domain, body);
    }

}//namespace mastercoin
<commit_msg>fix mess logging<commit_after>/**
 * Copyright (c) 2013 MasterWallet developers (see AUTHORS)
 *
 * This file is part of MasterWallet <https://github.com/duzy/masterwallet>.
 *
 * libwallet is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License as
 * published by the Free Software Foundation, either version 3 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 Affero General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with this program. If not, see <http://www.gnu.org/licenses/>.
 */
#include "logging.h"

namespace mastercoin {

    static void log(std::ostream &out, bitcoin::log_level level, const std::string& domain, const std::string& body)
    {
	out << level_repr(level);
	if (!domain.empty()) out << " [" << domain << "]";
	out << ": " << body << std::endl;
    }

    logger::logger(std::ostream & debug, std::ostream & error)
	: debug_(debug), error_(error)
    {
    }

    logger::~logger()
    {
    }

    void logger::setup(std::ostream & outdebug, std::ostream & outerror)
    {
	logger log(outdebug, outerror);
	bitcoin::log_info()   .set_output_function(log);
	bitcoin::log_debug()  .set_output_function(log);
	bitcoin::log_warning().set_output_function(log);
	bitcoin::log_error()  .set_output_function(log);
	bitcoin::log_fatal()  .set_output_function(log);
    }

    void logger::operator()(bitcoin::log_level level, const std::string& domain, const std::string& body)
    {
	if (body.empty()) return;
	switch (level) {
	case bitcoin::log_level::debug:	  this->debug  (level, domain, body); break;
	case bitcoin::log_level::info:    this->info   (level, domain, body); break;
	case bitcoin::log_level::warning: this->warning(level, domain, body); break;
	case bitcoin::log_level::error:	  this->error  (level, domain, body); break;
	case bitcoin::log_level::fatal:	  this->fatal  (level, domain, body); break;
	}
    }

    void logger::info(bitcoin::log_level level, const std::string& domain, const std::string& body)
    {
	log(debug_, level, domain, body);
    }

    void logger::debug(bitcoin::log_level level, const std::string& domain, const std::string& body)
    {
	log(debug_, level, domain, body);
    }

    void logger::warning(bitcoin::log_level level, const std::string& domain, const std::string& body)
    {
	log(error_, level, domain, body);
    }

    void logger::error(bitcoin::log_level level, const std::string& domain, const std::string& body)
    {
	log(error_, level, domain, body);
    }

    void logger::fatal(bitcoin::log_level level, const std::string& domain, const std::string& body)
    {
	log(error_, level, domain, body);
    }

}//namespace mastercoin
<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  $RCSfile: fmtcntnt.hxx,v $
 *
 *  $Revision: 1.5 $
 *
 *  last change: $Author: rt $ $Date: 2005-01-05 15:49:27 $
 *
 *  The Contents of this file are made available subject to the terms of
 *  either of the following licenses
 *
 *         - GNU Lesser General Public License Version 2.1
 *         - Sun Industry Standards Source License Version 1.1
 *
 *  Sun Microsystems Inc., October, 2000
 *
 *  GNU Lesser General Public License Version 2.1
 *  =============================================
 *  Copyright 2000 by Sun Microsystems, Inc.
 *  901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *  This library is free software; you can redistribute it and/or
 *  modify it under the terms of the GNU Lesser General Public
 *  License version 2.1, as published by the Free Software Foundation.
 *
 *  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
 *
 *
 *  Sun Industry Standards Source License Version 1.1
 *  =================================================
 *  The contents of this file are subject to the Sun Industry Standards
 *  Source License Version 1.1 (the "License"); You may not use this file
 *  except in compliance with the License. You may obtain a copy of the
 *  License at http://www.openoffice.org/license.html.
 *
 *  Software provided under this License is provided on an "AS IS" basis,
 *  WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
 *  WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
 *  MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
 *  See the License for the specific provisions governing your rights and
 *  obligations concerning the Software.
 *
 *  The Initial Developer of the Original Code is: Sun Microsystems, Inc.
 *
 *  Copyright: 2000 by Sun Microsystems, Inc.
 *
 *  All Rights Reserved.
 *
 *  Contributor(s): _______________________________________
 *
 *
 ************************************************************************/
#ifndef _FMTCNTNT_HXX
#define _FMTCNTNT_HXX

#ifndef _SFXPOOLITEM_HXX //autogen
#include <svtools/poolitem.hxx>
#endif
#ifndef _HINTIDS_HXX
#include <hintids.hxx>
#endif
#ifndef _FORMAT_HXX //autogen
#include <format.hxx>
#endif

class SwNodeIndex;
class SwStartNode;

//Cntnt, Inhalt des Frame (Header, Footer, Fly) ----

class SwFmtCntnt: public SfxPoolItem
{
    SwNodeIndex *pStartNode;

    SwFmtCntnt &operator=( const SwFmtCntnt & ); //Kopieren verboten

public:
//  SwFmtCntnt( const SwNodeIndex *pStartNodeIdx = 0 );
    SwFmtCntnt( const SwStartNode* pStartNode = 0 );
    SwFmtCntnt( const SwFmtCntnt &rCpy );
    ~SwFmtCntnt();

    // "pure virtual Methoden" vom SfxPoolItem
    virtual int             operator==( const SfxPoolItem& ) const;
    virtual SfxPoolItem*    Clone( SfxItemPool* pPool = 0 ) const;

    const SwNodeIndex *GetCntntIdx() const { return pStartNode; }
    void SetNewCntntIdx( const SwNodeIndex *pIdx );
};

inline const SwFmtCntnt &SwAttrSet::GetCntnt(BOOL bInP) const
    { return (const SwFmtCntnt&)Get( RES_CNTNT,bInP); }

inline const SwFmtCntnt &SwFmt::GetCntnt(BOOL bInP) const
    { return aSet.GetCntnt(bInP); }

#endif

<commit_msg>INTEGRATION: CWS ooo19126 (1.5.406); FILE MERGED 2005/09/05 13:36:02 rt 1.5.406.1: #i54170# Change license header: remove SISSL<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: fmtcntnt.hxx,v $
 *
 *  $Revision: 1.6 $
 *
 *  last change: $Author: rt $ $Date: 2005-09-09 01:48:28 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 by Sun Microsystems, Inc.
 *    901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License version 2.1, as published by the Free Software Foundation.
 *
 *    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
 *
 ************************************************************************/
#ifndef _FMTCNTNT_HXX
#define _FMTCNTNT_HXX

#ifndef _SFXPOOLITEM_HXX //autogen
#include <svtools/poolitem.hxx>
#endif
#ifndef _HINTIDS_HXX
#include <hintids.hxx>
#endif
#ifndef _FORMAT_HXX //autogen
#include <format.hxx>
#endif

class SwNodeIndex;
class SwStartNode;

//Cntnt, Inhalt des Frame (Header, Footer, Fly) ----

class SwFmtCntnt: public SfxPoolItem
{
    SwNodeIndex *pStartNode;

    SwFmtCntnt &operator=( const SwFmtCntnt & ); //Kopieren verboten

public:
//  SwFmtCntnt( const SwNodeIndex *pStartNodeIdx = 0 );
    SwFmtCntnt( const SwStartNode* pStartNode = 0 );
    SwFmtCntnt( const SwFmtCntnt &rCpy );
    ~SwFmtCntnt();

    // "pure virtual Methoden" vom SfxPoolItem
    virtual int             operator==( const SfxPoolItem& ) const;
    virtual SfxPoolItem*    Clone( SfxItemPool* pPool = 0 ) const;

    const SwNodeIndex *GetCntntIdx() const { return pStartNode; }
    void SetNewCntntIdx( const SwNodeIndex *pIdx );
};

inline const SwFmtCntnt &SwAttrSet::GetCntnt(BOOL bInP) const
    { return (const SwFmtCntnt&)Get( RES_CNTNT,bInP); }

inline const SwFmtCntnt &SwFmt::GetCntnt(BOOL bInP) const
    { return aSet.GetCntnt(bInP); }

#endif

<|endoftext|>


<commit_before>//
// Copyright 2020 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//      http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//

#include "src/linter.h"

#include <cstdio>
#include <fstream>
#include <sstream>
#include <string>

#include "absl/strings/match.h"
#include "gtest/gtest.h"
#include "src/linter_options.h"

namespace zetasql::linter {

namespace {

TEST(LinterTest, StatementLineLengthCheck) {
  absl::string_view sql =
      "SELECT e, sum(f) FROM emp where b = a or c < d group by x";
  absl::string_view multiline_sql =
      "SELECT c\n"
      "some long invalid sql statement that shouldn't stop check\n"
      "SELECT t from G\n";
  LinterOptions option;
  EXPECT_TRUE(CheckLineLength(sql, option).ok());
  option.SetLineLimit(10);
  EXPECT_FALSE(CheckLineLength(sql, option).ok());
  option.SetLineDelimeter(' ');
  EXPECT_TRUE(CheckLineLength(sql, option).ok());

  option.SetLineLimit(100);
  option.SetLineDelimeter('\n');
  EXPECT_TRUE(CheckLineLength(multiline_sql, option).ok());

  option.SetLineLimit(30);
  EXPECT_FALSE(CheckLineLength(multiline_sql, option).ok());
}

TEST(LinterTest, StatementValidityCheck) {
  LinterOptions option;
  EXPECT_TRUE(CheckParserSucceeds("SELECT 5+2", option).ok());
  EXPECT_FALSE(CheckParserSucceeds("SELECT 5+2 sss ddd", option).ok());

  EXPECT_TRUE(CheckParserSucceeds(
                  "SELECT * FROM emp where b = a or c < d group by x", option)
                  .ok());

  EXPECT_TRUE(
      CheckParserSucceeds(
          "SELECT e, sum(f) FROM emp where b = a or c < d group by x", option)
          .ok());

  EXPECT_FALSE(
      CheckParserSucceeds("SELET A FROM B\nSELECT C FROM D", option).ok());

  EXPECT_FALSE(CheckParserSucceeds("SELECT 1; SELECT 2 3 4;", option).ok());
}

TEST(LinterTest, SemicolonCheck) {
  LinterOptions option;
  EXPECT_TRUE(CheckSemicolon("SELECT 3+5;\nSELECT 4+6;", option).ok());
  EXPECT_TRUE(CheckSemicolon("SELECT 3+5;   \n   SELECT 4+6;", option).ok());
  EXPECT_FALSE(CheckSemicolon("SELECT 3+5\nSELECT 4+6;", option).ok());
  EXPECT_FALSE(CheckSemicolon("SELECT 3+5;  \nSELECT 4+6", option).ok());
  EXPECT_FALSE(CheckSemicolon("SELECT 3+5  ;  \nSELECT 4+6", option).ok());
}

TEST(LinterTest, UppercaseKeywordCheck) {
  LinterOptions option;
  EXPECT_TRUE(CheckUppercaseKeywords(
                  "SELECT * FROM emp WHERE b = a OR c < d GROUP BY x", option)
                  .ok());
  EXPECT_TRUE(CheckUppercaseKeywords(
                  "SELECT * FROM emp where b = a or c < d GROUP by x", option)
                  .ok());
  EXPECT_FALSE(CheckUppercaseKeywords(
                   "SeLEct * frOM emp wHEre b = a or c < d GROUP by x", option)
                   .ok());
}

TEST(LinterTest, CommentTypeCheck) {
  LinterOptions option;
  EXPECT_FALSE(
      CheckCommentType("# Comment 1\n-- Comment 2\nSELECT 3+5\n", option).ok());
  EXPECT_TRUE(
      CheckCommentType("-- Comment /* unfinished comment", option).ok());

  EXPECT_TRUE(
      CheckCommentType("//comment 1\nSELECT 3+5\n//comment 2", option).ok());
  EXPECT_FALSE(
      CheckCommentType("//comment 1\nSELECT 3+5\n--comment 2", option).ok());
  EXPECT_TRUE(
      CheckCommentType("--comment 1\nSELECT 3+5\n--comment 2", option).ok());

  // Check a sql containing a multiline comment.
  EXPECT_TRUE(
      CheckCommentType("/* here is // and -- */SELECT 1+2 -- comment 2", option)
          .ok());

  // Check multiline string literal
  EXPECT_TRUE(
      CheckCommentType(
          "SELECT \"\"\"multiline\nstring--\nliteral\nhaving//--//\"\"\"",
          option)
          .ok());
}

TEST(LinterTest, AliasKeywordCheck) {
  LinterOptions option;
  EXPECT_FALSE(CheckAliasKeyword("SELECT 1 a", option).ok());
  EXPECT_TRUE(CheckAliasKeyword("SELECT * FROM emp AS X", option).ok());
  EXPECT_FALSE(CheckAliasKeyword("SELECT * FROM emp X", option).ok());
  EXPECT_TRUE(CheckAliasKeyword("SELECT 1 AS one", option).ok());
}

TEST(LinterTest, TabCharactersUniformCheck) {
  LinterOptions option_space;
  EXPECT_TRUE(
      CheckTabCharactersUniform("  SELECT 5;\n    SELECT 6;", option_space)
          .ok());
  LinterOptions option_tab;
  option_tab.SetAllowedIndent('\t');
  EXPECT_TRUE(
      CheckTabCharactersUniform("\tSELECT 5;\n\t\tSELECT 6;", option_tab)
          .ok());
  EXPECT_TRUE(
      CheckTabCharactersUniform("SELECT 5;\n SELECT\t6;\t", option_space).ok());

  EXPECT_TRUE(
      CheckTabCharactersUniform("SELECT 5;\n \t SELECT 6;", option_space)
          .GetErrors()
          .back()
          .GetPosition() == std::make_pair(2, 2));
  EXPECT_TRUE(
      CheckTabCharactersUniform("  SELECT kek;\n\tSELECT lol;", option_space)
          .GetErrors()
          .back()
          .GetPosition() == std::make_pair(2, 1));
  EXPECT_TRUE(CheckTabCharactersUniform("SELECT 5;\n  SELECT 6;", option_tab)
                  .GetErrors()
                  .back()
                  .GetPosition() == std::make_pair(2, 1));
}

TEST(LinterTest, NoTabsBesidesIndentationsCheck) {
  LinterOptions option;
  EXPECT_TRUE(
      CheckNoTabsBesidesIndentations("\tSELECT 5;\n\tSELECT 6;", option).ok());
  EXPECT_TRUE(
      CheckNoTabsBesidesIndentations("\tSELECT   5;\n\t\tSELECT   6;", option)
          .ok());

  EXPECT_TRUE(
      CheckNoTabsBesidesIndentations("\tSELECT \t5;\n\t\tSELECT   6;", option)
          .GetErrors()
          .back()
          .GetPosition() == std::make_pair(1, 16));
  EXPECT_TRUE(CheckNoTabsBesidesIndentations("\tSELECT 5;\nS\tELECT 6;", option)
                  .GetErrors()
                  .back()
                  .GetPosition() == std::make_pair(2, 2));
}

}  // namespace
}  // namespace zetasql::linter
<commit_msg>fixes<commit_after>//
// Copyright 2020 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//      http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//

#include "src/linter.h"

#include <cstdio>
#include <fstream>
#include <sstream>
#include <string>

#include "absl/strings/match.h"
#include "gtest/gtest.h"
#include "src/linter_options.h"

namespace zetasql::linter {

namespace {

TEST(LinterTest, StatementLineLengthCheck) {
  absl::string_view sql =
      "SELECT e, sum(f) FROM emp where b = a or c < d group by x";
  absl::string_view multiline_sql =
      "SELECT c\n"
      "some long invalid sql statement that shouldn't stop check\n"
      "SELECT t from G\n";
  LinterOptions option;
  EXPECT_TRUE(CheckLineLength(sql, option).ok());
  option.SetLineLimit(10);
  EXPECT_FALSE(CheckLineLength(sql, option).ok());
  option.SetLineDelimeter(' ');
  EXPECT_TRUE(CheckLineLength(sql, option).ok());

  option.SetLineLimit(100);
  option.SetLineDelimeter('\n');
  EXPECT_TRUE(CheckLineLength(multiline_sql, option).ok());

  option.SetLineLimit(30);
  EXPECT_FALSE(CheckLineLength(multiline_sql, option).ok());
}

TEST(LinterTest, StatementValidityCheck) {
  LinterOptions option;
  EXPECT_TRUE(CheckParserSucceeds("SELECT 5+2", option).ok());
  EXPECT_FALSE(CheckParserSucceeds("SELECT 5+2 sss ddd", option).ok());

  EXPECT_TRUE(CheckParserSucceeds(
                  "SELECT * FROM emp where b = a or c < d group by x", option)
                  .ok());

  EXPECT_TRUE(
      CheckParserSucceeds(
          "SELECT e, sum(f) FROM emp where b = a or c < d group by x", option)
          .ok());

  EXPECT_FALSE(
      CheckParserSucceeds("SELET A FROM B\nSELECT C FROM D", option).ok());

  EXPECT_FALSE(CheckParserSucceeds("SELECT 1; SELECT 2 3 4;", option).ok());
}

TEST(LinterTest, SemicolonCheck) {
  LinterOptions option;
  EXPECT_TRUE(CheckSemicolon("SELECT 3+5;\nSELECT 4+6;", option).ok());
  EXPECT_TRUE(CheckSemicolon("SELECT 3+5;   \n   SELECT 4+6;", option).ok());
  EXPECT_FALSE(CheckSemicolon("SELECT 3+5\nSELECT 4+6;", option).ok());
  EXPECT_FALSE(CheckSemicolon("SELECT 3+5;  \nSELECT 4+6", option).ok());
  EXPECT_FALSE(CheckSemicolon("SELECT 3+5  ;  \nSELECT 4+6", option).ok());
}

TEST(LinterTest, UppercaseKeywordCheck) {
  LinterOptions option;
  EXPECT_TRUE(CheckUppercaseKeywords(
                  "SELECT * FROM emp WHERE b = a OR c < d GROUP BY x", option)
                  .ok());
  EXPECT_TRUE(CheckUppercaseKeywords(
                  "SELECT * FROM emp where b = a or c < d GROUP by x", option)
                  .ok());
  EXPECT_FALSE(CheckUppercaseKeywords(
                   "SeLEct * frOM emp wHEre b = a or c < d GROUP by x", option)
                   .ok());
}

TEST(LinterTest, CommentTypeCheck) {
  LinterOptions option;
  EXPECT_FALSE(
      CheckCommentType("# Comment 1\n-- Comment 2\nSELECT 3+5\n", option).ok());
  EXPECT_TRUE(
      CheckCommentType("-- Comment /* unfinished comment", option).ok());

  EXPECT_TRUE(
      CheckCommentType("//comment 1\nSELECT 3+5\n//comment 2", option).ok());
  EXPECT_FALSE(
      CheckCommentType("//comment 1\nSELECT 3+5\n--comment 2", option).ok());
  EXPECT_TRUE(
      CheckCommentType("--comment 1\nSELECT 3+5\n--comment 2", option).ok());

  // Check a sql containing a multiline comment.
  EXPECT_TRUE(
      CheckCommentType("/* here is // and -- */SELECT 1+2 -- comment 2", option)
          .ok());

  // Check multiline string literal
  EXPECT_TRUE(
      CheckCommentType(
          "SELECT \"\"\"multiline\nstring--\nliteral\nhaving//--//\"\"\"",
          option)
          .ok());
}

TEST(LinterTest, AliasKeywordCheck) {
  LinterOptions option;
  EXPECT_FALSE(CheckAliasKeyword("SELECT 1 a", option).ok());
  EXPECT_TRUE(CheckAliasKeyword("SELECT * FROM emp AS X", option).ok());
  EXPECT_FALSE(CheckAliasKeyword("SELECT * FROM emp X", option).ok());
  EXPECT_TRUE(CheckAliasKeyword("SELECT 1 AS one", option).ok());
}

TEST(LinterTest, TabCharactersUniformCheck) {
  LinterOptions option_space;
  EXPECT_TRUE(
      CheckTabCharactersUniform("  SELECT 5;\n    SELECT 6;", option_space)
          .ok());
  LinterOptions option_tab;
  option_tab.SetAllowedIndent('\t');
  EXPECT_TRUE(
      CheckTabCharactersUniform("\tSELECT 5;\n\t\tSELECT 6;", option_tab).ok());
  EXPECT_TRUE(
      CheckTabCharactersUniform("SELECT 5;\n SELECT\t6;\t", option_space).ok());

  EXPECT_TRUE(
      CheckTabCharactersUniform("SELECT 5;\n \t SELECT 6;", option_space)
          .GetErrors()
          .back()
          .GetPosition() == std::make_pair(2, 2));
  EXPECT_TRUE(
      CheckTabCharactersUniform("  SELECT kek;\n\tSELECT lol;", option_space)
          .GetErrors()
          .back()
          .GetPosition() == std::make_pair(2, 1));
  EXPECT_TRUE(CheckTabCharactersUniform("SELECT 5;\n  SELECT 6;", option_tab)
                  .GetErrors()
                  .back()
                  .GetPosition() == std::make_pair(2, 1));
}

TEST(LinterTest, NoTabsBesidesIndentationsCheck) {
  LinterOptions option;
  EXPECT_TRUE(
      CheckNoTabsBesidesIndentations("\tSELECT 5;\n\tSELECT 6;", option).ok());
  EXPECT_TRUE(
      CheckNoTabsBesidesIndentations("\tSELECT   5;\n\t\tSELECT   6;", option)
          .ok());

  EXPECT_TRUE(
      CheckNoTabsBesidesIndentations("\tSELECT \t5;\n\t\tSELECT   6;", option)
          .GetErrors()
          .back()
          .GetPosition() == std::make_pair(1, 16));
  EXPECT_TRUE(CheckNoTabsBesidesIndentations("\tSELECT 5;\nS\tELECT 6;", option)
                  .GetErrors()
                  .back()
                  .GetPosition() == std::make_pair(2, 2));
}

}  // namespace
}  // namespace zetasql::linter
<|endoftext|>


<commit_before>#include "ofxBgScene.h"

//--------------------------------------------------------------
void ofxBgScene::setup() {
	bBackground = false;
}

//--------------------------------------------------------------
void ofxBgScene::update() {

}

//--------------------------------------------------------------
void ofxBgScene::draw() {
	ofColor startColor;
	ofColor endColor;

	if (bBlack) {
		ofClear(ofColor::black);
	}
	else
	{
		if (bBlue) {
			if (bBackground) {
				ofClear(ofColor::red);
			}
			else {
				ofClear(255);
			}
			startColor = ofColor(0, 200, 255);
			endColor = ofColor(0, 51, 255);
		}
		else {
			if (bBackground) {
				ofClear(ofColor(0, 0, 255));
			}
			else {
				ofClear(255);
			}
			startColor = ofColor::orangeRed;
			endColor = ofColor::orangeRed; //ofColor::orangeRed;
		}

		if (bAnimate) {
			ofColor cs; cs.setHsb(startColor.getHue() + (ofSignedNoise(ofGetElapsedTimef()*0.29 - 0.896)) * 22
				, startColor.getSaturation()
				, startColor.getBrightness());
			ofColor ce; ce.setHsb(endColor.getHue() + (ofSignedNoise(ofGetElapsedTimef()*0.19 + 7.12)) * 22
				, endColor.getSaturation()
				, endColor.getBrightness());

			ofBackgroundGradient(cs, ce);
		}
		else {
			ofBackgroundGradient(startColor, startColor);
		}
	}
}

//--------------------------------------------------------------
void ofxBgScene::clear() {
}

//--------------------------------------------------------------
void ofxBgScene::mouseMoved(int x, int y) {
}

//--------------------------------------------------------------
void ofxBgScene::keyPressed(int key) {
	switch (key)
	{
	case ' ': clear(); break;
	case 'r': setup(); break;
	case 'c': bBlue = !bBlue; break;
	case 'b': bBackground = !bBackground; break;
	default:
		break;
	}
}<commit_msg>bg scene with b/w<commit_after>#include "ofxBgScene.h"

//--------------------------------------------------------------
void ofxBgScene::setup() {
	bBackground = false;
}

//--------------------------------------------------------------
void ofxBgScene::update() {

}

//--------------------------------------------------------------
void ofxBgScene::draw() {
	ofColor startColor;
	ofColor endColor;

	if (bBlack) {
		ofClear(ofColor::black);
	}
	else
	{
		if (bBlue) {
			if (bBackground) {
				ofClear(ofColor::white);
				startColor = ofColor(0);
				endColor = ofColor(0);

			}
			else {
				ofClear(0);
				startColor = ofColor(255);
				endColor = ofColor(255);

			}
		}
		else {
			if (bBackground) {
				ofClear(ofColor(0, 0, 255));
			}
			else {
				ofClear(255);
			}
			startColor = ofColor::orangeRed;
			endColor = ofColor::orangeRed; //ofColor::orangeRed;
		}

		//glClearColor(0,0,0,1);
		if (bAnimate) {
			ofColor cs; cs.setHsb(startColor.getHue() + (ofSignedNoise(ofGetElapsedTimef()*0.29 - 0.896)) * 22
								  , startColor.getSaturation()
								  , startColor.getBrightness());
			ofColor ce; ce.setHsb(endColor.getHue() + (ofSignedNoise(ofGetElapsedTimef()*0.19 + 7.12)) * 22
								  , endColor.getSaturation()
								  , endColor.getBrightness());

			ofBackgroundGradient(cs, ce);
		}
		else {
			ofBackgroundGradient(startColor, startColor);
		}
	}
}

//--------------------------------------------------------------
void ofxBgScene::clear() {
}

//--------------------------------------------------------------
void ofxBgScene::mouseMoved(int x, int y) {
}

//--------------------------------------------------------------
void ofxBgScene::keyPressed(int key) {
	switch (key)
	{
	case ' ': clear(); break;
	case 'r': setup(); break;
	case 'c': bBlue = !bBlue; break;
	case 'b': bBackground = !bBackground; break;
	default:
		break;
	}
}<|endoftext|>


<commit_before>/*
Copyright (c) 2011 Timo Boll, Tony Kostanjsek

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.
*/

#include "../../include/slub/config.h"
#include "../../include/slub/clazz.h"

#include <iostream>
#include <stdexcept>

namespace slub {

  std::pair<int, int> abstract_clazz::construct(lua_State * state, registry * reg, char const * name, char const * fqname, int target)
  {
    lua_newtable(state);
    int methods = lua_gettop(state);

    if (luaL_newmetatable(state, fqname) == 0) {
      throw new std::runtime_error("already registered: "+ string(fqname));
    }
    int metatable = lua_gettop(state);

    // store method table in globals so that
    // scripts can add functions written in Lua.
    lua_pushvalue(state, methods);
    lua_setfield(state, target != -1 ? target : LUA_GLOBALSINDEX, name);

    lua_pushliteral(state, "__metatable");
    lua_pushvalue(state, methods);
    lua_settable(state, metatable);  // hide metatable from Lua getmetatable()

    return std::make_pair(methods, metatable);
  }

  void abstract_clazz::add_symbols(lua_State * state, registry * reg, int methods, int metatable)
  {
    lua_pushliteral(state, "__index");
    lua_pushlightuserdata(state, reg);
    lua_pushcclosure(state, index, 1);
    lua_settable(state, metatable);

    lua_pushliteral(state, "__newindex");
    lua_pushlightuserdata(state, reg);
    lua_pushcclosure(state, newindex, 1);
    lua_settable(state, metatable);

    lua_pushliteral(state, "__eq");
    lua_pushlightuserdata(state, reg);
    lua_pushstring(state, "__eq");
    lua_pushcclosure(state, callOperator, 2);
    lua_settable(state, metatable);

    lua_pushliteral(state, "__lt");
    lua_pushlightuserdata(state, reg);
    lua_pushstring(state, "__lt");
    lua_pushcclosure(state, callOperator, 2);
    lua_settable(state, metatable);

    lua_pushliteral(state, "__le");
    lua_pushlightuserdata(state, reg);
    lua_pushstring(state, "__le");
    lua_pushcclosure(state, callOperator, 2);
    lua_settable(state, metatable);

    lua_pushliteral(state, "__tostring");
    lua_pushlightuserdata(state, reg);
    lua_pushstring(state, "__tostring");
    lua_pushcclosure(state, callOperator, 2);
    lua_settable(state, metatable);

    lua_pushliteral(state, "__add");
    lua_pushlightuserdata(state, reg);
    lua_pushstring(state, "__add");
    lua_pushcclosure(state, callOperator, 2);
    lua_settable(state, metatable);

    lua_pushliteral(state, "__sub");
    lua_pushlightuserdata(state, reg);
    lua_pushstring(state, "__sub");
    lua_pushcclosure(state, callOperator, 2);
    lua_settable(state, metatable);

    lua_pushliteral(state, "__mul");
    lua_pushlightuserdata(state, reg);
    lua_pushstring(state, "__mul");
    lua_pushcclosure(state, callOperator, 2);
    lua_settable(state, metatable);

    lua_pushliteral(state, "__div");
    lua_pushlightuserdata(state, reg);
    lua_pushstring(state, "__div");
    lua_pushcclosure(state, callOperator, 2);
    lua_settable(state, metatable);

    lua_pushliteral(state, "__mod");
    lua_pushlightuserdata(state, reg);
    lua_pushstring(state, "__mod");
    lua_pushcclosure(state, callOperator, 2);
    lua_settable(state, metatable);

    lua_pushliteral(state, "__pow");
    lua_pushlightuserdata(state, reg);
    lua_pushstring(state, "__pow");
    lua_pushcclosure(state, callOperator, 2);
    lua_settable(state, metatable);

    lua_pushliteral(state, "__unm");
    lua_pushlightuserdata(state, reg);
    lua_pushstring(state, "__unm");
    lua_pushcclosure(state, callOperator, 2);
    lua_settable(state, metatable);

    lua_pop(state, 2);  // drop metatable and method table
  }

  // TODO: access by type
  int abstract_clazz::index(lua_State* L) {
    registry* reg = registry::get(*((wrapper_base*) lua_touserdata(L, 1))->type);
    if (reg != NULL) {
      const char* name = lua_tostring(L, -1);
      if (reg->containsField(name)) {
        return reg->getField(lua_touserdata(L, 1), name)->get(L);
      }
      else if (reg->containsMethod(name)) {
        lua_pushvalue(L, -1);
        lua_pushcclosure(L, callMethod, 1);
        return 1;
      }
      else {
        // get value from Lua table
        luaL_getmetatable(L, reg->getTypeName().c_str());
        lua_getfield(L, -1, "__metatable");
        int methods = lua_gettop(L);

        lua_pushvalue(L, -3);
        lua_gettable(L, methods);

        return 1;
      }
    }
    return 0;
  }

  int abstract_clazz::newindex(lua_State* L) {
    registry* reg = registry::get(*((wrapper_base*) lua_touserdata(L, 1))->type);
    if (reg != NULL) {
      string name(lua_tostring(L, -2));
      if (reg->containsField(name)) {
        return reg->getField(lua_touserdata(L, 1), name)->set(L);
      }
      else {
        luaL_getmetatable(L, reg->getTypeName().c_str());
        lua_getfield(L, -1, "__metatable");
        int methods = lua_gettop(L);

        lua_pushvalue(L, -3);
        lua_setfield(L, methods, name.c_str());

        lua_pop(L, 2);
        return 0;
      }
    }
    return 0;
  }

  int abstract_clazz::callMethod(lua_State* L) {
    registry* reg = registry::get(*((wrapper_base*) lua_touserdata(L, 1))->type);
    int num = lua_gettop(L);
    reg->getMethod(lua_tostring(L, lua_upvalueindex(1)), L)->call(L);
    return lua_gettop(L) - num;
  }

  int abstract_clazz::callOperator(lua_State* L) {
    registry* reg = registry::get(*((wrapper_base*) lua_touserdata(L, 1))->type);
    if (reg != NULL) {
      int num = lua_gettop(L);
      reg->getOperator(lua_tostring(L, lua_upvalueindex(2)), L)->op(L);
      return lua_gettop(L) - num;
    }
    return 0;
  }

}
<commit_msg>std::runtime_error constructor needs std::string param<commit_after>/*
Copyright (c) 2011 Timo Boll, Tony Kostanjsek

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.
*/

#include "../../include/slub/config.h"
#include "../../include/slub/clazz.h"

#include <iostream>
#include <stdexcept>

namespace slub {

  std::pair<int, int> abstract_clazz::construct(lua_State * state, registry * reg, char const * name, char const * fqname, int target)
  {
    lua_newtable(state);
    int methods = lua_gettop(state);

    if (luaL_newmetatable(state, fqname) == 0) {
      throw new std::runtime_error("already registered: "+ std::string(fqname));
    }
    int metatable = lua_gettop(state);

    // store method table in globals so that
    // scripts can add functions written in Lua.
    lua_pushvalue(state, methods);
    lua_setfield(state, target != -1 ? target : LUA_GLOBALSINDEX, name);

    lua_pushliteral(state, "__metatable");
    lua_pushvalue(state, methods);
    lua_settable(state, metatable);  // hide metatable from Lua getmetatable()

    return std::make_pair(methods, metatable);
  }

  void abstract_clazz::add_symbols(lua_State * state, registry * reg, int methods, int metatable)
  {
    lua_pushliteral(state, "__index");
    lua_pushlightuserdata(state, reg);
    lua_pushcclosure(state, index, 1);
    lua_settable(state, metatable);

    lua_pushliteral(state, "__newindex");
    lua_pushlightuserdata(state, reg);
    lua_pushcclosure(state, newindex, 1);
    lua_settable(state, metatable);

    lua_pushliteral(state, "__eq");
    lua_pushlightuserdata(state, reg);
    lua_pushstring(state, "__eq");
    lua_pushcclosure(state, callOperator, 2);
    lua_settable(state, metatable);

    lua_pushliteral(state, "__lt");
    lua_pushlightuserdata(state, reg);
    lua_pushstring(state, "__lt");
    lua_pushcclosure(state, callOperator, 2);
    lua_settable(state, metatable);

    lua_pushliteral(state, "__le");
    lua_pushlightuserdata(state, reg);
    lua_pushstring(state, "__le");
    lua_pushcclosure(state, callOperator, 2);
    lua_settable(state, metatable);

    lua_pushliteral(state, "__tostring");
    lua_pushlightuserdata(state, reg);
    lua_pushstring(state, "__tostring");
    lua_pushcclosure(state, callOperator, 2);
    lua_settable(state, metatable);

    lua_pushliteral(state, "__add");
    lua_pushlightuserdata(state, reg);
    lua_pushstring(state, "__add");
    lua_pushcclosure(state, callOperator, 2);
    lua_settable(state, metatable);

    lua_pushliteral(state, "__sub");
    lua_pushlightuserdata(state, reg);
    lua_pushstring(state, "__sub");
    lua_pushcclosure(state, callOperator, 2);
    lua_settable(state, metatable);

    lua_pushliteral(state, "__mul");
    lua_pushlightuserdata(state, reg);
    lua_pushstring(state, "__mul");
    lua_pushcclosure(state, callOperator, 2);
    lua_settable(state, metatable);

    lua_pushliteral(state, "__div");
    lua_pushlightuserdata(state, reg);
    lua_pushstring(state, "__div");
    lua_pushcclosure(state, callOperator, 2);
    lua_settable(state, metatable);

    lua_pushliteral(state, "__mod");
    lua_pushlightuserdata(state, reg);
    lua_pushstring(state, "__mod");
    lua_pushcclosure(state, callOperator, 2);
    lua_settable(state, metatable);

    lua_pushliteral(state, "__pow");
    lua_pushlightuserdata(state, reg);
    lua_pushstring(state, "__pow");
    lua_pushcclosure(state, callOperator, 2);
    lua_settable(state, metatable);

    lua_pushliteral(state, "__unm");
    lua_pushlightuserdata(state, reg);
    lua_pushstring(state, "__unm");
    lua_pushcclosure(state, callOperator, 2);
    lua_settable(state, metatable);

    lua_pop(state, 2);  // drop metatable and method table
  }

  // TODO: access by type
  int abstract_clazz::index(lua_State* L) {
    registry* reg = registry::get(*((wrapper_base*) lua_touserdata(L, 1))->type);
    if (reg != NULL) {
      const char* name = lua_tostring(L, -1);
      if (reg->containsField(name)) {
        return reg->getField(lua_touserdata(L, 1), name)->get(L);
      }
      else if (reg->containsMethod(name)) {
        lua_pushvalue(L, -1);
        lua_pushcclosure(L, callMethod, 1);
        return 1;
      }
      else {
        // get value from Lua table
        luaL_getmetatable(L, reg->getTypeName().c_str());
        lua_getfield(L, -1, "__metatable");
        int methods = lua_gettop(L);

        lua_pushvalue(L, -3);
        lua_gettable(L, methods);

        return 1;
      }
    }
    return 0;
  }

  int abstract_clazz::newindex(lua_State* L) {
    registry* reg = registry::get(*((wrapper_base*) lua_touserdata(L, 1))->type);
    if (reg != NULL) {
      string name(lua_tostring(L, -2));
      if (reg->containsField(name)) {
        return reg->getField(lua_touserdata(L, 1), name)->set(L);
      }
      else {
        luaL_getmetatable(L, reg->getTypeName().c_str());
        lua_getfield(L, -1, "__metatable");
        int methods = lua_gettop(L);

        lua_pushvalue(L, -3);
        lua_setfield(L, methods, name.c_str());

        lua_pop(L, 2);
        return 0;
      }
    }
    return 0;
  }

  int abstract_clazz::callMethod(lua_State* L) {
    registry* reg = registry::get(*((wrapper_base*) lua_touserdata(L, 1))->type);
    int num = lua_gettop(L);
    reg->getMethod(lua_tostring(L, lua_upvalueindex(1)), L)->call(L);
    return lua_gettop(L) - num;
  }

  int abstract_clazz::callOperator(lua_State* L) {
    registry* reg = registry::get(*((wrapper_base*) lua_touserdata(L, 1))->type);
    if (reg != NULL) {
      int num = lua_gettop(L);
      reg->getOperator(lua_tostring(L, lua_upvalueindex(2)), L)->op(L);
      return lua_gettop(L) - num;
    }
    return 0;
  }

}
<|endoftext|>


<commit_before>/*

Copyright (c) 2007, Arvid Norberg
All rights reserved.

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:

    * Redistributions of source code must retain the above copyright
      notice, this list of conditions and the following disclaimer.
    * Redistributions in binary form must reproduce the above copyright
      notice, this list of conditions and the following disclaimer in
      the documentation and/or other materials provided with the distribution.
    * Neither the name of the author nor the names of its
      contributors may be used to endorse or promote products derived
      from this software without specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.

*/

#include "libtorrent/magnet_uri.hpp"
#include "libtorrent/session.hpp"
#include "libtorrent/torrent_handle.hpp"
#include "libtorrent/escape_string.hpp"

#include <string>
#include <sstream>

namespace libtorrent
{
	std::string make_magnet_uri(torrent_handle const& handle)
	{
		std::stringstream ret;
		if (!handle.is_valid()) return ret.str();

		std::string name = handle.name();

		ret << "magnet:?xt=urn:btih:" << base32encode((char*)handle.info_hash().begin());
		if (!name.empty())
			ret << "&dn=" << escape_string(name.c_str(), name.length());
		torrent_status st = handle.status();
		if (!st.current_tracker.empty())
		{
			ret << "&tr=" << escape_string(st.current_tracker.c_str()
				, st.current_tracker.length());
		}
		else
		{
			std::vector<announce_entry> const& tr = handle.trackers();
			if (!tr.empty())
			{
				ret << "&tr=" << escape_string(tr[0].url.c_str()
					, tr[0].url.length());
			}
		}
		return ret.str();
	}

	torrent_handle add_magnet_uri(session& ses, std::string const& uri
		, fs::path const& save_path
		, storage_mode_t storage_mode
		, bool paused
		, storage_constructor_type sc
		, void* userdata)
	{
		std::string name;
		std::string tracker;

		boost::optional<std::string> display_name = url_has_argument(uri, "dn");
		if (display_name) name = unescape_string(display_name->c_str());
		boost::optional<std::string> tracker_string = url_has_argument(uri, "tr");
		if (tracker_string) tracker = unescape_string(tracker_string->c_str());

		boost::optional<std::string> btih = url_has_argument(uri, "xt");
		if (!btih) return torrent_handle();

		if (btih->compare(0, 9, "urn:btih:") != 0) return torrent_handle();

		sha1_hash info_hash(base32decode(btih->substr(9)));

		return ses.add_torrent(tracker.empty() ? 0 : tracker.c_str(), info_hash
			, name.empty() ? 0 : name.c_str(), save_path, entry()
			, storage_mode, paused, sc, userdata);
	}
}

<commit_msg>fixed bug in make_magnet_uri<commit_after>/*

Copyright (c) 2007, Arvid Norberg
All rights reserved.

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:

    * Redistributions of source code must retain the above copyright
      notice, this list of conditions and the following disclaimer.
    * Redistributions in binary form must reproduce the above copyright
      notice, this list of conditions and the following disclaimer in
      the documentation and/or other materials provided with the distribution.
    * Neither the name of the author nor the names of its
      contributors may be used to endorse or promote products derived
      from this software without specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.

*/

#include "libtorrent/magnet_uri.hpp"
#include "libtorrent/session.hpp"
#include "libtorrent/torrent_handle.hpp"
#include "libtorrent/escape_string.hpp"

#include <string>
#include <sstream>

namespace libtorrent
{
	std::string make_magnet_uri(torrent_handle const& handle)
	{
		std::stringstream ret;
		if (!handle.is_valid()) return ret.str();

		std::string name = handle.name();

		ret << "magnet:?xt=urn:btih:" << base32encode(
			std::string((char*)handle.info_hash().begin(), 20));
		if (!name.empty())
			ret << "&dn=" << escape_string(name.c_str(), name.length());
		torrent_status st = handle.status();
		if (!st.current_tracker.empty())
		{
			ret << "&tr=" << escape_string(st.current_tracker.c_str()
				, st.current_tracker.length());
		}
		else
		{
			std::vector<announce_entry> const& tr = handle.trackers();
			if (!tr.empty())
			{
				ret << "&tr=" << escape_string(tr[0].url.c_str()
					, tr[0].url.length());
			}
		}
		return ret.str();
	}

	torrent_handle add_magnet_uri(session& ses, std::string const& uri
		, fs::path const& save_path
		, storage_mode_t storage_mode
		, bool paused
		, storage_constructor_type sc
		, void* userdata)
	{
		std::string name;
		std::string tracker;

		boost::optional<std::string> display_name = url_has_argument(uri, "dn");
		if (display_name) name = unescape_string(display_name->c_str());
		boost::optional<std::string> tracker_string = url_has_argument(uri, "tr");
		if (tracker_string) tracker = unescape_string(tracker_string->c_str());

		boost::optional<std::string> btih = url_has_argument(uri, "xt");
		if (!btih) return torrent_handle();

		if (btih->compare(0, 9, "urn:btih:") != 0) return torrent_handle();

		sha1_hash info_hash(base32decode(btih->substr(9)));

		return ses.add_torrent(tracker.empty() ? 0 : tracker.c_str(), info_hash
			, name.empty() ? 0 : name.c_str(), save_path, entry()
			, storage_mode, paused, sc, userdata);
	}
}

<|endoftext|>


<commit_before>#include "mainwindow.h"

#include "bucketlist.h"

#include <QLabel>
#include <QBoxLayout>
#include <QtWebKit>
#include <QSettings>
#include <QInputDialog>
#include <QFileSystemWatcher>
#include <QDebug>

MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent)
{
    QWidget *central = new QWidget;
    setCentralWidget(central);

    QBoxLayout *topLayout = new QHBoxLayout(central);

    BucketList *bucketList = new BucketList;
    topLayout->addWidget(bucketList);

    m_view = new QWebView;
    topLayout->addWidget(m_view, 1);
    m_view->setMinimumSize(1080, 600);

    getServerPath();

    m_dirWatcher = new QFileSystemWatcher(this);
    connect(m_dirWatcher, SIGNAL(fileChanged(QString)), SLOT(loadView()));

    setWatchedFiles();

    connect(&m_server, SIGNAL(started()), SLOT(loadView()));
    m_server.start();
}

MainWindow::~MainWindow()
{
    m_server.stop();
}

void MainWindow::getServerPath()
{
    QSettings settings;

    QString path = settings.value("view/path").toString();
    if (path.isEmpty()) {
        path = QInputDialog::getText(this, "View path", "Enter base path of view for web server");
    }
    settings.setValue("view/path", path);

    m_server.setPath(path);
}

void MainWindow::loadView()
{
    QUrl url("http://localhost");
    url.setPort(m_server.port());
    m_view->setUrl(url);
    m_view->show();

    setWatchedFiles();
}

void MainWindow::setWatchedFiles()
{
    m_dirWatcher->addPath(m_server.path() + "/index.html");
    m_dirWatcher->addPath(m_server.path() + "/chart.js");
    m_dirWatcher->addPath(m_server.path() + "/chart.css");
}
<commit_msg>More robust way to add files to watcher<commit_after>#include "mainwindow.h"

#include "bucketlist.h"

#include <QLabel>
#include <QBoxLayout>
#include <QtWebKit>
#include <QSettings>
#include <QInputDialog>
#include <QFileSystemWatcher>
#include <QDebug>

MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent)
{
    QWidget *central = new QWidget;
    setCentralWidget(central);

    QBoxLayout *topLayout = new QHBoxLayout(central);

    BucketList *bucketList = new BucketList;
    topLayout->addWidget(bucketList);

    m_view = new QWebView;
    topLayout->addWidget(m_view, 1);
    m_view->setMinimumSize(1080, 600);

    getServerPath();

    m_dirWatcher = new QFileSystemWatcher(this);
    connect(m_dirWatcher, SIGNAL(fileChanged(QString)), SLOT(loadView()));

    setWatchedFiles();

    connect(&m_server, SIGNAL(started()), SLOT(loadView()));
    m_server.start();
}

MainWindow::~MainWindow()
{
    m_server.stop();
}

void MainWindow::getServerPath()
{
    QSettings settings;

    QString path = settings.value("view/path").toString();
    if (path.isEmpty()) {
        path = QInputDialog::getText(this, "View path", "Enter base path of view for web server");
    }
    settings.setValue("view/path", path);

    m_server.setPath(path);
}

void MainWindow::loadView()
{
    QUrl url("http://localhost");
    url.setPort(m_server.port());
    m_view->setUrl(url);
    m_view->show();

    setWatchedFiles();
}

void MainWindow::setWatchedFiles()
{
    QStringList files;
    files << "index.html" << "chart.js" << "chart.css";

    foreach(QString file, files) {
        QString path = m_server.path();
        if(!path.endsWith("/")) {
            path += "/";
        }
        path += file;
        if(!m_dirWatcher->files().contains(path)) {
            m_dirWatcher->addPath(path);
        }
    }
}
<|endoftext|>


<commit_before>#include "mainwindow.h"
#include "cardreader.h"

#include <QGridLayout>
#include <QLabel>

#include "shoppinglist.h"

MainWindow::MainWindow(QWidget *parent)
{
	QGridLayout *layout = new QGridLayout(this);
	QLabel *testLabel = new QLabel;
	layout->addWidget(testLabel);

	//install cardReader as an filter which intercepts keyboard events
	CardReader *cardReader = new CardReader(this);
	installEventFilter(cardReader);
	connect(cardReader, SIGNAL(newCardNumber(QString)), testLabel, SLOT(setText(QString)));

	//shoppinglist and associated view
	ShoppingList *list = new ShoppingList(this);

	ShoppingListWidget *shoppingListWidget = new ShoppingListWidget(list);
	layout->addWidget(shoppingListWidget);

	//FIXME: Populate with some example data.
	list->newItem("Brus", 15, 2);
	list->newItem("Godterisopp", 2, 35);
	list->newItem("Kvikklunsj", 10, 1);
	list->newItem("Ragni spesial", 788.5, 3);
}
<commit_msg>Add note about slot connection tin mainwindow.<commit_after>#include "mainwindow.h"
#include "cardreader.h"

#include <QGridLayout>
#include <QLabel>

#include "shoppinglist.h"

MainWindow::MainWindow(QWidget *parent)
{
	QGridLayout *layout = new QGridLayout(this);
	QLabel *testLabel = new QLabel;
	layout->addWidget(testLabel);

	//install cardReader as an filter which intercepts keyboard events
	CardReader *cardReader = new CardReader(this);
	installEventFilter(cardReader);
	connect(cardReader, SIGNAL(newCardNumber(QString)), testLabel, SLOT(setText(QString)));

	//shoppinglist and associated view
	ShoppingList *list = new ShoppingList(this);

	ShoppingListWidget *shoppingListWidget = new ShoppingListWidget(list);
	layout->addWidget(shoppingListWidget);

	//Populate with some example data.
	//Menu class will have to connect to ShoppingList::newItem().
	list->newItem("Brus", 15, 2);
	list->newItem("Godterisopp", 2, 35);
	list->newItem("Kvikklunsj", 10, 1);
	list->newItem("Ragni spesial", 788.5, 3);
}
<|endoftext|>


<commit_before>#include <vector>
#include <sys/ptrace.h>
#include <sys/wait.h>
#include <unistd.h>
#include <sstream>
#include <iostream>

#include "linenoise.h"

#include "debugger.hpp"

using namespace minidbg;

std::vector<std::string> split(const std::string &s, char delimiter) {
    std::vector<std::string> out{};
    std::stringstream ss {s};
    std::string item;

    while (std::getline(ss,item,delimiter)) {
        out.push_back(item);
    }

    return out;
}

bool is_prefix(const std::string& s, const std::string& of) {
    if (s.size() > of.size()) return false;
    return std::equal(s.begin(), s.end(), of.begin());
}

void debugger::handle_command(const std::string& line) {
    auto args = split(line,' ');
    auto command = args[0];

    if (is_prefix(command, "cont")) {
        continue_execution();
    }
    else if(is_prefix(command, "break")) {
        std::string addr {args[1], 2}; //naively assume that the user has written 0xADDRESS
        set_breakpoint_at_address(std::stol(addr, 0, 16));
    }
    else {
        std::cerr << "Unknown command\n";
    }
}

void debugger::set_breakpoint_at_address(std::intptr_t addr) {
    std::cout << "Set breakpoint at address 0x" << std::hex << addr << std::endl;
    breakpoint bp {m_pid, addr};
    bp.enable();
    m_breakpoints[addr] = bp;
}

void debugger::run() {
    int wait_status;
    auto options = 0;
    waitpid(m_pid, &wait_status, options);

    char* line = nullptr;
    while((line = linenoise("minidbg> ")) != nullptr) {
        handle_command(line);
        linenoiseHistoryAdd(line);
        linenoiseFree(line);
    }
}

void debugger::continue_execution() {
    ptrace(PTRACE_CONT, m_pid, nullptr, nullptr);

    int wait_status;
    auto options = 0;
    waitpid(m_pid, &wait_status, options);
}

void execute_debugee (const std::string& prog_name) {
    if (ptrace(PTRACE_TRACEME, 0, 0, 0) < 0) {
        std::cerr << "Error in ptrace\n";
        return;
    }
    execl(prog_name.c_str(), prog_name.c_str(), nullptr);
}

int main(int argc, char* argv[]) {
    if (argc < 2) {
        std::cerr << "Program name not specified";
        return -1;
    }

    auto prog = argv[1];

    auto pid = fork();
    if (pid == 0) {
        //child
        execute_debugee(prog);

    }
    else if (pid >= 1)  {
        //parent
        std::cout << "Started debugging process " << pid << '\n';
        debugger dbg{prog, pid};
        dbg.run();
    }
}

<commit_msg>Add ASLR disable<commit_after>#include <vector>
#include <sys/ptrace.h>
#include <sys/wait.h>
#include <sys/personality.h>
#include <unistd.h>
#include <sstream>
#include <iostream>

#include "linenoise.h"

#include "debugger.hpp"

using namespace minidbg;

std::vector<std::string> split(const std::string &s, char delimiter) {
    std::vector<std::string> out{};
    std::stringstream ss {s};
    std::string item;

    while (std::getline(ss,item,delimiter)) {
        out.push_back(item);
    }

    return out;
}

bool is_prefix(const std::string& s, const std::string& of) {
    if (s.size() > of.size()) return false;
    return std::equal(s.begin(), s.end(), of.begin());
}

void debugger::handle_command(const std::string& line) {
    auto args = split(line,' ');
    auto command = args[0];

    if (is_prefix(command, "cont")) {
        continue_execution();
    }
    else if(is_prefix(command, "break")) {
        std::string addr {args[1], 2}; //naively assume that the user has written 0xADDRESS
        set_breakpoint_at_address(std::stol(addr, 0, 16));
    }
    else {
        std::cerr << "Unknown command\n";
    }
}

void debugger::set_breakpoint_at_address(std::intptr_t addr) {
    std::cout << "Set breakpoint at address 0x" << std::hex << addr << std::endl;
    breakpoint bp {m_pid, addr};
    bp.enable();
    m_breakpoints[addr] = bp;
}

void debugger::run() {
    int wait_status;
    auto options = 0;
    waitpid(m_pid, &wait_status, options);

    char* line = nullptr;
    while((line = linenoise("minidbg> ")) != nullptr) {
        handle_command(line);
        linenoiseHistoryAdd(line);
        linenoiseFree(line);
    }
}

void debugger::continue_execution() {
    ptrace(PTRACE_CONT, m_pid, nullptr, nullptr);

    int wait_status;
    auto options = 0;
    waitpid(m_pid, &wait_status, options);
}

void execute_debugee (const std::string& prog_name) {
    if (ptrace(PTRACE_TRACEME, 0, 0, 0) < 0) {
        std::cerr << "Error in ptrace\n";
        return;
    }
    execl(prog_name.c_str(), prog_name.c_str(), nullptr);
}

int main(int argc, char* argv[]) {
    if (argc < 2) {
        std::cerr << "Program name not specified";
        return -1;
    }

    auto prog = argv[1];

    auto pid = fork();
    if (pid == 0) {
        //child
        personality(ADDR_NO_RANDOMIZE);
        execute_debugee(prog);
    }
    else if (pid >= 1)  {
        //parent
        std::cout << "Started debugging process " << pid << '\n';
        debugger dbg{prog, pid};
        dbg.run();
    }
}

<|endoftext|>


<commit_before>#include "natives.hpp"
#include "CCallback.hpp"
#include "CNetwork.hpp"
#include "CDispatcher.hpp"
#include "CMessage.hpp"
#include "CChannel.hpp"
#include "misc.hpp"
#include "types.hpp"
#include "CLog.hpp"

#include <fmt/printf.h>

#ifdef ERROR
#undef ERROR
#endif
/*
// native native_name(...);
AMX_DECLARE_NATIVE(Native::native_name)
{
	CScopedDebugInfo dbg_info(amx, "native_name", "sd");

	cell ret_val = ;
	CLog::Get()->LogNative(LogLevel::DEBUG, "return value: '{}'", ret_val);
	return ret_val;
}
*/

// native DCC_Connect(const bot_token[]);
AMX_DECLARE_NATIVE(Native::DCC_Connect)
{
	CScopedDebugInfo dbg_info(amx, "DCC_Connect", "s");

	CChannelManager::Get()->Initialize(amx);
	CNetwork::Get()->Initialize(amx_GetCppString(amx, params[1]));

	CChannelManager::Get()->WaitForInitialization();

	cell ret_val = 1;
	CLog::Get()->LogNative(LogLevel::DEBUG, "return value: '{}'", ret_val);
	return ret_val;
}

// native DCC_SendChannelMessage(DCC_Channel:channel, const message[]);
AMX_DECLARE_NATIVE(Native::DCC_SendChannelMessage)
{
	CScopedDebugInfo dbg_info(amx, "DCC_SendMessage", "ds");

	ChannelId_t channelid = static_cast<ChannelId_t>(params[1]);
	Channel_t const &channel = CChannelManager::Get()->FindChannel(channelid);
	if (!channel)
	{
		CLog::Get()->LogNative(LogLevel::ERROR, "invalid channel id '{}'", channelid);
		return 0;
	}

	channel->SendMessage(amx_GetCppString(amx, params[2]));

	CLog::Get()->LogNative(LogLevel::DEBUG, "return value: '1'");
	return 1;
}

// native DCC_Channel:DCC_FindChannelByName(const channel_name[]);
AMX_DECLARE_NATIVE(Native::DCC_FindChannelByName)
{
	CScopedDebugInfo dbg_info(amx, "DCC_FindChannelByName", "s");

	std::string const channel_name = amx_GetCppString(amx, params[1]);
	Channel_t const &channel = CChannelManager::Get()->FindChannelByName(channel_name);

	cell ret_val = channel ? channel->GetPawnId() : 0;

	CLog::Get()->LogNative(LogLevel::DEBUG, "return value: '{}'", ret_val);
	return ret_val;
}

// native DCC_Channel:DCC_FindChannelById(const channel_id[]);
AMX_DECLARE_NATIVE(Native::DCC_FindChannelById)
{
	CScopedDebugInfo dbg_info(amx, "DCC_FindChannelById", "s");

	Snowflake_t const channel_id = amx_GetCppString(amx, params[1]);
	Channel_t const &channel = CChannelManager::Get()->FindChannelById(channel_id);

	cell ret_val = channel ? channel->GetPawnId() : 0;

	CLog::Get()->LogNative(LogLevel::DEBUG, "return value: '{}'", ret_val);
	return ret_val;
}
<commit_msg>censor bot token in log<commit_after>#include "natives.hpp"
#include "CCallback.hpp"
#include "CNetwork.hpp"
#include "CDispatcher.hpp"
#include "CMessage.hpp"
#include "CChannel.hpp"
#include "misc.hpp"
#include "types.hpp"
#include "CLog.hpp"

#include <fmt/printf.h>

#ifdef ERROR
#undef ERROR
#endif
/*
// native native_name(...);
AMX_DECLARE_NATIVE(Native::native_name)
{
	CScopedDebugInfo dbg_info(amx, "native_name", "sd");

	cell ret_val = ;
	CLog::Get()->LogNative(LogLevel::DEBUG, "return value: '{}'", ret_val);
	return ret_val;
}
*/

// native DCC_Connect(const bot_token[]);
AMX_DECLARE_NATIVE(Native::DCC_Connect)
{
	CScopedDebugInfo dbg_info(amx, "DCC_Connect", "*");

	CChannelManager::Get()->Initialize(amx);
	CNetwork::Get()->Initialize(amx_GetCppString(amx, params[1]));

	CChannelManager::Get()->WaitForInitialization();

	cell ret_val = 1;
	CLog::Get()->LogNative(LogLevel::DEBUG, "return value: '{}'", ret_val);
	return ret_val;
}

// native DCC_SendChannelMessage(DCC_Channel:channel, const message[]);
AMX_DECLARE_NATIVE(Native::DCC_SendChannelMessage)
{
	CScopedDebugInfo dbg_info(amx, "DCC_SendMessage", "ds");

	ChannelId_t channelid = static_cast<ChannelId_t>(params[1]);
	Channel_t const &channel = CChannelManager::Get()->FindChannel(channelid);
	if (!channel)
	{
		CLog::Get()->LogNative(LogLevel::ERROR, "invalid channel id '{}'", channelid);
		return 0;
	}

	channel->SendMessage(amx_GetCppString(amx, params[2]));

	CLog::Get()->LogNative(LogLevel::DEBUG, "return value: '1'");
	return 1;
}

// native DCC_Channel:DCC_FindChannelByName(const channel_name[]);
AMX_DECLARE_NATIVE(Native::DCC_FindChannelByName)
{
	CScopedDebugInfo dbg_info(amx, "DCC_FindChannelByName", "s");

	std::string const channel_name = amx_GetCppString(amx, params[1]);
	Channel_t const &channel = CChannelManager::Get()->FindChannelByName(channel_name);

	cell ret_val = channel ? channel->GetPawnId() : 0;

	CLog::Get()->LogNative(LogLevel::DEBUG, "return value: '{}'", ret_val);
	return ret_val;
}

// native DCC_Channel:DCC_FindChannelById(const channel_id[]);
AMX_DECLARE_NATIVE(Native::DCC_FindChannelById)
{
	CScopedDebugInfo dbg_info(amx, "DCC_FindChannelById", "s");

	Snowflake_t const channel_id = amx_GetCppString(amx, params[1]);
	Channel_t const &channel = CChannelManager::Get()->FindChannelById(channel_id);

	cell ret_val = channel ? channel->GetPawnId() : 0;

	CLog::Get()->LogNative(LogLevel::DEBUG, "return value: '{}'", ret_val);
	return ret_val;
}
<|endoftext|>


<commit_before>#include "utils.h"

#ifdef QT_GUI_LIB
#include <QApplication>
#endif
#include <QDir>
#include <QDirIterator>
#include <QFile>
#include <QFileInfo>
#ifdef QT_GUI_LIB
#include <QMessageBox>
#endif
#include <QProcess>
#include <QResource>

namespace OpenCOR {

QString exec(const QString &pProg, const QString &pArgs)
{
    if (QFileInfo(pProg).exists()) {
        // The program exists, so we can execute it

        QProcess process;

        process.start(pProg,  QStringList() << pArgs);
        process.waitForFinished();

        return process.readAll().trimmed();
    } else {
        // The program doesn't exist, so...

        return QString();
    }
}

OsType getOsType()
{
#ifdef Q_OS_WIN32
    return Windows;
#elif Q_OS_LINUX
    return Linux;
#elif Q_OS_MAC
    return MacOsX;
#else
    return Unknown;
#endif
}

QString getOsName()
{
#ifdef Q_WS_WIN
    switch(QSysInfo::WindowsVersion)
    {
        case QSysInfo::WV_NT:
            return "Microsoft Windows NT";
        case QSysInfo::WV_2000:
            return "Microsoft Windows 2000";
        case QSysInfo::WV_XP:
            return "Microsoft Windows XP";
        case QSysInfo::WV_2003:
            return "Microsoft Windows 2003";
        case QSysInfo::WV_VISTA:
            return "Microsoft Windows Vista";
        case QSysInfo::WV_WINDOWS7:
            return "Microsoft Windows 7";
        default:
            return "Microsoft Windows";
    }
#elif Q_WS_MAC
    // Note: the version of Qt that we use on Mac OS X only supports Mac OS X
    //       10.5 and above, so...

    switch(QSysInfo::MacintoshVersion)
    {
        case QSysInfo::MV_10_5:
            return "Mac OS X 10.5 (Leopard)";
        case QSysInfo::MV_10_6:
            return "Mac OS X 10.6 (Snow Leopard)";
        default:
            return "Mac OS X";
    }
#else
    QString os = exec("/bin/uname", "-o");

    if (os.isEmpty())
        // We couldn't find /bin/uname, so...

        return "Unknown";
    else
        return os+" "+exec("/bin/uname", "-r");
#endif
}

BitVersion getAppBitVersion()
{
    int sizeOfPointer = sizeof(void *);

    switch (sizeOfPointer) {
        case 4:
            // 32-bit

            return x86;
        case 8:
            // 64-bit

            return x86_64;
        default:
            // Not a size that we could recognise, so...

            return xUnknown;
    }
}

QByteArray resourceAsByteArray(const QString &pResource)
{
    // Retrieve a resource as a QByteArray

    QResource resource(pResource);

    if (resource.isValid()) {
        if (resource.isCompressed())
            // The resource is compressed, so uncompress it before returning it
            // Note: qUncompress returns a QByteArray, so we are fine...

            return qUncompress(reinterpret_cast<const uchar *>(resource.data()),
                               resource.size());
        else
            // The resource is not compressed, so just return it after doing the
            // right conversions

            return QByteArray(reinterpret_cast<const char *>(resource.data()),
                              resource.size());
    }
    else {
        // The resource doesn't exist, so...

        return QByteArray();
    }
}

void saveResourceAs(const QString &pResource, const QString &pFilename)
{
    if (QResource(pResource).isValid()) {
        // The resource exists, so write a file with name pFilename and which
        // contents is that of the resource which is retrieved as a QByteArray

        QFile file(pFilename);

        file.open(QIODevice::ReadWrite);
        file.write(resourceAsByteArray(pResource));
        file.close();
    }
}

#ifdef QT_GUI_LIB
void notYetImplemented(const QString &method)
{
    QMessageBox::information(0, qApp->applicationName()+" Information",
                             "Sorry, but the '"+method+"' method has not yet been implemented.");
}
#endif

}
<commit_msg>Oops, silly oversight!<commit_after>#include "utils.h"

#ifdef QT_GUI_LIB
#include <QApplication>
#endif
#include <QDir>
#include <QDirIterator>
#include <QFile>
#include <QFileInfo>
#ifdef QT_GUI_LIB
#include <QMessageBox>
#endif
#include <QProcess>
#include <QResource>

namespace OpenCOR {

QString exec(const QString &pProg, const QString &pArgs)
{
    if (QFileInfo(pProg).exists()) {
        // The program exists, so we can execute it

        QProcess process;

        process.start(pProg,  QStringList() << pArgs);
        process.waitForFinished();

        return process.readAll().trimmed();
    } else {
        // The program doesn't exist, so...

        return QString();
    }
}

OsType getOsType()
{
#ifdef Q_OS_WIN32
    return Windows;
#elif defined(Q_OS_LINUX)
    return Linux;
#elif defined(Q_OS_MAC)
    return MacOsX;
#else
    return Unknown;
#endif
}

QString getOsName()
{
#ifdef Q_WS_WIN
    switch(QSysInfo::WindowsVersion)
    {
        case QSysInfo::WV_NT:
            return "Microsoft Windows NT";
        case QSysInfo::WV_2000:
            return "Microsoft Windows 2000";
        case QSysInfo::WV_XP:
            return "Microsoft Windows XP";
        case QSysInfo::WV_2003:
            return "Microsoft Windows 2003";
        case QSysInfo::WV_VISTA:
            return "Microsoft Windows Vista";
        case QSysInfo::WV_WINDOWS7:
            return "Microsoft Windows 7";
        default:
            return "Microsoft Windows";
    }
#elif defined(Q_WS_MAC)
    // Note: the version of Qt that we use on Mac OS X only supports Mac OS X
    //       10.5 and above, so...

    switch(QSysInfo::MacintoshVersion)
    {
        case QSysInfo::MV_10_5:
            return "Mac OS X 10.5 (Leopard)";
        case QSysInfo::MV_10_6:
            return "Mac OS X 10.6 (Snow Leopard)";
        default:
            return "Mac OS X";
    }
#else
    QString os = exec("/bin/uname", "-o");

    if (os.isEmpty())
        // We couldn't find /bin/uname, so...

        return "Unknown";
    else
        return os+" "+exec("/bin/uname", "-r");
#endif
}

BitVersion getAppBitVersion()
{
    int sizeOfPointer = sizeof(void *);

    switch (sizeOfPointer) {
        case 4:
            // 32-bit

            return x86;
        case 8:
            // 64-bit

            return x86_64;
        default:
            // Not a size that we could recognise, so...

            return xUnknown;
    }
}

QByteArray resourceAsByteArray(const QString &pResource)
{
    // Retrieve a resource as a QByteArray

    QResource resource(pResource);

    if (resource.isValid()) {
        if (resource.isCompressed())
            // The resource is compressed, so uncompress it before returning it
            // Note: qUncompress returns a QByteArray, so we are fine...

            return qUncompress(reinterpret_cast<const uchar *>(resource.data()),
                               resource.size());
        else
            // The resource is not compressed, so just return it after doing the
            // right conversions

            return QByteArray(reinterpret_cast<const char *>(resource.data()),
                              resource.size());
    }
    else {
        // The resource doesn't exist, so...

        return QByteArray();
    }
}

void saveResourceAs(const QString &pResource, const QString &pFilename)
{
    if (QResource(pResource).isValid()) {
        // The resource exists, so write a file with name pFilename and which
        // contents is that of the resource which is retrieved as a QByteArray

        QFile file(pFilename);

        file.open(QIODevice::ReadWrite);
        file.write(resourceAsByteArray(pResource));
        file.close();
    }
}

#ifdef QT_GUI_LIB
void notYetImplemented(const QString &method)
{
    QMessageBox::information(0, qApp->applicationName()+" Information",
                             "Sorry, but the '"+method+"' method has not yet been implemented.");
}
#endif

}
<|endoftext|>