<commit_before>//===- PrettyResultPrinter.cpp ---------------------------------------------===//
//
//                     The pat Team
//
// This file is distributed under the New BSD License.
// See LICENSE for details.
//
//===----------------------------------------------------------------------===//
#include <pat/Listeners/PrettyResultPrinter.h>
#include <pat/ADT/Color.h>
#include <iostream>

using namespace pat;

//===----------------------------------------------------------------------===//
// PrettyResultPrinter
//===----------------------------------------------------------------------===//
void PrettyResultPrinter::PrintCaseName(const std::string& pCase,
                                        const std::string& pTest)
{
  testing::Log::getOStream() << pCase << "." << pTest;
}

void PrettyResultPrinter::OnTestProgramStart(const testing::UnitTest& pUnitTest)
{
  testing::Log::getOStream() << Color::CYAN << "[    pat   ] "
    << "Running " << pUnitTest.getNumOfTests()
    << " tests from " << pUnitTest.getNumOfCases() << " cases." << std::endl;
}

void PrettyResultPrinter::OnTestCaseStart(const testing::TestCase& pTestCase)
{
  testing::Log::getOStream() << Color::GREEN << "[----------] " << Color::YELLOW;
  int num_tests = pTestCase.getNumOfTests();
  if (1 == num_tests)
    testing::Log::getOStream() << "1 test from ";
  else if (1 < num_tests)
    testing::Log::getOStream() << num_tests << " tests from ";

  testing::Log::getOStream() << pTestCase.getCaseName() << "."
                             << Color::RESET << std::endl;
}

void PrettyResultPrinter::OnTestStart(const testing::TestInfo& pTestInfo)
{
  testing::Log::getOStream() << Color::GREEN
                             << "[ RUN      ] " << Color::WHITE;
  PrintCaseName(pTestInfo.getCaseName(), pTestInfo.getTestName());
  testing::Log::getOStream() << Color::RESET << std::endl;
}

void PrettyResultPrinter::OnTestEnd(const testing::TestInfo& pTestInfo)
{
  // unit-test results
  if (pTestInfo.result().isPassed()) {
    testing::Log::getOStream() << Color::GREEN
                               << "[       OK ] \n";
  }
  if (pTestInfo.result().isFailed()) {
    testing::Log::getOStream() << Color::RED
                               << "[  FAILED  ] ";
    testing::TestResult::Reliability::const_iterator test =
                                    pTestInfo.result().reliability().begin();
    testing::TestResult::Reliability::const_iterator tEnd =
                                      pTestInfo.result().reliability().end();
    while (test != tEnd) {
      testing::Log::getOStream() << "\n" << Color::Bold(Color::YELLOW)
                                         << (*test)->filename()
                                         << ':'
                                         << (*test)->lineNumber()
                                         << ": ";
      switch ((*test)->type()) {
        case testing::TestPartResult::kFatalFailure: {
          testing::Log::getOStream()
                               << Color::RED
                               << "fatal: "
                               << Color::RESET << Color::Bold(Color::YELLOW)
                               << "failed to assert\n";
          break;
        }
        case testing::TestPartResult::kNonFatalFailure: {
          testing::Log::getOStream()
                               << Color::MAGENTA
                               << "error: "
                               << Color::RESET << Color::Bold(Color::YELLOW)
                               << "failed to expect\n";
          break;
        }
        default:
          break;
      }

      testing::Log::getOStream() << Color::RESET
                                 << (*test)->message();
      ++test;
    }
    testing::Log::getOStream() << std::endl;
  }

  // performance test results
  if (!pTestInfo.result().performance().empty()) {
    // timer's result
    testing::Log::getOStream() << Color::Bold(Color::BLUE)
                               << "[ TIME (ns)]";

    testing::TestResult::Performance::const_iterator perf =
                                      pTestInfo.result().performance().begin();
    testing::TestResult::Performance::const_iterator pEnd =
                                      pTestInfo.result().performance().end();

    while (perf != pEnd) {
      testing::Log::getOStream() << " " << std::setw(7)
                                 << (*perf)->getTimerNum();
      ++perf;
    }
    testing::Log::getOStream() << Color::RESET << std::endl;

    // perf_event's results
    testing::Log::getOStream() << Color::Bold(Color::BLUE)
                               << "[CXT SWITCH]";

    perf = pTestInfo.result().performance().begin();
    pEnd = pTestInfo.result().performance().end();

    while (perf != pEnd) {
      testing::Log::getOStream() << " " << std::setw(7)
                                 << (*perf)->getPerfEventNum();
      ++perf;
    }
    testing::Log::getOStream() << Color::RESET << std::endl;
  }
}

void PrettyResultPrinter::OnTestProgramEnd(const testing::UnitTest& pUnitTest)
{
  testing::Log::getOStream() << Color::CYAN << "[==========] "
                             << pUnitTest.getNumOfTests();
  if (1 == pUnitTest.getNumOfTests())
    testing::Log::getOStream() << " test from ";
  if (1 < pUnitTest.getNumOfTests())
    testing::Log::getOStream() << " tests from ";

  testing::Log::getOStream() << pUnitTest.getNumOfCases()
                             << " cases ran.\n";

  if (0 == pUnitTest.getNumOfFails()) {
    testing::Log::getOStream() << Color::GREEN << "[  PASSED  ] "
                               << Color::RESET
                               << pUnitTest.getNumOfTests();

    if (1 == pUnitTest.getNumOfTests()) {
      testing::Log::getOStream() << " test.\n"
                                 << std::flush;
    }

    if (1 < pUnitTest.getNumOfTests()) {
      testing::Log::getOStream() << " tests.\n"
                                 << std::flush;
    }
  }
  else {
    testing::Log::getOStream() << Color::RED << "[  FAILED  ] "
                               << Color::RESET
                               << pUnitTest.getNumOfFails();
    if (1 == pUnitTest.getNumOfFails()) {
      testing::Log::getOStream() << " test.\n"
                                 << std::flush;
    }

    if (1 < pUnitTest.getNumOfFails()) {
      testing::Log::getOStream() << " tests.\n"
                                 << std::flush;
    }
  }
}
<commit_msg>Let runtime data gathered by ''Perf'' only print in Linux environment<commit_after>//===- PrettyResultPrinter.cpp ---------------------------------------------===//
//
//                     The pat Team
//
// This file is distributed under the New BSD License.
// See LICENSE for details.
//
//===----------------------------------------------------------------------===//
#include <pat/Listeners/PrettyResultPrinter.h>
#include <pat/ADT/Color.h>
#include <iostream>

using namespace pat;

//===----------------------------------------------------------------------===//
// PrettyResultPrinter
//===----------------------------------------------------------------------===//
void PrettyResultPrinter::PrintCaseName(const std::string& pCase,
                                        const std::string& pTest)
{
  testing::Log::getOStream() << pCase << "." << pTest;
}

void PrettyResultPrinter::OnTestProgramStart(const testing::UnitTest& pUnitTest)
{
  testing::Log::getOStream() << Color::CYAN << "[    pat   ] "
    << "Running " << pUnitTest.getNumOfTests()
    << " tests from " << pUnitTest.getNumOfCases() << " cases." << std::endl;
}

void PrettyResultPrinter::OnTestCaseStart(const testing::TestCase& pTestCase)
{
  testing::Log::getOStream() << Color::GREEN << "[----------] " << Color::YELLOW;
  int num_tests = pTestCase.getNumOfTests();
  if (1 == num_tests)
    testing::Log::getOStream() << "1 test from ";
  else if (1 < num_tests)
    testing::Log::getOStream() << num_tests << " tests from ";

  testing::Log::getOStream() << pTestCase.getCaseName() << "."
                             << Color::RESET << std::endl;
}

void PrettyResultPrinter::OnTestStart(const testing::TestInfo& pTestInfo)
{
  testing::Log::getOStream() << Color::GREEN
                             << "[ RUN      ] " << Color::WHITE;
  PrintCaseName(pTestInfo.getCaseName(), pTestInfo.getTestName());
  testing::Log::getOStream() << Color::RESET << std::endl;
}

void PrettyResultPrinter::OnTestEnd(const testing::TestInfo& pTestInfo)
{
  // unit-test results
  if (pTestInfo.result().isPassed()) {
    testing::Log::getOStream() << Color::GREEN
                               << "[       OK ] \n";
  }
  if (pTestInfo.result().isFailed()) {
    testing::Log::getOStream() << Color::RED
                               << "[  FAILED  ] ";
    testing::TestResult::Reliability::const_iterator test =
                                    pTestInfo.result().reliability().begin();
    testing::TestResult::Reliability::const_iterator tEnd =
                                      pTestInfo.result().reliability().end();
    while (test != tEnd) {
      testing::Log::getOStream() << "\n" << Color::Bold(Color::YELLOW)
                                         << (*test)->filename()
                                         << ':'
                                         << (*test)->lineNumber()
                                         << ": ";
      switch ((*test)->type()) {
        case testing::TestPartResult::kFatalFailure: {
          testing::Log::getOStream()
                               << Color::RED
                               << "fatal: "
                               << Color::RESET << Color::Bold(Color::YELLOW)
                               << "failed to assert\n";
          break;
        }
        case testing::TestPartResult::kNonFatalFailure: {
          testing::Log::getOStream()
                               << Color::MAGENTA
                               << "error: "
                               << Color::RESET << Color::Bold(Color::YELLOW)
                               << "failed to expect\n";
          break;
        }
        default:
          break;
      }

      testing::Log::getOStream() << Color::RESET
                                 << (*test)->message();
      ++test;
    }
    testing::Log::getOStream() << std::endl;
  }

  // performance test results
  if (!pTestInfo.result().performance().empty()) {
    // timer's result
    testing::Log::getOStream() << Color::Bold(Color::BLUE)
                               << "[ TIME (ns)]";

    testing::TestResult::Performance::const_iterator perf =
                                      pTestInfo.result().performance().begin();
    testing::TestResult::Performance::const_iterator pEnd =
                                      pTestInfo.result().performance().end();

    while (perf != pEnd) {
      testing::Log::getOStream() << " " << std::setw(7)
                                 << (*perf)->getTimerNum();
      ++perf;
    }
    testing::Log::getOStream() << Color::RESET << std::endl;

    // perf_event's results
#if defined(HAVE_LINUX_PERF_EVENT_H)
    testing::Log::getOStream() << Color::Bold(Color::BLUE)
                               << "[CXT SWITCH]";

    perf = pTestInfo.result().performance().begin();
    pEnd = pTestInfo.result().performance().end();

    while (perf != pEnd) {
      testing::Log::getOStream() << " " << std::setw(7)
                                 << (*perf)->getPerfEventNum();
      ++perf;
    }
    testing::Log::getOStream() << Color::RESET << std::endl;
#endif
  }
}

void PrettyResultPrinter::OnTestProgramEnd(const testing::UnitTest& pUnitTest)
{
  testing::Log::getOStream() << Color::CYAN << "[==========] "
                             << pUnitTest.getNumOfTests();
  if (1 == pUnitTest.getNumOfTests())
    testing::Log::getOStream() << " test from ";
  if (1 < pUnitTest.getNumOfTests())
    testing::Log::getOStream() << " tests from ";

  testing::Log::getOStream() << pUnitTest.getNumOfCases()
                             << " cases ran.\n";

  if (0 == pUnitTest.getNumOfFails()) {
    testing::Log::getOStream() << Color::GREEN << "[  PASSED  ] "
                               << Color::RESET
                               << pUnitTest.getNumOfTests();

    if (1 == pUnitTest.getNumOfTests()) {
      testing::Log::getOStream() << " test.\n"
                                 << std::flush;
    }

    if (1 < pUnitTest.getNumOfTests()) {
      testing::Log::getOStream() << " tests.\n"
                                 << std::flush;
    }
  }
  else {
    testing::Log::getOStream() << Color::RED << "[  FAILED  ] "
                               << Color::RESET
                               << pUnitTest.getNumOfFails();
    if (1 == pUnitTest.getNumOfFails()) {
      testing::Log::getOStream() << " test.\n"
                                 << std::flush;
    }

    if (1 < pUnitTest.getNumOfFails()) {
      testing::Log::getOStream() << " tests.\n"
                                 << std::flush;
    }
  }
}
<|endoftext|>


<commit_before>/*
 * Software License Agreement (BSD License)
 *
 *  Copyright (c) 2009, Willow Garage, Inc.
 *  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 Willow Garage, Inc. 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.
 *
 * $Id$
 *
 */

#include "pcl/impl/instantiate.hpp"
#include "pcl/point_types.h"
#include "pcl/filters/extract_indices.h"
#include "pcl/filters/impl/extract_indices.hpp"

//////////////////////////////////////////////////////////////////////////////////////////////
void
pcl::ExtractIndices<sensor_msgs::PointCloud2>::applyFilter (PointCloud2 &output)
{
  if (indices_->empty ())
  {
    output.width = output.height = 0;
    output.data.clear ();
    // If negative, copy all the data
    if (negative_)
      output = *input_;
    return;
  }
  if (indices_->size () == (input_->width * input_->height))
  {
    output = *input_;
    return;
  }

  // Copy the common fields (header and fields should have already been copied)
  output.is_bigendian = input_->is_bigendian;
  output.point_step   = input_->point_step;
  output.height       = 1;
  // TODO: check the output cloud and assign is_dense based on whether the points are valid or not
  output.is_dense     = false;

  if (negative_)
  {
    // Prepare a vector holding all indices
    std::vector<int> all_indices (input_->width * input_->height);
    for (size_t i = 0; i < all_indices.size (); ++i)
      all_indices[i] = i;

    std::vector<int> indices = *indices_;
    std::sort (indices.begin (), indices.end ());

    // Get the diference
    std::vector<int> remaining_indices;
    set_difference (all_indices.begin (), all_indices.end (), indices.begin (), indices.end (),
                    inserter (remaining_indices, remaining_indices.begin ()));

    // Prepare the output and copy the data
    output.width = remaining_indices.size ();
    output.data.resize (remaining_indices.size () * output.point_step);
    for (size_t i = 0; i < remaining_indices.size (); ++i)
      memcpy (&output.data[i * output.point_step], &input_->data[remaining_indices[i] * output.point_step], output.point_step);
  }
  else
  {
    // Prepare the output and copy the data
    output.width = indices_->size ();
    output.data.resize (indices_->size () * output.point_step);
    for (size_t i = 0; i < indices_->size (); ++i)
      memcpy (&output.data[i * output.point_step], &input_->data[(*indices_)[i] * output.point_step], output.point_step);
  }
  output.row_step = output.point_step * output.width;
}

PCL_INSTANTIATE(ExtractIndices, PCL_POINT_TYPES);
<commit_msg>fixing a bug in `ExtractIndices<sensor_msgs::PointCloud2>` where the negative logic was not correctly implemented (as compared to the PointCloud<T> version), per issue #319<commit_after>/*
 * Software License Agreement (BSD License)
 *
 *  Copyright (c) 2009, Willow Garage, Inc.
 *  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 Willow Garage, Inc. 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.
 *
 * $Id$
 *
 */

#include "pcl/impl/instantiate.hpp"
#include "pcl/point_types.h"
#include "pcl/filters/extract_indices.h"
#include "pcl/filters/impl/extract_indices.hpp"

//////////////////////////////////////////////////////////////////////////////////////////////
void
pcl::ExtractIndices<sensor_msgs::PointCloud2>::applyFilter (PointCloud2 &output)
{
  if (indices_->empty () || (input_->width * input_->height == 0))
  {
    output.width = output.height = 0;
    output.data.clear ();
    // If negative, copy all the data
    if (negative_)
      output = *input_;
    return;
  }
  if (indices_->size () == (input_->width * input_->height))
  {
    // If negative, then return an empty cloud
    if (negative_)
    {
      output.width = output.height = 0;
      output.data.clear ();
    }
    // else, we need to return all points
    else
      output = *input_;
    return;
  }

  // Copy the common fields (header and fields should have already been copied)
  output.is_bigendian = input_->is_bigendian;
  output.point_step   = input_->point_step;
  output.height       = 1;
  // TODO: check the output cloud and assign is_dense based on whether the points are valid or not
  output.is_dense     = false;

  if (negative_)
  {
    // Prepare a vector holding all indices
    std::vector<int> all_indices (input_->width * input_->height);
    for (size_t i = 0; i < all_indices.size (); ++i)
      all_indices[i] = i;

    std::vector<int> indices = *indices_;
    std::sort (indices.begin (), indices.end ());

    // Get the diference
    std::vector<int> remaining_indices;
    set_difference (all_indices.begin (), all_indices.end (), indices.begin (), indices.end (),
                    inserter (remaining_indices, remaining_indices.begin ()));

    // Prepare the output and copy the data
    output.width = remaining_indices.size ();
    output.data.resize (remaining_indices.size () * output.point_step);
    for (size_t i = 0; i < remaining_indices.size (); ++i)
      memcpy (&output.data[i * output.point_step], &input_->data[remaining_indices[i] * output.point_step], output.point_step);
  }
  else
  {
    // Prepare the output and copy the data
    output.width = indices_->size ();
    output.data.resize (indices_->size () * output.point_step);
    for (size_t i = 0; i < indices_->size (); ++i)
      memcpy (&output.data[i * output.point_step], &input_->data[(*indices_)[i] * output.point_step], output.point_step);
  }
  output.row_step = output.point_step * output.width;
}

PCL_INSTANTIATE(ExtractIndices, PCL_POINT_TYPES);
<|endoftext|>


<commit_before>/*
*	Odometer.cpp - Handles the gyroscope (L3G4200D) sensor of the Smartcar.
*	Version: 0.3
*	Author: Dimitris Platis (based on the bildr.org example: http://bildr.org/2011/06/l3g4200d-arduino/)
* 	License: GNU GPL v3 http://www.gnu.org/licenses/gpl-3.0.html
*/

#include "CaroloCup.h"

/* ---- GYROSCOPE (L3G4200D) ---- */
	const unsigned short Gyroscope::DEFAULT_GYRO_SAMPLING = 25;
	static const int GYRO_OFFSET = 57; //The value that is usually given by the gyroscope when not moving. Determined experimentally, adapt accordingly.
	static const float GYRO_SENSITIVITY = 0.07; //L3G4200D specific.
	static const int GYRO_THRESHOLD = 12; //Tolerance threshold. Determined experimentally, adapt accordingly.

	static const int CTRL_REG1 = 0x20;
	static const int CTRL_REG2 =  0x21;
	static const int CTRL_REG3 = 0x22;
	static const int CTRL_REG4 = 0x23;
	static const int CTRL_REG5 = 0x24;

	static const int L3G4200D_Address = 105; //gyroscope I2C address

volatile int _angularDisplacement = 0;
volatile unsigned long _prevSample = 0;

Gyroscope::Gyroscope(){
}

void Gyroscope::attach(){
	initializeGyro();
}

void Gyroscope::initMeasurement(){
	_angularDisplacement = 0;
	_prevSample = 0;
}

void Gyroscope::begin(unsigned short samplingRate){
	initMeasurement();
	_prevSample = millis();
	_samplingRate = samplingRate;
}

int Gyroscope::getAngularDisplacement(){
	return _angularDisplacement;
}

/* based on http://www.pieter-jan.com/node/7 integration algorithm */
void Gyroscope::update(){
	if (millis()- _prevSample > _samplingRate){
		float gyroRate = 0;
		int gyroValue = getGyroValues();
		short drift = GYRO_OFFSET - gyroValue;
 		if (abs(drift) > GYRO_THRESHOLD){
			gyroRate = (gyroValue - GYRO_OFFSET) * GYRO_SENSITIVITY;
		}
		unsigned long now = millis();
		_angularDisplacement += gyroRate / (1000 / (now - _prevSample));
		_prevSample = now;
	}
}

void Gyroscope::initializeGyro(){
	Wire.begin();
	setupL3G4200D(2000); // Configure L3G4200 at 2000 deg/sec. Other options: 250, 500 (NOT suggested, will have to redetermine offset)
}

/* based on the bildr.org example: http://bildr.org/2011/06/l3g4200d-arduino/ */
int Gyroscope::getGyroValues(){
	byte zMSB = readRegister(L3G4200D_Address, 0x2D);
	byte zLSB = readRegister(L3G4200D_Address, 0x2C);
	return ((zMSB << 8) | zLSB);
}

int Gyroscope::setupL3G4200D(int scale){
	//From  Jim Lindblom of Sparkfun's code

	// Enable x, y, z and turn off power down:
	writeRegister(L3G4200D_Address, CTRL_REG1, 0b00001111);

	// If you'd like to adjust/use the HPF, you can edit the line below to configure CTRL_REG2:
	writeRegister(L3G4200D_Address, CTRL_REG2, 0b00000000);

	// Configure CTRL_REG3 to generate data ready interrupt on INT2
	// No interrupts used on INT1, if you'd like to configure INT1
	// or INT2 otherwise, consult the datasheet:
	writeRegister(L3G4200D_Address, CTRL_REG3, 0b00001000);

	// CTRL_REG4 controls the full-scale range, among other things:

	if(scale == 250){
		writeRegister(L3G4200D_Address, CTRL_REG4, 0b00000000);
	}else if(scale == 500){
		writeRegister(L3G4200D_Address, CTRL_REG4, 0b00010000);
	}else{
		writeRegister(L3G4200D_Address, CTRL_REG4, 0b00110000);
	}

	// CTRL_REG5 controls high-pass filtering of outputs, use it
	// if you'd like:
	writeRegister(L3G4200D_Address, CTRL_REG5, 0b00000000);
}

void Gyroscope::writeRegister(int deviceAddress, byte address, byte val) {
	Wire.beginTransmission(deviceAddress); // start transmission to device
	Wire.write(address);       // send register address
	Wire.write(val);         // send value to write
	Wire.endTransmission();     // end transmission
}

int Gyroscope::readRegister(int deviceAddress, byte address){
	interrupts(); //sei();
	int v;
	Wire.beginTransmission(deviceAddress);
	Wire.write(address); // register to read
	Wire.endTransmission();
	Wire.requestFrom(deviceAddress, 1); // read a byte

	while(!Wire.available()) {
		//waiting
 	}

	v = Wire.read();

	return v;
}
<commit_msg>changing gyro offset<commit_after>/*
*	Odometer.cpp - Handles the gyroscope (L3G4200D) sensor of the Smartcar.
*	Version: 0.3
*	Author: Dimitris Platis (based on the bildr.org example: http://bildr.org/2011/06/l3g4200d-arduino/)
* 	License: GNU GPL v3 http://www.gnu.org/licenses/gpl-3.0.html
*/

#include "CaroloCup.h"

/* ---- GYROSCOPE (L3G4200D) ---- */
	const unsigned short Gyroscope::DEFAULT_GYRO_SAMPLING = 80;
	static const int GYRO_OFFSET = 15; //The value that is usually given by the gyroscope when not moving. Determined experimentally, adapt accordingly.
	static const float GYRO_SENSITIVITY = 0.07; //L3G4200D specific.
	static const int GYRO_THRESHOLD = 12; //Tolerance threshold. Determined experimentally, adapt accordingly.

	static const int CTRL_REG1 = 0x20;
	static const int CTRL_REG2 =  0x21;
	static const int CTRL_REG3 = 0x22;
	static const int CTRL_REG4 = 0x23;
	static const int CTRL_REG5 = 0x24;

	static const int L3G4200D_Address = 105; //gyroscope I2C address

volatile int _angularDisplacement = 0;
volatile unsigned long _prevSample = 0;

Gyroscope::Gyroscope(){
}

void Gyroscope::attach(){
	initializeGyro();
}

void Gyroscope::initMeasurement(){
	_angularDisplacement = 0;
	_prevSample = 0;
}

void Gyroscope::begin(unsigned short samplingRate){
	initMeasurement();
	_prevSample = millis();
	_samplingRate = samplingRate;
}

int Gyroscope::getAngularDisplacement(){
	return _angularDisplacement;
}

/* based on http://www.pieter-jan.com/node/7 integration algorithm */
void Gyroscope::update(){
	if (millis()- _prevSample > _samplingRate){
		float gyroRate = 0;
		int gyroValue = getGyroValues();
		short drift = GYRO_OFFSET - gyroValue;
 		if (abs(drift) > GYRO_THRESHOLD){ //if there has been a big enough drift (trying to contemplate for the noise)
			gyroRate = (gyroValue - GYRO_OFFSET) * GYRO_SENSITIVITY;
		}
		unsigned long now = millis();
		_angularDisplacement += gyroRate / (1000 / (now - _prevSample));
		_prevSample = now;
	}
}

void Gyroscope::initializeGyro(){
	Wire.begin();
	setupL3G4200D(2000); // Configure L3G4200 at 2000 deg/sec. Other options: 250, 500 (NOT suggested, will have to redetermine offset)
}

/* based on the bildr.org example: http://bildr.org/2011/06/l3g4200d-arduino/ */
int Gyroscope::getGyroValues(){
	byte zMSB = readRegister(L3G4200D_Address, 0x2D);
	byte zLSB = readRegister(L3G4200D_Address, 0x2C);
	return ((zMSB << 8) | zLSB);
}

int Gyroscope::setupL3G4200D(int scale){
	//From  Jim Lindblom of Sparkfun's code

	// Enable x, y, z and turn off power down:
	writeRegister(L3G4200D_Address, CTRL_REG1, 0b00001111);

	// If you'd like to adjust/use the HPF, you can edit the line below to configure CTRL_REG2:
	writeRegister(L3G4200D_Address, CTRL_REG2, 0b00000000);

	// Configure CTRL_REG3 to generate data ready interrupt on INT2
	// No interrupts used on INT1, if you'd like to configure INT1
	// or INT2 otherwise, consult the datasheet:
	writeRegister(L3G4200D_Address, CTRL_REG3, 0b00001000);

	// CTRL_REG4 controls the full-scale range, among other things:

	if(scale == 250){
		writeRegister(L3G4200D_Address, CTRL_REG4, 0b00000000);
	}else if(scale == 500){
		writeRegister(L3G4200D_Address, CTRL_REG4, 0b00010000);
	}else{
		writeRegister(L3G4200D_Address, CTRL_REG4, 0b00110000);
	}

	// CTRL_REG5 controls high-pass filtering of outputs, use it
	// if you'd like:
	writeRegister(L3G4200D_Address, CTRL_REG5, 0b00000000);
}

void Gyroscope::writeRegister(int deviceAddress, byte address, byte val) {
	Wire.beginTransmission(deviceAddress); // start transmission to device
	Wire.write(address);       // send register address
	Wire.write(val);         // send value to write
	Wire.endTransmission();     // end transmission
}

int Gyroscope::readRegister(int deviceAddress, byte address){
	interrupts(); //sei();
	int v;
	Wire.beginTransmission(deviceAddress);
	Wire.write(address); // register to read
	Wire.endTransmission();
	Wire.requestFrom(deviceAddress, 1); // read a byte

	while(!Wire.available()) {
		//waiting
 	}

	v = Wire.read();

	return v;
}
<|endoftext|>


<commit_before>/*  This file is part of the KDE project
    Copyright (C) 2004,2006 Matthias Kretz <kretz@kde.org>

    This program is free software; you can redistribute it and/or modify
    it under the terms of the GNU General Public License version 2
    as published by the Free Software Foundation.

    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 General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with this program; if not, write to the Free Software
    Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
    02110-1301, USA.

*/

#include "backendselection.h"

#include <kservicetypeprofile.h>
#include <dcopclient.h>
#include <kservicetypetrader.h>
#include <ksimpleconfig.h>
#include <QStringList>
#include <QListWidgetItem>
#include <kapplication.h>
#include <kicon.h>
#include <QList>

BackendSelection::BackendSelection( QWidget* parent )
	: QWidget( parent )
{
	setupUi( this );

	connect( m_select, SIGNAL( itemSelectionChanged() ),
			SLOT( selectionChanged() ) );
	//connect( m_website, SIGNAL( leftClickedURL( const QString & ) ),
			//kapp, SLOT( invokeBrowser( const QString & ) ) );
	connect( m_up, SIGNAL( clicked() ), SLOT( up() ) );
	connect( m_down, SIGNAL( clicked() ), SLOT( down() ) );
}

void BackendSelection::load()
{
	m_services.clear();
	m_select->clear();
	KServiceTypeProfile::clear();

        const KService::List offers = KServiceTypeTrader::self()->query( "PhononBackend",
			"Type == 'Service' and [X-KDE-PhononBackendInfo-InterfaceVersion] == 1" );
	// the offers are already sorted for preference
        KService::List::const_iterator it = offers.begin();
        const KService::List::const_iterator end = offers.end();
	for( ; it != end; ++it )
	{
		KService::Ptr service = *it;
		m_select->addItem( service->name() );
		m_services[ service->name() ] = service;
	}
	m_select->setItemSelected( m_select->item( 0 ), true );
}

void BackendSelection::save()
{
	// save to profilerc
	KSimpleConfig config( "profilerc" );
	QStringList grouplist = config.groupList();
	QStringList::Iterator it = grouplist.begin();
	QStringList::Iterator end = grouplist.end();
	for( ; it != end; ++it )
	{
		config.setGroup( *it );
		if( config.readEntry( "ServiceType" ) == "PhononBackend" )
			config.deleteGroup( *it );
	}
	unsigned int count = m_select->count();
	for( unsigned int i = 0; i < count; ++i )
	{
		QListWidgetItem* item = m_select->item( i );
		KService::Ptr service = m_services[ item->text() ];
		config.setGroup( "PhononBackend" + QString( " - %1" ).arg( i ) );
		config.writeEntry( "AllowAsDefault", true );
		config.writeEntry( "Application", service->storageId() );
		config.writeEntry( "GenericServiceType", "PhononBackend" );
		config.writeEntry( "Preference", count - i );
		config.writeEntry( "ServiceType", "PhononBackend" );
	}
	config.sync();
	KService::rebuildKSycoca( this );

	kapp->dcopClient()->emitDCOPSignal( "phononBackendChanged()", QByteArray() );
}

void BackendSelection::defaults()
{
	// XXX: hack, I don't know how to get the initalPreference without
	// reading it all manually
	KSimpleConfig config( "profilerc" );
	QStringList grouplist = config.groupList();
	QStringList::Iterator it = grouplist.begin();
	QStringList::Iterator end = grouplist.end();
	QStringList apps;
	QList<int> pref;
	for( ; it != end; ++it )
	{
		config.setGroup( *it );
		if( config.readEntry( "ServiceType" ) == "PhononBackend" )
		{
			apps.append( config.readEntry( "Application" ) );
			pref.append( config.readEntry( "Preference", int( 0 ) ) );
			config.deleteGroup( *it );
		}
	}
	config.sync();
	load();
	for( int i = 0; i < apps.count(); ++i )
	{
		config.setGroup( "PhononBackend" + QString( " - %1" ).arg( i ) );
		config.writeEntry( "AllowAsDefault", true );
		config.writeEntry( "Application", apps[ i ] );
		config.writeEntry( "GenericServiceType", "PhononBackend" );
		config.writeEntry( "Preference", pref[ i ] );
		config.writeEntry( "ServiceType", "PhononBackend" );
	}
	config.sync();
}

void BackendSelection::selectionChanged()
{
	KService::Ptr service;
	for( int i = 0; i < m_select->count(); ++i )
	{
		QListWidgetItem* item = m_select->item( i );
		if( m_select->isItemSelected( item ) )
		{
			service = m_services[ item->text() ];
			break;
		}
	}
	m_icon->setPixmap( KIcon( service->icon() ).pixmap( 32 ) );
	m_name->setText( service->name() );
	m_comment->setText( service->comment() );
	m_website->setText( service->property( "X-KDE-PhononBackendInfo-Website" ).toString() );
	//m_website->setURL( m_website->text() );
	m_version->setText( service->property( "X-KDE-PhononBackendInfo-Version" ).toString() );
}

void BackendSelection::up()
{
	QList<QListWidgetItem*> selectedList = m_select->selectedItems();
	foreach( QListWidgetItem* selected, selectedList )
	{
		int row = m_select->row( selected );
		if( row > 0 )
		{
			QListWidgetItem* taken = m_select->takeItem( row - 1 );
			m_select->insertItem( row, taken );
			emit changed();
		}
	}
}

void BackendSelection::down()
{
	QList<QListWidgetItem*> selectedList = m_select->selectedItems();
	foreach( QListWidgetItem* selected, selectedList )
	{
		int row = m_select->row( selected );
		if( row + 1 < m_select->count() )
		{
			QListWidgetItem* taken = m_select->takeItem( row + 1 );
			m_select->insertItem( row, taken );
			emit changed();
		}
	}
}

#include "backendselection.moc"

// vim: sw=4 ts=4 noet
<commit_msg>The progress dialog looks fancy, but there's no need to rebuild ksycoca when profilerc changes, the profile isn't stored in ksycoca. Anyway I'll provide public API for writing to profilerc.<commit_after>/*  This file is part of the KDE project
    Copyright (C) 2004,2006 Matthias Kretz <kretz@kde.org>

    This program is free software; you can redistribute it and/or modify
    it under the terms of the GNU General Public License version 2
    as published by the Free Software Foundation.

    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 General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with this program; if not, write to the Free Software
    Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
    02110-1301, USA.

*/

#include "backendselection.h"

#include <kservicetypeprofile.h>
#include <dcopclient.h>
#include <kservicetypetrader.h>
#include <ksimpleconfig.h>
#include <QStringList>
#include <QListWidgetItem>
#include <kapplication.h>
#include <kicon.h>
#include <QList>

BackendSelection::BackendSelection( QWidget* parent )
	: QWidget( parent )
{
	setupUi( this );

	connect( m_select, SIGNAL( itemSelectionChanged() ),
			SLOT( selectionChanged() ) );
	//connect( m_website, SIGNAL( leftClickedURL( const QString & ) ),
			//kapp, SLOT( invokeBrowser( const QString & ) ) );
	connect( m_up, SIGNAL( clicked() ), SLOT( up() ) );
	connect( m_down, SIGNAL( clicked() ), SLOT( down() ) );
}

void BackendSelection::load()
{
	m_services.clear();
	m_select->clear();
	KServiceTypeProfile::clear();

        const KService::List offers = KServiceTypeTrader::self()->query( "PhononBackend",
			"Type == 'Service' and [X-KDE-PhononBackendInfo-InterfaceVersion] == 1" );
	// the offers are already sorted for preference
        KService::List::const_iterator it = offers.begin();
        const KService::List::const_iterator end = offers.end();
	for( ; it != end; ++it )
	{
		KService::Ptr service = *it;
		m_select->addItem( service->name() );
		m_services[ service->name() ] = service;
	}
	m_select->setItemSelected( m_select->item( 0 ), true );
}

void BackendSelection::save()
{
	// save to profilerc
	KSimpleConfig config( "profilerc" );
	QStringList grouplist = config.groupList();
	QStringList::Iterator it = grouplist.begin();
	QStringList::Iterator end = grouplist.end();
	for( ; it != end; ++it )
	{
		config.setGroup( *it );
		if( config.readEntry( "ServiceType" ) == "PhononBackend" )
			config.deleteGroup( *it );
	}
	unsigned int count = m_select->count();
	for( unsigned int i = 0; i < count; ++i )
	{
		QListWidgetItem* item = m_select->item( i );
		KService::Ptr service = m_services[ item->text() ];
		config.setGroup( "PhononBackend" + QString( " - %1" ).arg( i ) );
		config.writeEntry( "AllowAsDefault", true );
		config.writeEntry( "Application", service->storageId() );
		config.writeEntry( "GenericServiceType", "PhononBackend" );
		config.writeEntry( "Preference", count - i );
		config.writeEntry( "ServiceType", "PhononBackend" );
	}
	config.sync();
	KServiceTypeProfile::clear();

	kapp->dcopClient()->emitDCOPSignal( "phononBackendChanged()", QByteArray() );
}

void BackendSelection::defaults()
{
	// XXX: hack, I don't know how to get the initalPreference without
	// reading it all manually
	KSimpleConfig config( "profilerc" );
	QStringList grouplist = config.groupList();
	QStringList::Iterator it = grouplist.begin();
	QStringList::Iterator end = grouplist.end();
	QStringList apps;
	QList<int> pref;
	for( ; it != end; ++it )
	{
		config.setGroup( *it );
		if( config.readEntry( "ServiceType" ) == "PhononBackend" )
		{
			apps.append( config.readEntry( "Application" ) );
			pref.append( config.readEntry( "Preference", int( 0 ) ) );
			config.deleteGroup( *it );
		}
	}
	config.sync();
	load();
	for( int i = 0; i < apps.count(); ++i )
	{
		config.setGroup( "PhononBackend" + QString( " - %1" ).arg( i ) );
		config.writeEntry( "AllowAsDefault", true );
		config.writeEntry( "Application", apps[ i ] );
		config.writeEntry( "GenericServiceType", "PhononBackend" );
		config.writeEntry( "Preference", pref[ i ] );
		config.writeEntry( "ServiceType", "PhononBackend" );
	}
	config.sync();
}

void BackendSelection::selectionChanged()
{
	KService::Ptr service;
	for( int i = 0; i < m_select->count(); ++i )
	{
		QListWidgetItem* item = m_select->item( i );
		if( m_select->isItemSelected( item ) )
		{
			service = m_services[ item->text() ];
			break;
		}
	}
	m_icon->setPixmap( KIcon( service->icon() ).pixmap( 32 ) );
	m_name->setText( service->name() );
	m_comment->setText( service->comment() );
	m_website->setText( service->property( "X-KDE-PhononBackendInfo-Website" ).toString() );
	//m_website->setURL( m_website->text() );
	m_version->setText( service->property( "X-KDE-PhononBackendInfo-Version" ).toString() );
}

void BackendSelection::up()
{
	QList<QListWidgetItem*> selectedList = m_select->selectedItems();
	foreach( QListWidgetItem* selected, selectedList )
	{
		int row = m_select->row( selected );
		if( row > 0 )
		{
			QListWidgetItem* taken = m_select->takeItem( row - 1 );
			m_select->insertItem( row, taken );
			emit changed();
		}
	}
}

void BackendSelection::down()
{
	QList<QListWidgetItem*> selectedList = m_select->selectedItems();
	foreach( QListWidgetItem* selected, selectedList )
	{
		int row = m_select->row( selected );
		if( row + 1 < m_select->count() )
		{
			QListWidgetItem* taken = m_select->takeItem( row + 1 );
			m_select->insertItem( row, taken );
			emit changed();
		}
	}
}

#include "backendselection.moc"

// vim: sw=4 ts=4 noet
<|endoftext|>


<commit_before>#include "Hierarchy.h"
#include "Application.h"
#include "Editor.h"

#include "GameObject.h"
#include "Component.h"
#include "ComponentTransform.h"
#include "ComponentLight.h"

#include "ModuleGOManager.h"
#include "LayerSystem.h"

Hierarchy::Hierarchy()
{
	active = true;
	flags |= ImGuiWindowFlags_NoResize | ImGuiWindowFlags_NoMove;
}
Hierarchy::~Hierarchy()
{}

void Hierarchy::Draw()
{
	if (!active) return;

	ImGui::SetNextWindowSize(current_size);
	ImGui::SetNextWindowPos(current_position);

	ImGui::Begin("Hierarchy", &active, flags);

	DisplayGameObjectsChilds(App->go_manager->root->GetChilds());

	if (ImGui::IsMouseHoveringWindow())
	{
		if (ImGui::IsMouseClicked(1))
		{
			ImGui::OpenPopup("HierarchyOptions");
		}
		if (ImGui::IsMouseClicked(0))// && been_selected == false)
		{
			if (setting_parent == true)
			{
				if (App->editor->selected.size() > 0)
				{
					App->editor->selected.back()->SetParent(App->go_manager->root);
				}
			}
		}
	}

	if (ImGui::BeginPopup("HierarchyOptions"))
	{
		if (ImGui::MenuItem("Copy"))
		{
			if (App->editor->selected.size() > 0)
				App->editor->Copy(App->editor->selected.back());
		}
		if (ImGui::MenuItem("Paste"))
		{
			if (App->editor->selected.size() > 0)
				App->editor->Paste(App->editor->selected.back());
			else
				App->editor->Paste(nullptr);
		}
		ImGui::Separator();
		if (ImGui::MenuItem("Duplicate"))
		{
			if (App->editor->selected.size() > 0)
				App->editor->Duplicate(App->editor->selected.back());
		}

		if (ImGui::MenuItem("Delete"))
		{
			App->editor->RemoveSelected();
		}
		ImGui::Separator();
		if (ImGui::MenuItem("Create Prefab"))
		{
			if (App->editor->selected.size() > 0)
			{
				App->resource_manager->SavePrefab(App->editor->selected.back());
			}
		}
		ImGui::Separator();
		if (ImGui::MenuItem("Create Empty"))
		{
			GameObject* game_object = (App->editor->selected.size() > 0) ? App->editor->selected.back() : nullptr;
			App->editor->SelectSingle(App->go_manager->CreateGameObject(game_object));
		}
		if (ImGui::BeginMenu("3D Object"))
		{
			if (ImGui::MenuItem("Cube"))
				App->go_manager->CreatePrimitive(PrimitiveType::P_CUBE);

			if (ImGui::MenuItem("Sphere"))
				App->go_manager->CreatePrimitive(PrimitiveType::P_SPHERE);

			if (ImGui::MenuItem("Plane"))
				App->go_manager->CreatePrimitive(PrimitiveType::P_PLANE);

			if (ImGui::MenuItem("Cylinder"))
				App->go_manager->CreatePrimitive(PrimitiveType::P_CYLINDER);

			if (ImGui::BeginMenu("Light"))
			{
				if (ImGui::MenuItem("Directional Light"))
				{
					App->go_manager->CreateLight(nullptr, DIRECTIONAL_LIGHT);
				}
				ImGui::EndMenu();
			}
			ImGui::EndMenu();
		}

		if (ImGui::MenuItem("Set Parent"))
		{
			setting_parent = true;
		}

		ImGui::EndPopup();
	}

	// Quick test for unselecting game objects when not selecting none
	int size_x = current_size.x;
	int size_y = current_size.y - ImGui::GetCursorPosY() - 10;
	ImGui::SetCursorPosX(0);
	if (ImGui::Button("test: unselect GO", ImVec2(size_x, size_y)))
	{
		App->editor->UnselectAll();
	}

	ImGui::End();
}

void Hierarchy::DisplayGameObjectsChilds(const std::vector<GameObject*>* childs)
{
	for (std::vector<GameObject*>::const_iterator object = (*childs).begin(); object != (*childs).end(); ++object)
	{
		uint flags = ImGuiTreeNodeFlags_OpenOnArrow;
		if (App->editor->IsSelected(*object))
			flags |= ImGuiTreeNodeFlags_Selected;

		if ((*object)->ChildCount() == 0)
			flags |= ImGuiTreeNodeFlags_Leaf | ImGuiTreeNodeFlags_NoTreePushOnOpen;

		bool open = ImGui::TreeNodeEx((*object)->name.data(), flags);
		bool hasChilds = (*object)->ChildCount() > 0;

		if (ImGui::IsItemHovered() && ImGui::IsMouseDoubleClicked(0))
		{
			ComponentTransform* transform = (ComponentTransform*)(*object)->GetComponent(C_TRANSFORM);
			App->camera->Center(transform->GetGlobalMatrix().TranslatePart());
		}

		if (ImGui::IsItemClicked(0) || ImGui::IsItemClicked(1))
		{
			if (setting_parent == true)
			{
				if (App->editor->selected.size() > 0)
				{
					App->editor->selected.back()->SetParent(*object);
				}
				setting_parent = false;
			}
			else
			{
				OnClickSelect(*object);
			}
		}

		if (hasChilds > 0 && open)
		{
			DisplayGameObjectsChilds((*object)->GetChilds());
			ImGui::TreePop();
		}
	}
}

void Hierarchy::OnClickSelect(GameObject* game_object)
{
	if (App->input->GetKey(SDL_SCANCODE_LSHIFT) == KEY_REPEAT || App->input->GetKey(SDL_SCANCODE_RSHIFT) == KEY_REPEAT ||
		App->input->GetKey(SDL_SCANCODE_LCTRL) == KEY_REPEAT || App->input->GetKey(SDL_SCANCODE_RCTRL) == KEY_REPEAT)
	{
		if (App->editor->IsSelected(game_object))
		{
			App->editor->Unselect(game_object);
		}
		else
		{
			App->editor->AddSelect(game_object);
		}
	}
	else
	{
		App->editor->SelectSingle(game_object);
	}
}<commit_msg>Hiding hierarchy button<commit_after>#include "Hierarchy.h"
#include "Application.h"
#include "Editor.h"

#include "GameObject.h"
#include "Component.h"
#include "ComponentTransform.h"
#include "ComponentLight.h"

#include "ModuleGOManager.h"
#include "LayerSystem.h"

Hierarchy::Hierarchy()
{
	active = true;
	flags |= ImGuiWindowFlags_NoResize | ImGuiWindowFlags_NoMove;
}
Hierarchy::~Hierarchy()
{}

void Hierarchy::Draw()
{
	if (!active) return;

	ImGui::SetNextWindowSize(current_size);
	ImGui::SetNextWindowPos(current_position);

	ImGui::Begin("Hierarchy", &active, flags);

	DisplayGameObjectsChilds(App->go_manager->root->GetChilds());

	if (ImGui::IsMouseHoveringWindow())
	{
		if (ImGui::IsMouseClicked(1))
		{
			ImGui::OpenPopup("HierarchyOptions");
		}
		if (ImGui::IsMouseClicked(0))// && been_selected == false)
		{
			if (setting_parent == true)
			{
				if (App->editor->selected.size() > 0)
				{
					App->editor->selected.back()->SetParent(App->go_manager->root);
				}
			}
		}
	}

	if (ImGui::BeginPopup("HierarchyOptions"))
	{
		if (ImGui::MenuItem("Copy"))
		{
			if (App->editor->selected.size() > 0)
				App->editor->Copy(App->editor->selected.back());
		}
		if (ImGui::MenuItem("Paste"))
		{
			if (App->editor->selected.size() > 0)
				App->editor->Paste(App->editor->selected.back());
			else
				App->editor->Paste(nullptr);
		}
		ImGui::Separator();
		if (ImGui::MenuItem("Duplicate"))
		{
			if (App->editor->selected.size() > 0)
				App->editor->Duplicate(App->editor->selected.back());
		}

		if (ImGui::MenuItem("Delete"))
		{
			App->editor->RemoveSelected();
		}
		ImGui::Separator();
		if (ImGui::MenuItem("Create Prefab"))
		{
			if (App->editor->selected.size() > 0)
			{
				App->resource_manager->SavePrefab(App->editor->selected.back());
			}
		}
		ImGui::Separator();
		if (ImGui::MenuItem("Create Empty"))
		{
			GameObject* game_object = (App->editor->selected.size() > 0) ? App->editor->selected.back() : nullptr;
			App->editor->SelectSingle(App->go_manager->CreateGameObject(game_object));
		}
		if (ImGui::BeginMenu("3D Object"))
		{
			if (ImGui::MenuItem("Cube"))
				App->go_manager->CreatePrimitive(PrimitiveType::P_CUBE);

			if (ImGui::MenuItem("Sphere"))
				App->go_manager->CreatePrimitive(PrimitiveType::P_SPHERE);

			if (ImGui::MenuItem("Plane"))
				App->go_manager->CreatePrimitive(PrimitiveType::P_PLANE);

			if (ImGui::MenuItem("Cylinder"))
				App->go_manager->CreatePrimitive(PrimitiveType::P_CYLINDER);

			if (ImGui::BeginMenu("Light"))
			{
				if (ImGui::MenuItem("Directional Light"))
				{
					App->go_manager->CreateLight(nullptr, DIRECTIONAL_LIGHT);
				}
				ImGui::EndMenu();
			}
			ImGui::EndMenu();
		}

		if (ImGui::MenuItem("Set Parent"))
		{
			setting_parent = true;
		}

		ImGui::EndPopup();
	}

	// Quick test for unselecting game objects when not selecting none
	int size_x = current_size.x;
	int size_y = current_size.y - ImGui::GetCursorPosY() - 10;
	ImGui::SetCursorPosX(0);
	if (ImGui::InvisibleButton("test: unselect GO", ImVec2(size_x, size_y)))
	{
		App->editor->UnselectAll();
	}

	ImGui::End();
}

void Hierarchy::DisplayGameObjectsChilds(const std::vector<GameObject*>* childs)
{
	for (std::vector<GameObject*>::const_iterator object = (*childs).begin(); object != (*childs).end(); ++object)
	{
		uint flags = ImGuiTreeNodeFlags_OpenOnArrow;
		if (App->editor->IsSelected(*object))
			flags |= ImGuiTreeNodeFlags_Selected;

		if ((*object)->ChildCount() == 0)
			flags |= ImGuiTreeNodeFlags_Leaf | ImGuiTreeNodeFlags_NoTreePushOnOpen;

		bool open = ImGui::TreeNodeEx((*object)->name.data(), flags);
		bool hasChilds = (*object)->ChildCount() > 0;

		if (ImGui::IsItemHovered() && ImGui::IsMouseDoubleClicked(0))
		{
			ComponentTransform* transform = (ComponentTransform*)(*object)->GetComponent(C_TRANSFORM);
			App->camera->Center(transform->GetGlobalMatrix().TranslatePart());
		}

		if (ImGui::IsItemClicked(0) || ImGui::IsItemClicked(1))
		{
			if (setting_parent == true)
			{
				if (App->editor->selected.size() > 0)
				{
					App->editor->selected.back()->SetParent(*object);
				}
				setting_parent = false;
			}
			else
			{
				OnClickSelect(*object);
			}
		}

		if (hasChilds > 0 && open)
		{
			DisplayGameObjectsChilds((*object)->GetChilds());
			ImGui::TreePop();
		}
	}
}

void Hierarchy::OnClickSelect(GameObject* game_object)
{
	if (App->input->GetKey(SDL_SCANCODE_LSHIFT) == KEY_REPEAT || App->input->GetKey(SDL_SCANCODE_RSHIFT) == KEY_REPEAT ||
		App->input->GetKey(SDL_SCANCODE_LCTRL) == KEY_REPEAT || App->input->GetKey(SDL_SCANCODE_RCTRL) == KEY_REPEAT)
	{
		if (App->editor->IsSelected(game_object))
		{
			App->editor->Unselect(game_object);
		}
		else
		{
			App->editor->AddSelect(game_object);
		}
	}
	else
	{
		App->editor->SelectSingle(game_object);
	}
}<|endoftext|>


<commit_before>//===--- DebuggerTestingTransform.cpp - Transform for debugger testing ----===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2018 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
///
/// \file This transform inserts instrumentation which the debugger can use to
/// test its expression evaluation facilities.
///
//===----------------------------------------------------------------------===//

#include "CodeSynthesis.h"
#include "swift/AST/ASTContext.h"
#include "swift/AST/ASTNode.h"
#include "swift/AST/ASTWalker.h"
#include "swift/AST/Decl.h"
#include "swift/AST/DeclContext.h"
#include "swift/AST/Expr.h"
#include "swift/AST/Module.h"
#include "swift/AST/ParameterList.h"
#include "swift/AST/SourceFile.h"
#include "swift/AST/Stmt.h"
#include "swift/Subsystems.h"

#include "TypeChecker.h"

using namespace swift;

namespace {

/// Find available closure discriminators.
///
/// The parser typically takes care of assigning unique discriminators to
/// closures, but the parser is unavailable during semantic analysis.
class DiscriminatorFinder : public ASTWalker {
  unsigned NextDiscriminator = 0;

public:
  Expr *walkToExprPost(Expr *E) override {
    auto *ACE = dyn_cast<AbstractClosureExpr>(E);
    if (!ACE)
      return E;

    unsigned Discriminator = ACE->getDiscriminator();
    assert(Discriminator != AbstractClosureExpr::InvalidDiscriminator &&
           "Existing closures should have valid discriminators");
    if (Discriminator >= NextDiscriminator)
      NextDiscriminator = Discriminator + 1;
    return E;
  }

  // Get the next available closure discriminator.
  unsigned getNextDiscriminator() {
    if (NextDiscriminator == AbstractClosureExpr::InvalidDiscriminator)
      llvm::report_fatal_error("Out of valid closure discriminators");
    return NextDiscriminator++;
  }
};

/// Instrument decls with sanity-checks which the debugger can evaluate.
class DebuggerTestingTransform : public ASTWalker {
  ASTContext &Ctx;
  DiscriminatorFinder &DF;
  std::vector<DeclContext *> LocalDeclContextStack;
  const DeclNameRef StringForPrintObjectName;
  const DeclNameRef DebuggerTestingCheckExpectName;

public:
  DebuggerTestingTransform(ASTContext &Ctx, DiscriminatorFinder &DF)
      : Ctx(Ctx), DF(DF),
        StringForPrintObjectName(Ctx.getIdentifier("_stringForPrintObject")),
        DebuggerTestingCheckExpectName(
            Ctx.getIdentifier("_debuggerTestingCheckExpect")) {}

  bool walkToDeclPre(Decl *D) override {
    pushLocalDeclContext(D);

    // Skip implicit decls, because the debugger isn't used to step through
    // these.
    if (D->isImplicit())
      return false;

    // Whitelist the kinds of decls to transform.
    // TODO: Expand the set of decls visited here.
    if (auto *FD = dyn_cast<AbstractFunctionDecl>(D))
      return FD->getBody();
    if (auto *TLCD = dyn_cast<TopLevelCodeDecl>(D))
      return TLCD->getBody();
    if (isa<NominalTypeDecl>(D))
      return true;
    return false;
  }

  bool walkToDeclPost(Decl *D) override {
    popLocalDeclContext(D);
    return true;
  }

  std::pair<bool, Expr *> walkToExprPre(Expr *E) override {
    pushLocalDeclContext(E);

    // Whitelist the kinds of exprs to transform.
    // TODO: Expand the set of exprs visited here.
    if (auto *AE = dyn_cast<AssignExpr>(E))
      return insertCheckExpect(AE, AE->getDest());

    return {true, E};
  }

  Expr *walkToExprPost(Expr *E) override {
    popLocalDeclContext(E);
    return E;
  }

private:
  /// Return N as a local DeclContext if possible, or return nullptr.
  DeclContext *getLocalDeclContext(ASTNode N) const {
    DeclContext *DC = N.getAsDeclContext();
    return (DC && DC->isLocalContext()) ? DC : nullptr;
  }

  /// If N is a local DeclContext, push it onto the context stack.
  void pushLocalDeclContext(ASTNode N) {
    if (auto *LDC = getLocalDeclContext(N))
      LocalDeclContextStack.push_back(LDC);
  }

  /// If N is a local DeclContext, pop it off the context stack.
  void popLocalDeclContext(ASTNode N) {
    if (getLocalDeclContext(N))
      LocalDeclContextStack.pop_back();
  }

  /// Get the current local DeclContext. This is used to create closures in the
  /// right context.
  DeclContext *getCurrentDeclContext() const {
    assert(!LocalDeclContextStack.empty() && "Missing decl context");
    return LocalDeclContextStack.back();
  }

  /// Try to extract a DeclRefExpr or MemberRefExpr from the expression.
  Expr *extractDeclOrMemberRef(Expr *E) {
    while (!isa<DeclRefExpr>(E) && !isa<MemberRefExpr>(E)) {
      // TODO: Try more ways to extract interesting decl refs.
      if (auto *Subscript = dyn_cast<SubscriptExpr>(E))
        E = Subscript->getBase();
      else if (auto *InOut = dyn_cast<InOutExpr>(E))
        E = InOut->getSubExpr();
      else if (auto *MemberRef = dyn_cast<MemberRefExpr>(E))
        E = MemberRef->getBase();
      else
        return nullptr;
    }
    return E;
  }

  /// Attempt to create a functionally-equivalent replacement for OriginalExpr,
  /// given that DstExpr identifies the target of some mutating update, and that
  /// DstExpr is a subexpression of OriginalExpr.
  ///
  /// The return value contains 1) a flag indicating whether or not to
  /// recursively transform the children of the transformed expression, and 2)
  /// the transformed expression itself.
  std::pair<bool, Expr *> insertCheckExpect(Expr *OriginalExpr, Expr *DstExpr) {
    auto *DstRef = extractDeclOrMemberRef(DstExpr);
    if (!DstRef)
      return {true, OriginalExpr};

    ValueDecl *DstDecl;
    if (auto *DRE = dyn_cast<DeclRefExpr>(DstRef))
      DstDecl = DRE->getDecl();
    else {
      auto *MRE = cast<MemberRefExpr>(DstRef);
      DstDecl = MRE->getMember().getDecl();
    }
    if (!DstDecl->hasName())
      return {true, OriginalExpr};

    // Don't capture variables which aren't default-initialized.
    if (auto *VD = dyn_cast<VarDecl>(DstDecl))
      if (!VD->isParentInitialized() &&
          !(isa<ParamDecl>(VD) &&
            cast<ParamDecl>(VD)->isInOut()))
        return {true, OriginalExpr};

    // Rewrite the original expression into this:
    // call
    //   closure {
    //     $OriginalExpr
    //     checkExpect("$Varname", _stringForPrintObject($Varname))
    //   }

    // Create "$Varname".
    llvm::SmallString<256> DstNameBuf;
    const DeclName DstDN = DstDecl->getName();
    StringRef DstName = Ctx.AllocateCopy(DstDN.getString(DstNameBuf));
    assert(!DstName.empty() && "Varname must be non-empty");
    Expr *Varname = new (Ctx) StringLiteralExpr(DstName, SourceRange());
    Varname->setImplicit(true);

    // Create _stringForPrintObject($Varname).
    auto *PODeclRef = new (Ctx)
        UnresolvedDeclRefExpr(StringForPrintObjectName,
                              DeclRefKind::Ordinary, DeclNameLoc());
    auto *POArgList = ArgumentList::forImplicitUnlabeled(Ctx, {DstRef});
    auto *POCall = CallExpr::createImplicit(Ctx, PODeclRef, POArgList);
    POCall->setThrows(false);

    // Create the call to checkExpect.
    UnresolvedDeclRefExpr *CheckExpectDRE = new (Ctx)
        UnresolvedDeclRefExpr(DebuggerTestingCheckExpectName,
                              DeclRefKind::Ordinary, DeclNameLoc());
    auto *CheckArgList =
        ArgumentList::forImplicitUnlabeled(Ctx, {Varname, POCall});
    auto *CheckExpectExpr =
        CallExpr::createImplicit(Ctx, CheckExpectDRE, CheckArgList);
    CheckExpectExpr->setThrows(false);

    // Create the closure.
    auto *Params = ParameterList::createEmpty(Ctx);
    auto *Closure = new (Ctx)
        ClosureExpr(DeclAttributes(), SourceRange(), nullptr, Params,
                    SourceLoc(), SourceLoc(),
                    SourceLoc(), SourceLoc(), nullptr,
                    DF.getNextDiscriminator(), getCurrentDeclContext());
    Closure->setImplicit(true);

    // TODO: Save and return the value of $OriginalExpr.
    ASTNode ClosureElements[] = {OriginalExpr, CheckExpectExpr};
    auto *ClosureBody = BraceStmt::create(Ctx, SourceLoc(), ClosureElements,
                                          SourceLoc(), /*Implicit=*/true);
    Closure->setBody(ClosureBody, /*isSingleExpression=*/false);

    // Call the closure.
    auto *ClosureCall = CallExpr::createImplicitEmpty(Ctx, Closure);
    ClosureCall->setThrows(false);

    // TODO: typeCheckExpression() seems to assign types to everything here,
    // but may not be sufficient in some cases.
    Expr *FinalExpr = ClosureCall;
    if (!TypeChecker::typeCheckExpression(FinalExpr, getCurrentDeclContext(),
                                          /*contextualInfo=*/{}))
      llvm::report_fatal_error("Could not type-check instrumentation");

    // Captures have to be computed after the closure is type-checked. This
    // ensures that the type checker can infer <noescape> for captured values.
    TypeChecker::computeCaptures(Closure);

    return {false, FinalExpr};
  }
};

} // end anonymous namespace

void swift::performDebuggerTestingTransform(SourceFile &SF) {
  // Walk over all decls in the file to find the next available closure
  // discriminator.
  DiscriminatorFinder DF;
  for (Decl *D : SF.getTopLevelDecls())
    D->walk(DF);

  // Instrument the decls with checkExpect() sanity-checks.
  for (Decl *D : SF.getTopLevelDecls()) {
    DebuggerTestingTransform Transform{D->getASTContext(), DF};
    D->walk(Transform);
    swift::verify(D);
  }
}
<commit_msg>[Sema] DebuggerTestingTransform: avoid re-using AST nodes in generated code<commit_after>//===--- DebuggerTestingTransform.cpp - Transform for debugger testing ----===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2018 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
///
/// \file This transform inserts instrumentation which the debugger can use to
/// test its expression evaluation facilities.
///
//===----------------------------------------------------------------------===//

#include "CodeSynthesis.h"
#include "swift/AST/ASTContext.h"
#include "swift/AST/ASTNode.h"
#include "swift/AST/ASTWalker.h"
#include "swift/AST/Decl.h"
#include "swift/AST/DeclContext.h"
#include "swift/AST/Expr.h"
#include "swift/AST/Module.h"
#include "swift/AST/ParameterList.h"
#include "swift/AST/SourceFile.h"
#include "swift/AST/Stmt.h"
#include "swift/Subsystems.h"

#include "TypeChecker.h"

using namespace swift;

namespace {

/// Find available closure discriminators.
///
/// The parser typically takes care of assigning unique discriminators to
/// closures, but the parser is unavailable during semantic analysis.
class DiscriminatorFinder : public ASTWalker {
  unsigned NextDiscriminator = 0;

public:
  Expr *walkToExprPost(Expr *E) override {
    auto *ACE = dyn_cast<AbstractClosureExpr>(E);
    if (!ACE)
      return E;

    unsigned Discriminator = ACE->getDiscriminator();
    assert(Discriminator != AbstractClosureExpr::InvalidDiscriminator &&
           "Existing closures should have valid discriminators");
    if (Discriminator >= NextDiscriminator)
      NextDiscriminator = Discriminator + 1;
    return E;
  }

  // Get the next available closure discriminator.
  unsigned getNextDiscriminator() {
    if (NextDiscriminator == AbstractClosureExpr::InvalidDiscriminator)
      llvm::report_fatal_error("Out of valid closure discriminators");
    return NextDiscriminator++;
  }
};

/// Instrument decls with sanity-checks which the debugger can evaluate.
class DebuggerTestingTransform : public ASTWalker {
  ASTContext &Ctx;
  DiscriminatorFinder &DF;
  std::vector<DeclContext *> LocalDeclContextStack;
  const DeclNameRef StringForPrintObjectName;
  const DeclNameRef DebuggerTestingCheckExpectName;

public:
  DebuggerTestingTransform(ASTContext &Ctx, DiscriminatorFinder &DF)
      : Ctx(Ctx), DF(DF),
        StringForPrintObjectName(Ctx.getIdentifier("_stringForPrintObject")),
        DebuggerTestingCheckExpectName(
            Ctx.getIdentifier("_debuggerTestingCheckExpect")) {}

  bool walkToDeclPre(Decl *D) override {
    pushLocalDeclContext(D);

    // Skip implicit decls, because the debugger isn't used to step through
    // these.
    if (D->isImplicit())
      return false;

    // Whitelist the kinds of decls to transform.
    // TODO: Expand the set of decls visited here.
    if (auto *FD = dyn_cast<AbstractFunctionDecl>(D))
      return FD->getBody();
    if (auto *TLCD = dyn_cast<TopLevelCodeDecl>(D))
      return TLCD->getBody();
    if (isa<NominalTypeDecl>(D))
      return true;
    return false;
  }

  bool walkToDeclPost(Decl *D) override {
    popLocalDeclContext(D);
    return true;
  }

  std::pair<bool, Expr *> walkToExprPre(Expr *E) override {
    pushLocalDeclContext(E);

    // Whitelist the kinds of exprs to transform.
    // TODO: Expand the set of exprs visited here.
    if (auto *AE = dyn_cast<AssignExpr>(E))
      return insertCheckExpect(AE, AE->getDest());

    return {true, E};
  }

  Expr *walkToExprPost(Expr *E) override {
    popLocalDeclContext(E);
    return E;
  }

private:
  /// Return N as a local DeclContext if possible, or return nullptr.
  DeclContext *getLocalDeclContext(ASTNode N) const {
    DeclContext *DC = N.getAsDeclContext();
    return (DC && DC->isLocalContext()) ? DC : nullptr;
  }

  /// If N is a local DeclContext, push it onto the context stack.
  void pushLocalDeclContext(ASTNode N) {
    if (auto *LDC = getLocalDeclContext(N))
      LocalDeclContextStack.push_back(LDC);
  }

  /// If N is a local DeclContext, pop it off the context stack.
  void popLocalDeclContext(ASTNode N) {
    if (getLocalDeclContext(N))
      LocalDeclContextStack.pop_back();
  }

  /// Get the current local DeclContext. This is used to create closures in the
  /// right context.
  DeclContext *getCurrentDeclContext() const {
    assert(!LocalDeclContextStack.empty() && "Missing decl context");
    return LocalDeclContextStack.back();
  }

  /// Try to extract a DeclRefExpr or MemberRefExpr from the expression.
  Expr *extractDeclOrMemberRef(Expr *E) {
    while (!isa<DeclRefExpr>(E) && !isa<MemberRefExpr>(E)) {
      // TODO: Try more ways to extract interesting decl refs.
      if (auto *Subscript = dyn_cast<SubscriptExpr>(E))
        E = Subscript->getBase();
      else if (auto *InOut = dyn_cast<InOutExpr>(E))
        E = InOut->getSubExpr();
      else if (auto *MemberRef = dyn_cast<MemberRefExpr>(E))
        E = MemberRef->getBase();
      else
        return nullptr;
    }
    return E;
  }

  /// Attempt to create a functionally-equivalent replacement for OriginalExpr,
  /// given that DstExpr identifies the target of some mutating update, and that
  /// DstExpr is a subexpression of OriginalExpr.
  ///
  /// The return value contains 1) a flag indicating whether or not to
  /// recursively transform the children of the transformed expression, and 2)
  /// the transformed expression itself.
  std::pair<bool, Expr *> insertCheckExpect(Expr *OriginalExpr, Expr *DstExpr) {
    auto *DstRef = extractDeclOrMemberRef(DstExpr);
    if (!DstRef)
      return {true, OriginalExpr};

    ValueDecl *DstDecl;
    if (auto *DRE = dyn_cast<DeclRefExpr>(DstRef))
      DstDecl = DRE->getDecl();
    else {
      auto *MRE = cast<MemberRefExpr>(DstRef);
      DstDecl = MRE->getMember().getDecl();
    }
    if (!DstDecl->hasName())
      return {true, OriginalExpr};

    // Don't capture variables which aren't default-initialized.
    if (auto *VD = dyn_cast<VarDecl>(DstDecl))
      if (!VD->isParentInitialized() &&
          !(isa<ParamDecl>(VD) &&
            cast<ParamDecl>(VD)->isInOut()))
        return {true, OriginalExpr};

    // Rewrite the original expression into this:
    // call
    //   closure {
    //     $OriginalExpr
    //     checkExpect("$Varname", _stringForPrintObject($Varname))
    //   }

    // Create "$Varname".
    llvm::SmallString<256> DstNameBuf;
    const DeclName DstDN = DstDecl->getName();
    StringRef DstName = Ctx.AllocateCopy(DstDN.getString(DstNameBuf));
    assert(!DstName.empty() && "Varname must be non-empty");
    Expr *Varname = new (Ctx) StringLiteralExpr(DstName, SourceRange());
    Varname->setImplicit(true);

    // Create _stringForPrintObject($Varname).
    auto *PODeclRef = new (Ctx)
        UnresolvedDeclRefExpr(StringForPrintObjectName,
                              DeclRefKind::Ordinary, DeclNameLoc());

    std::function<DeclRefExpr *(DeclRefExpr *)> cloneDeclRef =
        [&](DeclRefExpr *DRE) {
          auto *ref = new (Ctx) DeclRefExpr(
              DRE->getDeclRef(),
              /*Loc=*/DeclNameLoc(),
              /*Implicit=*/true, DRE->getAccessSemantics(), DRE->getType());

          if (auto hopTarget = DRE->isImplicitlyAsync())
            ref->setImplicitlyAsync(*hopTarget);

          ref->setImplicitlyThrows(DRE->isImplicitlyThrows());

          return ref;
        };

    std::function<MemberRefExpr *(MemberRefExpr *)> cloneMemberRef =
        [&](MemberRefExpr *M) {
          auto *base = M->getBase();

          if (auto *DRE = dyn_cast<DeclRefExpr>(base))
            base = cloneDeclRef(DRE);
          else if (auto *M = dyn_cast<MemberRefExpr>(base))
            base = cloneMemberRef(M);

          auto *ref = new (Ctx)
              MemberRefExpr(base, /*dotLoc=*/SourceLoc(), M->getDecl(),
                            /*loc=*/DeclNameLoc(),
                            /*Implicit=*/true, M->getAccessSemantics());
          ref->setType(M->getType());

          return ref;
        };

    // Let's make a copy of either decl or member ref without source
    // information. It's invalid to have decl reference expressions
    // reused, each reference should get a fresh expression.
    if (auto *DRE = dyn_cast<DeclRefExpr>(DstRef)) {
      DstRef = cloneDeclRef(DRE);
    } else {
      DstRef = cloneMemberRef(cast<MemberRefExpr>(DstRef));
    }

    auto *POArgList = ArgumentList::forImplicitUnlabeled(Ctx, {DstRef});
    auto *POCall = CallExpr::createImplicit(Ctx, PODeclRef, POArgList);
    POCall->setThrows(false);

    // Create the call to checkExpect.
    UnresolvedDeclRefExpr *CheckExpectDRE = new (Ctx)
        UnresolvedDeclRefExpr(DebuggerTestingCheckExpectName,
                              DeclRefKind::Ordinary, DeclNameLoc());
    auto *CheckArgList =
        ArgumentList::forImplicitUnlabeled(Ctx, {Varname, POCall});
    auto *CheckExpectExpr =
        CallExpr::createImplicit(Ctx, CheckExpectDRE, CheckArgList);
    CheckExpectExpr->setThrows(false);

    // Create the closure.
    auto *Params = ParameterList::createEmpty(Ctx);
    auto *Closure = new (Ctx)
        ClosureExpr(DeclAttributes(), SourceRange(), nullptr, Params,
                    SourceLoc(), SourceLoc(),
                    SourceLoc(), SourceLoc(), nullptr,
                    DF.getNextDiscriminator(), getCurrentDeclContext());
    Closure->setImplicit(true);

    // TODO: Save and return the value of $OriginalExpr.
    ASTNode ClosureElements[] = {OriginalExpr, CheckExpectExpr};
    auto *ClosureBody = BraceStmt::create(Ctx, SourceLoc(), ClosureElements,
                                          SourceLoc(), /*Implicit=*/true);
    Closure->setBody(ClosureBody, /*isSingleExpression=*/false);

    // Call the closure.
    auto *ClosureCall = CallExpr::createImplicitEmpty(Ctx, Closure);
    ClosureCall->setThrows(false);

    // TODO: typeCheckExpression() seems to assign types to everything here,
    // but may not be sufficient in some cases.
    Expr *FinalExpr = ClosureCall;
    if (!TypeChecker::typeCheckExpression(FinalExpr, getCurrentDeclContext(),
                                          /*contextualInfo=*/{}))
      llvm::report_fatal_error("Could not type-check instrumentation");

    // Captures have to be computed after the closure is type-checked. This
    // ensures that the type checker can infer <noescape> for captured values.
    TypeChecker::computeCaptures(Closure);

    return {false, FinalExpr};
  }
};

} // end anonymous namespace

void swift::performDebuggerTestingTransform(SourceFile &SF) {
  // Walk over all decls in the file to find the next available closure
  // discriminator.
  DiscriminatorFinder DF;
  for (Decl *D : SF.getTopLevelDecls())
    D->walk(DF);

  // Instrument the decls with checkExpect() sanity-checks.
  for (Decl *D : SF.getTopLevelDecls()) {
    DebuggerTestingTransform Transform{D->getASTContext(), DF};
    D->walk(Transform);
    swift::verify(D);
  }
}
<|endoftext|>


<commit_before>//===-- MipsTargetMachine.cpp - Define TargetMachine for Mips -------------===//
//
//                     The LLVM Compiler Infrastructure
//
// This file was developed by Bruno Cardoso Lopes and is distributed under the
// University of Illinois Open Source License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// Implements the info about Mips target spec.
//
//===----------------------------------------------------------------------===//

#include "Mips.h"
#include "MipsTargetAsmInfo.h"
#include "MipsTargetMachine.h"
#include "llvm/Module.h"
#include "llvm/PassManager.h"
#include "llvm/Target/TargetMachineRegistry.h"
using namespace llvm;

namespace {
  // Register the target.
  RegisterTarget<MipsTargetMachine> X("mips", "  Mips");
}

const TargetAsmInfo *MipsTargetMachine::
createTargetAsmInfo() const
{
  return new MipsTargetAsmInfo(*this);
}

// DataLayout --> Big-endian, 32-bit pointer/ABI/alignment
// FrameInfo  --> StackGrowsDown, 8 bytes aligned, LOA : -4 (Ra : 0)
MipsTargetMachine::
MipsTargetMachine(const Module &M, const std::string &FS):
  Subtarget(*this, M, FS), DataLayout("E-p:32:32:32"),
  InstrInfo(*this), FrameInfo(TargetFrameInfo::StackGrowsDown, 8, -4),
  TLInfo(*this) {}

// return 0 and must specify -march to gen MIPS code.
unsigned MipsTargetMachine::
getModuleMatchQuality(const Module &M) {
  // We strongly match "mips-*".
  std::string TT = M.getTargetTriple();
  if (TT.size() >= 5 && std::string(TT.begin(), TT.begin()+5) == "mips-")
    return 20;
  // If the target triple is something non-mips, we don't match.
  if (!TT.empty()) return 0;

  return 0;
}

// Install an instruction selector pass using
// the ISelDag to gen Mips code.
bool MipsTargetMachine::
addInstSelector(FunctionPassManager &PM, bool Fast)
{
  PM.add(createMipsISelDag(*this));
  return false;
}

// Implemented by targets that want to run passes immediately before
// machine code is emitted. return true if -print-machineinstrs should
// print out the code after the passes.
// TODO: Delay slot must be implemented here.
bool MipsTargetMachine::
addPreEmitPass(FunctionPassManager &PM, bool Fast)
{
  return false;
}

// Implements the AssemblyEmitter for the target. Must return
// true if AssemblyEmitter is supported
bool MipsTargetMachine::
addAssemblyEmitter(FunctionPassManager &PM, bool Fast,
                   std::ostream &Out)
{
  // Output assembly language.
  PM.add(createMipsCodePrinterPass(Out, *this));
  return false;
}
<commit_msg>Now that stack is represented the right way, LOA starts at 0<commit_after>//===-- MipsTargetMachine.cpp - Define TargetMachine for Mips -------------===//
//
//                     The LLVM Compiler Infrastructure
//
// This file was developed by Bruno Cardoso Lopes and is distributed under the
// University of Illinois Open Source License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// Implements the info about Mips target spec.
//
//===----------------------------------------------------------------------===//

#include "Mips.h"
#include "MipsTargetAsmInfo.h"
#include "MipsTargetMachine.h"
#include "llvm/Module.h"
#include "llvm/PassManager.h"
#include "llvm/Target/TargetMachineRegistry.h"
using namespace llvm;

namespace {
  // Register the target.
  RegisterTarget<MipsTargetMachine> X("mips", "  Mips");
}

const TargetAsmInfo *MipsTargetMachine::
createTargetAsmInfo() const
{
  return new MipsTargetAsmInfo(*this);
}

// DataLayout --> Big-endian, 32-bit pointer/ABI/alignment
//
// FrameInfo  --> StackGrowsDown, 8 bytes aligned,
//                LOA : 0
MipsTargetMachine::
MipsTargetMachine(const Module &M, const std::string &FS):
  Subtarget(*this, M, FS), DataLayout("E-p:32:32:32"),
  InstrInfo(*this), FrameInfo(TargetFrameInfo::StackGrowsDown, 8, 0),
  TLInfo(*this) {}

// return 0 and must specify -march to gen MIPS code.
unsigned MipsTargetMachine::
getModuleMatchQuality(const Module &M)
{
  // We strongly match "mips-*".
  std::string TT = M.getTargetTriple();
  if (TT.size() >= 5 && std::string(TT.begin(), TT.begin()+5) == "mips-")
    return 20;

  return 0;
}

// Install an instruction selector pass using
// the ISelDag to gen Mips code.
bool MipsTargetMachine::
addInstSelector(FunctionPassManager &PM, bool Fast)
{
  PM.add(createMipsISelDag(*this));
  return false;
}

// Implemented by targets that want to run passes immediately before
// machine code is emitted. return true if -print-machineinstrs should
// print out the code after the passes.
// TODO: Delay slot must be implemented here.
bool MipsTargetMachine::
addPreEmitPass(FunctionPassManager &PM, bool Fast)
{
  return false;
}

// Implements the AssemblyEmitter for the target. Must return
// true if AssemblyEmitter is supported
bool MipsTargetMachine::
addAssemblyEmitter(FunctionPassManager &PM, bool Fast,
                   std::ostream &Out)
{
  // Output assembly language.
  PM.add(createMipsCodePrinterPass(Out, *this));
  return false;
}
<|endoftext|>


<commit_before># include "particle-functions.h"
# include <application.h>

extern WeatherData weather;

void WeatherData :: message(int data)     // defined outside class definition
{
 Serial.print("Timestamp: "); Serial.println(_weatherTime);
 Serial.print("Temp (F): "); Serial.println(_greenhouseTemp);
 Serial.print("Humidity (%): "); Serial.println(_greenhouseHumidity);
}

void WeatherData :: weatherData()
{
    _weatherTime = 0;
 _greenhouseTemp = 0;
 _greenhouseHumidity = 0;
 _backupGreenhouseTemp = 0;
 _backupGreenhouseHumidity = 0;
 _outsideTemp = 0;
 _outsideHumidity = 0;
 _high = 0;
 _low = 0;
}

void WeatherData :: weatherData(unsigned int weatherTime, int greenhouseTemp,int greenhouseHumidity,
                                int backupGreenhouseTemp, int backupGreenhouseHumidity,int outsideTemp,
                                int outsideHumidity, int high, int low)
 {
 _weatherTime = weatherTime;
 _greenhouseTemp = greenhouseTemp;
 _greenhouseHumidity = greenhouseHumidity;
 _backupGreenhouseTemp = backupGreenhouseTemp;
 _backupGreenhouseHumidity = backupGreenhouseHumidity;
 _outsideTemp = outsideTemp;
 _outsideHumidity = outsideHumidity;
 _high = high;
 _low = low;
 }

void WeatherData :: init()
{
 Spark.function("ghData", greenhouseData);
}

int greenhouseData(String data)
    {

    //Expected parameters in CSV format
    // 1. Unix time stamp
    // 2. current greenhouse temperature
    // 3. current greenhouse humidity

    char copyStr[64];
    data.toCharArray(copyStr,64);
    char *p = strtok(copyStr, ",");

    weather.weatherTime = atoi(p);
    p = strtok(NULL,",");
    weather.greenhouseTemp = atoi(p);
    p = strtok(NULL,",");
    weather.greenhouseHumidity = atoi(p);

return 1;
}

<commit_msg>Update particle-functions.cpp<commit_after># include "particle-functions.h"
# include <application.h>

extern WeatherData weather;

void WeatherData :: message(int data)     // defined outside class definition
{
 Serial.print("Timestamp: "); Serial.println(_weatherTime);
 Serial.print("Temp (F): "); Serial.println(_greenhouseTemp);
 Serial.print("Humidity (%): "); Serial.println(_greenhouseHumidity);
}

void WeatherData :: weatherData()
{
    _weatherTime = 0;
 _greenhouseTemp = 0;
 _greenhouseHumidity = 0;
 _backupGreenhouseTemp = 0;
 _backupGreenhouseHumidity = 0;
 _outsideTemp = 0;
 _outsideHumidity = 0;
  _solar = 0;
 _high = 0;
 _low = 0;
}

void WeatherData :: weatherData(unsigned int weatherTime, int greenhouseTemp,int greenhouseHumidity,
                                int backupGreenhouseTemp, int backupGreenhouseHumidity,int outsideTemp,
                                int outsideHumidity, int solar, int high, int low)
 {
 _weatherTime = weatherTime;
 _greenhouseTemp = greenhouseTemp;
 _greenhouseHumidity = greenhouseHumidity;
 _backupGreenhouseTemp = backupGreenhouseTemp;
 _backupGreenhouseHumidity = backupGreenhouseHumidity;
 _outsideTemp = outsideTemp;
 _outsideHumidity = outsideHumidity;
  _solar = solar;
 _high = high;
 _low = low;
 }

void WeatherData :: init()
{
 Spark.function("ghData", greenhouseData);
}

int greenhouseData(String data)
    {

    //Expected parameters in CSV format
    // 1. Unix time stamp
    // 2. current greenhouse temperature
    // 3. current greenhouse humidity
    // 4. backup sensor current greenhouse temperature
    // 5. backup sensor current greenhouse humidity
    // 6. current outside temperature
    // 7. current outside humidity
    // 8. solar radiation
    // 9. forecast high
    // 10. forecast low

    char copyStr[64];
    data.toCharArray(copyStr,64);
    char *p = strtok(copyStr, ",");

    unsigned int weatherTime = atoi(p);
    p = strtok(NULL,",");
    int greenhouseTemp = atoi(p);
    p = strtok(NULL,",");
    int greenhouseHumidity = atoi(p);
    p = strtok(NULL,",");
    int backupGreenhouseTemp = atoi(p);
    p = strtok(NULL,",");
    int backupGreenhouseHumidity = atoi(p);
    p = strtok(NULL,",");
    int outsideTemp = atoi(p);
    p = strtok(NULL,",");
    int outsideHumidity = atoi(p);
    p = strtok(NULL,",");
    int solar = atoi(p);
    p = strtok(NULL,",");
    int high = atoi(p);
    p = strtok(NULL,",");
    int low = atoi(p);

    weather.weatherData(weatherTime, greenhouseTemp, greenhouseHumidity, backupGreenhouseTemp,
                        backupGreenhouseHumidity, outsideTemp, outsideHumidity, solar, high, low);

return 1;
}

<|endoftext|>


<commit_before>#include "thermistor-library.h"

Thermistor::Thermistor(int pin, int resistor) {
	_pin = pin;
	_resistor = resistor;
}

void Thermistor::begin(void) {
	pinMode(_pin, INPUT);
}

int Thermistor::getTempRaw(bool smooth=false) {
	delay(1);

	if(smooth==true) {
		int total = 0;

		for(int i=0; i<100; i++) {
			total += analogRead(_pin);
			delay(1);
		}

		_temp_raw = total/100;
	} else
		_temp_raw = analogRead(_pin);

	return _temp_raw;
}

float Thermistor::getTempK(bool smooth=false) {
	_temp_raw = getTempRaw(smooth);

	_temp_k = log(((40960000/_temp_raw) - _resistor));
	_temp_k = 1 / (0.001129148 + (0.000234125 + (0.0000000876741 * _temp_k * _temp_k ))* _temp_k);

	return _temp_k;
}

float Thermistor::getTempC(bool smooth=false) {
	_temp_k = getTempK(smooth);

	_temp_c = _temp_k - 273.15;

	return _temp_c;
}

float Thermistor::getTempF(bool smooth=false) {
	_temp_c = getTempC(smooth);

	_temp_f = (_temp_c * 9.0)/ 5.0 + 32.0;

	return _temp_f;
}

float Thermistor::getTemp(bool smooth=false) {
	return getTempC(smooth);
}
<commit_msg>remove default param from .cpp<commit_after>#include "thermistor-library.h"

Thermistor::Thermistor(int pin, int resistor) {
	_pin = pin;
	_resistor = resistor;
}

void Thermistor::begin(void) {
	pinMode(_pin, INPUT);
}

int Thermistor::getTempRaw(bool smooth=false) {
	delay(1);

	if(smooth==true) {
		int total = 0;

		for(int i=0; i<100; i++) {
			total += analogRead(_pin);
			delay(1);
		}

		_temp_raw = total/100;
	} else
		_temp_raw = analogRead(_pin);

	return _temp_raw;
}

float Thermistor::getTempK(bool smooth=false) {
	_temp_raw = getTempRaw(smooth);

	_temp_k = log(((40960000/_temp_raw) - _resistor));
	_temp_k = 1 / (0.001129148 + (0.000234125 + (0.0000000876741 * _temp_k * _temp_k ))* _temp_k);

	return _temp_k;
}

float Thermistor::getTempC(bool smooth) {
	_temp_k = getTempK(smooth);

	_temp_c = _temp_k - 273.15;

	return _temp_c;
}

float Thermistor::getTempF(bool smooth) {
	_temp_c = getTempC(smooth);

	_temp_f = (_temp_c * 9.0)/ 5.0 + 32.0;

	return _temp_f;
}

float Thermistor::getTemp(bool smooth) {
	return getTempC(smooth);
}
<|endoftext|>


<commit_before>#include <shogun/features/SimpleFeatures.h>
#include <shogun/kernel/GaussianKernel.h>
#include <shogun/kernel/DistantSegmentsKernel.h>
#include <shogun/base/init.h>
#include <shogun/lib/common.h>
#include <shogun/lib/io.h>
#include <stdio.h>

using namespace std;
using namespace shogun;

void print_message(FILE* target, const char* str)
{
	fprintf(target, "%s", str);
}

bool test_float_scalar()
{
	bool result=true;
	float64_t initialValue=1;
	float64_t anotherValue=2;

	Parameter* params=new Parameter();
	float64_t param1=initialValue;
	params->add(&param1, "param", "");

	float64_t param2=anotherValue;
	Parameter* params2=new Parameter();
	params2->add(&param2, "param", "");

	params->set_from_parameters(params2);

	result&=param1==anotherValue;

	delete params;
	delete params2;

	return result;
}

bool test_float_vector()
{
	bool result=true;
	float64_t initialValue=1;
	float64_t anotherValue=2;

	index_t max=3;
	Parameter* params=new Parameter();
	float64_t* param1=(float64_t*) malloc(sizeof(float64_t)*max);
	for (index_t i=0; i<max; ++i)
		param1[i]=initialValue;

	params->add_vector(&param1, &max, "param", "");

	float64_t* param2=(float64_t*) malloc(sizeof(float64_t)*max);
	for (index_t i=0; i<max; ++i)
		param2[i]=anotherValue;

	Parameter* params2=new Parameter();
	params2->add_vector(&param2, &max, "param", "");

	params->set_from_parameters(params2);

	for (index_t i=0; i<max; ++i)
		result&=param1[i]==anotherValue;

	free(param1);
	free(param2);
	delete params;
	delete params2;

	return result;
}

bool test_float_matrix()
{
	bool result=true;
	float64_t initialValue=1;
	float64_t anotherValue=2;

	index_t max=3;
	Parameter* params=new Parameter();
	float64_t* param1=new float64_t[max*max];
	for (index_t i=0; i<max; ++i)
		for (index_t j=0; j<max; ++j)
			param1[max*j+i]=initialValue;

	params->add_matrix(&param1, &max, &max, "param", "");

	float64_t* param2=new float64_t[max*max];
	for (index_t i=0; i<max; ++i)
		for (index_t j=0; j<max; ++j)
			param2[max*j+i]=anotherValue;

	Parameter* params2=new Parameter();
	params2->add_matrix(&param2, &max, &max, "param", "");

	params->set_from_parameters(params2);

	for (index_t i=0; i<max; ++i)
		for (index_t j=0; j<max; ++j)
			result&=param1[max*j+i]==anotherValue;

	delete param1;
	delete param2;
	delete params;
	delete params2;

	return result;
}

bool test_sgobject_scalar()
{
	bool result=true;

	Parameter* params=new Parameter();
	CSGObject* kernel=new CGaussianKernel(10, 10);
	SG_REF(kernel);
	params->add(&kernel, "kernel", "");

	CSGObject* kernel2=new CDistantSegmentsKernel(10, 10, 10);
	Parameter* params2=new Parameter();
	params2->add(&kernel2, "kernel", "");

	params->set_from_parameters(params2);

	result&=kernel==kernel2;

	delete params;
	delete params2;

	return result;
}

bool test_sgobject_vector()
{
	bool result=true;

	index_t max=3;
	Parameter* params=new Parameter();
	CSGObject** param1=new CSGObject*[max];
	for (index_t i=0; i<max; ++i)
	{
		param1[i]=new CDistantSegmentsKernel(1, 1, 1);
		SG_REF(param1[i]);
	}

	params->add_vector(&param1, &max, "param", "");

	CSGObject** param2=new CSGObject*[max];
	for (index_t i=0; i<max; ++i)
		param2[i]=new CDistantSegmentsKernel(2, 2, 2);

	Parameter* params2=new Parameter();
	params2->add_vector(&param2, &max, "param", "");

	params->set_from_parameters(params2);

	for (index_t i=0; i<max; ++i)
		result&=param1[i]==param2[i];

	delete param1;
	delete param2;
	delete params;
	delete params2;

	return result;
}

bool test_sgobject_matrix()
{
	bool result=true;

	index_t max=3;
	Parameter* params=new Parameter();
	CSGObject** param1=new CSGObject*[max*max];
	for (index_t i=0; i<max; ++i)
		for (index_t j=0; j<max; ++j)
		{
			param1[j*max+i]=new CDistantSegmentsKernel(1, 1, 1);
			SG_REF(param1[j*max+i]);
		}

	params->add_matrix(&param1, &max, &max, "param", "");

	CSGObject** param2=new CSGObject*[max*max];
	for (index_t i=0; i<max; ++i)
		for (index_t j=0; j<max; ++j)
			param2[j*max+i]=new CDistantSegmentsKernel(1, 1, 1);

	Parameter* params2=new Parameter();
	params2->add_matrix(&param2, &max, &max, "param", "");

	params->set_from_parameters(params2);

	for (index_t i=0; i<max; ++i)
		for (index_t j=0; j<max; ++j)
			result&=param1[j*max+i]==param2[j*max+i];

	delete param1;
	delete param2;
	delete params;
	delete params2;

	return result;
}

int main(int argc, char **argv)
{
	init_shogun(&print_message, &print_message, &print_message);

	bool result=true;

	/* test wheater set_from_parameters works for these types */
	result&=test_float_scalar();
	result&=test_sgobject_scalar();
	result&=test_sgobject_vector();
	result&=test_sgobject_matrix();
	result&=test_float_matrix();
	result&=test_float_vector();

	if (result)
		SG_SPRINT("SUCCESS!");
	else
		SG_SPRINT("FAILURE!");

	return 0;
}
<commit_msg>-code style changes -usage of new instead of malloc -cleaned includes -usage of CMath::fill_vector -added missing memory cleanup -minor changes<commit_after>#include <shogun/lib/io.h>
#include <shogun/lib/Mathematics.h>
#include <shogun/base/Parameter.h>
#include <shogun/kernel/DistantSegmentsKernel.h>
#include <shogun/kernel/GaussianKernel.h>

using namespace shogun;

int32_t max=3;
const float64_t initial_value=1;
const float64_t another_value=2;

void print_message(FILE* target, const char* str)
{
	fprintf(target, "%s", str);
}

bool test_float_scalar()
{
	bool result=true;

	Parameter* original_parameter_list=new Parameter();
	float64_t original_parameter=initial_value;
	original_parameter_list->add(&original_parameter, "param", "");

	float64_t new_parameter=another_value;
	Parameter* new_parameter_list=new Parameter();
	new_parameter_list->add(&new_parameter, "param", "");

	original_parameter_list->set_from_parameters(new_parameter_list);

	result&=original_parameter==another_value;

	delete original_parameter_list;
	delete new_parameter_list;

	return result;
}

bool test_float_vector()
{
	bool result=true;

	Parameter* original_parameter_list=new Parameter();
	float64_t* original_parameter=new float64_t[max];
	CMath::fill_vector(original_parameter, max, initial_value);

	original_parameter_list->add_vector(&original_parameter, &max, "param", "");

	float64_t* new_parameter=new float64_t[max];
	CMath::fill_vector(new_parameter, max, another_value);

	Parameter* new_parameter_list=new Parameter();
	new_parameter_list->add_vector(&new_parameter, &max, "param", "");

	original_parameter_list->set_from_parameters(new_parameter_list);

	for (int32_t i=0; i<max; ++i)
	{
		result&=original_parameter[i]==another_value;
	}

	delete original_parameter;
	delete new_parameter;
	delete original_parameter_list;
	delete new_parameter_list;

	return result;
}

bool test_float_matrix()
{
	bool result=true;

	Parameter* original_parameter_list=new Parameter();
	float64_t* original_parameter=new float64_t[max*max];
	CMath::fill_vector(original_parameter, max*max, initial_value);

	original_parameter_list->add_matrix(&original_parameter, &max, &max, "param", "");

	float64_t* new_parameter=new float64_t[max*max];
	CMath::fill_vector(new_parameter, max*max, another_value);

	Parameter* new_parameter_list=new Parameter();
	new_parameter_list->add_matrix(&new_parameter, &max, &max, "param", "");

	original_parameter_list->set_from_parameters(new_parameter_list);

	for (int32_t i=0; i<max*max; ++i)
	{
		result&=original_parameter[i]==another_value;
	}

	delete original_parameter;
	delete new_parameter;
	delete original_parameter_list;
	delete new_parameter_list;

	return result;
}

bool test_sgobject_scalar()
{
	bool result=true;

	Parameter* original_parameter_list=new Parameter();
	CSGObject* original_parameter=new CGaussianKernel(10, 10);
	SG_REF(original_parameter);
	original_parameter_list->add(&original_parameter, "kernel", "");

	CSGObject* new_parameter=new CDistantSegmentsKernel(10, 10, 10);
	Parameter* new_parameter_list=new Parameter();
	new_parameter_list->add(&new_parameter, "kernel", "");

	/* note: old_parameter is SG_UNREF'ed, new one SG_REF'ed */
	original_parameter_list->set_from_parameters(new_parameter_list);

	result&=original_parameter==new_parameter;

	/* old original kernel was deleted by shogun's SG_UNREF */
	SG_UNREF(new_parameter);
	delete original_parameter_list;
	delete new_parameter_list;

	return result;
}

bool test_sgobject_vector()
{
	bool result=true;

	Parameter* original_parameter_list=new Parameter();
	CSGObject** original_parameter=new CSGObject*[max];
	for (int32_t i=0; i<max; ++i)
	{
		original_parameter[i]=new CDistantSegmentsKernel(1, 1, 1);
		SG_REF(original_parameter[i]);
	}

	original_parameter_list->add_vector(&original_parameter, &max, "param", "");

	CSGObject** new_parameter=new CSGObject*[max];
	for (int32_t i=0; i<max; ++i)
	{
		new_parameter[i]=new CDistantSegmentsKernel(2, 2, 2);
	}

	Parameter* new_parameter_list=new Parameter();
	new_parameter_list->add_vector(&new_parameter, &max, "param", "");

	/* note: old_parameters are SG_UNREF'ed, new ones SG_REF'ed */
	original_parameter_list->set_from_parameters(new_parameter_list);

	for (int32_t i=0; i<max; ++i)
	{
		result&=original_parameter[i]==new_parameter[i];
	}

	/* old original kernels were deleted by shogun's SG_UNREF */
	delete original_parameter;

	for (int32_t i=0; i<max; ++i)
	{
		SG_UNREF(new_parameter[i]);
	}
	delete new_parameter;
	delete original_parameter_list;
	delete new_parameter_list;

	return result;
}

bool test_sgobject_matrix()
{
	bool result=true;

	Parameter* original_parameter_list=new Parameter();
	CSGObject** original_parameter=new CSGObject*[max*max];
	for (int32_t i=0; i<max; ++i)
	{
		for (int32_t j=0; j<max; ++j)
		{
			original_parameter[j*max+i]=new CDistantSegmentsKernel(1, 1, 1);
			SG_REF(original_parameter[j*max+i]);
		}
	}

	original_parameter_list->add_matrix(&original_parameter, &max, &max, "param", "");

	CSGObject** new_parameter=new CSGObject*[max*max];
	for (int32_t i=0; i<max; ++i)
	{
		for (int32_t j=0; j<max; ++j)
		{
			new_parameter[j*max+i]=new CDistantSegmentsKernel(1, 1, 1);
		}
	}

	Parameter* new_parameter_list=new Parameter();
	new_parameter_list->add_matrix(&new_parameter, &max, &max, "param", "");

	/* note: old_parameters are SG_UNREF'ed, new ones SG_REF'ed */
	original_parameter_list->set_from_parameters(new_parameter_list);

	for (int32_t i=0; i<max; ++i)
	{
		for (int32_t j=0; j<max; ++j)
		{
			result&=original_parameter[j*max+i]==new_parameter[j*max+i];
		}
	}

	/* old original kernels were deleted by shogun's SG_UNREF */
	delete original_parameter;

	for (int32_t i=0; i<max*max; ++i)
	{
		SG_UNREF(new_parameter[i]);
	}
	delete new_parameter;
	delete original_parameter_list;
	delete new_parameter_list;

	return result;
}

int main(int argc, char **argv)
{
	init_shogun(&print_message, &print_message, &print_message);

	bool result=true;

	/* test wheater set_from_parameters works for these types */
	result&=test_float_scalar();
	result&=test_sgobject_scalar();
	result&=test_sgobject_vector();
	result&=test_sgobject_matrix();
	result&=test_float_matrix();
	result&=test_float_vector();

	if (result)
		SG_SPRINT("SUCCESS!\n");
	else
		SG_SPRINT("FAILURE!\n");

	return 0;
}
<|endoftext|>