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

#include <cstring>
#include <fstream>
#include <iostream>
#include <sstream>
#include <string>
using namespace std;

#include <unistd.h> // sleep

float cpu_percentage( unsigned int cpu_usage_delay )
{
  string stat_line;
  size_t line_start_pos;
  size_t line_end_pos;
  unsigned long long current_user;
  unsigned long long current_system;
  unsigned long long current_nice;
  unsigned long long current_idle;
  unsigned long long next_user;
  unsigned long long next_system;
  unsigned long long next_nice;
  unsigned long long next_idle;
  unsigned long long diff_user;
  unsigned long long diff_system;
  unsigned long long diff_nice;
  unsigned long long diff_idle;
  istringstream iss;

  ifstream stat_file("/proc/stat");
  getline(stat_file, stat_line);
  stat_file.close();

  // skip "cpu"
  line_start_pos = stat_line.find_first_not_of(" ", 3);
  line_end_pos = stat_line.find_first_of(' ', line_start_pos);
  line_end_pos = stat_line.find_first_of(' ', line_end_pos + 1);
  line_end_pos = stat_line.find_first_of(' ', line_end_pos + 1);
  line_end_pos = stat_line.find_first_of(' ', line_end_pos + 1);

  iss.str( stat_line.substr( line_start_pos, line_end_pos - line_start_pos ) );
  iss >> current_user >> current_nice >> current_system >> current_idle;
  iss.clear();

  usleep( cpu_usage_delay );

  stat_file.open("/proc/stat");
  getline(stat_file, stat_line);
  stat_file.close();

  // skip "cpu"
  line_start_pos = stat_line.find_first_not_of(" ", 3);
  line_end_pos = stat_line.find_first_of(' ', line_start_pos);
  line_end_pos = stat_line.find_first_of(' ', line_end_pos + 1);
  line_end_pos = stat_line.find_first_of(' ', line_end_pos + 1);
  line_end_pos = stat_line.find_first_of(' ', line_end_pos + 1);

  iss.str( stat_line.substr( line_start_pos, line_end_pos - line_start_pos ) );
  iss >> next_user >> next_nice >> next_system >> next_idle;
  iss.clear();

  diff_user   = next_user - current_user;
  diff_system = next_system - current_system;
  diff_nice   = next_nice - current_nice;
  diff_idle   = next_idle - current_idle;

  return static_cast<float>(diff_user + diff_system + diff_nice)/static_cast<float>(diff_user + diff_system + diff_nice + diff_idle)*100.0;
}

string cpu_string( unsigned int cpu_usage_delay, unsigned int graph_lines )
{
  string meter( graph_lines + 2, ' ' );
  meter[0] = '[';
  meter[meter.length() - 1] = ']';
  int meter_count = 0;
  float percentage;
  ostringstream oss;
  oss.precision( 1 );
  oss.setf( ios::fixed | ios::right );

  percentage = cpu_percentage( cpu_usage_delay );
  float meter_step = 99.9 / graph_lines;
  meter_count = 1;
  while(meter_count*meter_step < percentage)
    {
    meter[meter_count] = '|';
    meter_count++;
    }

  oss << meter;
  oss.width( 5 );
  oss << percentage;
  oss << "%";

  return oss.str();
}

string mem_string()
{
  unsigned int total_mem;
  unsigned int used_mem;
  unsigned int unused_mem;
  size_t line_start_pos;
  size_t line_end_pos;
  istringstream iss;
  ostringstream oss;
  string mem_line;

  ifstream meminfo_file( "/proc/meminfo" );
  getline( meminfo_file, mem_line );
  line_start_pos = mem_line.find_first_of( ':' );
  line_start_pos++;
  line_end_pos = mem_line.find_first_of( 'k' );
  iss.str( mem_line.substr( line_start_pos, line_end_pos - line_start_pos ) );
  iss >> total_mem;

  used_mem = total_mem;

  for( unsigned int i = 0; i < 3; i++ )
    {
    getline( meminfo_file, mem_line );
    line_start_pos = mem_line.find_first_of( ':' );
    line_start_pos++;
    line_end_pos = mem_line.find_first_of( 'k' );
    iss.str( mem_line.substr( line_start_pos, line_end_pos - line_start_pos ) );
    iss >> unused_mem;
    used_mem -= unused_mem;
    }
  meminfo_file.close();

  oss << used_mem / 1024 << '/' << total_mem / 1024 << "MB";

  return oss.str();
}

string load_string()
{
  ifstream loadavg_file( "/proc/loadavg" );
  string load_line;
  getline( loadavg_file, load_line );
  loadavg_file.close();

  return load_line.substr( 0, 14 );
}

int main(int argc, char** argv)
{
  unsigned int cpu_usage_delay = 900000;
  unsigned int graph_lines = 10;
  bool use_colors = false;
  try
    {
    istringstream iss;
    iss.exceptions ( ifstream::failbit | ifstream::badbit );
    std::string current_arg;
    unsigned int arg_index = 1;
    if( argc > arg_index )
      {
      if( strcmp( argv[arg_index], "--colors" ) == 0 )
        {
        use_colors = true;
        ++arg_index;
        }
      }
    if( argc > arg_index )
      {
      iss.str( argv[arg_index] );
      unsigned int status_interval;
      iss >> status_interval;
      cpu_usage_delay = status_interval * 1000000 - 100000;
      ++arg_index;
      }
    if( argc > arg_index )
      {
      iss.str( argv[arg_index] );
      iss.clear();
      iss >> graph_lines;
      }
    }
  catch(const exception &e)
    {
    cerr << "Usage: " << argv[0] << " [--colors] [tmux_status-interval(seconds)] [graph lines]" << endl;
    return 1;
    }

  std::cout << use_colors << " " << cpu_usage_delay << " " << graph_lines << std::endl;
  std::cout << mem_string() << ' ' << cpu_string( cpu_usage_delay, graph_lines ) << ' ' << load_string();

  return 0;
}

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

#include <cstring>
#include <fstream>
#include <iostream>
#include <sstream>
#include <string>

#include <unistd.h> // sleep

float cpu_percentage( unsigned int cpu_usage_delay )
{
  std::string stat_line;
  size_t line_start_pos;
  size_t line_end_pos;
  unsigned long long current_user;
  unsigned long long current_system;
  unsigned long long current_nice;
  unsigned long long current_idle;
  unsigned long long next_user;
  unsigned long long next_system;
  unsigned long long next_nice;
  unsigned long long next_idle;
  unsigned long long diff_user;
  unsigned long long diff_system;
  unsigned long long diff_nice;
  unsigned long long diff_idle;
  std::istringstream iss;

  std::ifstream stat_file("/proc/stat");
  getline(stat_file, stat_line);
  stat_file.close();

  // skip "cpu"
  line_start_pos = stat_line.find_first_not_of(" ", 3);
  line_end_pos = stat_line.find_first_of(' ', line_start_pos);
  line_end_pos = stat_line.find_first_of(' ', line_end_pos + 1);
  line_end_pos = stat_line.find_first_of(' ', line_end_pos + 1);
  line_end_pos = stat_line.find_first_of(' ', line_end_pos + 1);

  iss.str( stat_line.substr( line_start_pos, line_end_pos - line_start_pos ) );
  iss >> current_user >> current_nice >> current_system >> current_idle;
  iss.clear();

  usleep( cpu_usage_delay );

  stat_file.open("/proc/stat");
  getline(stat_file, stat_line);
  stat_file.close();

  // skip "cpu"
  line_start_pos = stat_line.find_first_not_of(" ", 3);
  line_end_pos = stat_line.find_first_of(' ', line_start_pos);
  line_end_pos = stat_line.find_first_of(' ', line_end_pos + 1);
  line_end_pos = stat_line.find_first_of(' ', line_end_pos + 1);
  line_end_pos = stat_line.find_first_of(' ', line_end_pos + 1);

  iss.str( stat_line.substr( line_start_pos, line_end_pos - line_start_pos ) );
  iss >> next_user >> next_nice >> next_system >> next_idle;
  iss.clear();

  diff_user   = next_user - current_user;
  diff_system = next_system - current_system;
  diff_nice   = next_nice - current_nice;
  diff_idle   = next_idle - current_idle;

  return static_cast<float>(diff_user + diff_system + diff_nice)/static_cast<float>(diff_user + diff_system + diff_nice + diff_idle)*100.0;
}

std::string cpu_string( unsigned int cpu_usage_delay, unsigned int graph_lines )
{
  std::string meter( graph_lines + 2, ' ' );
  meter[0] = '[';
  meter[meter.length() - 1] = ']';
  int meter_count = 0;
  float percentage;
  std::ostringstream oss;
  oss.precision( 1 );
  oss.setf( std::ios::fixed | std::ios::right );

  percentage = cpu_percentage( cpu_usage_delay );
  float meter_step = 99.9 / graph_lines;
  meter_count = 1;
  while(meter_count*meter_step < percentage)
    {
    meter[meter_count] = '|';
    meter_count++;
    }

  oss << meter;
  oss.width( 5 );
  oss << percentage;
  oss << "%";

  return oss.str();
}

std::string mem_string()
{
  unsigned int total_mem;
  unsigned int used_mem;
  unsigned int unused_mem;
  size_t line_start_pos;
  size_t line_end_pos;
  std::istringstream iss;
  std::ostringstream oss;
  std::string mem_line;

  std::ifstream meminfo_file( "/proc/meminfo" );
  getline( meminfo_file, mem_line );
  line_start_pos = mem_line.find_first_of( ':' );
  line_start_pos++;
  line_end_pos = mem_line.find_first_of( 'k' );
  iss.str( mem_line.substr( line_start_pos, line_end_pos - line_start_pos ) );
  iss >> total_mem;

  used_mem = total_mem;

  for( unsigned int i = 0; i < 3; i++ )
    {
    getline( meminfo_file, mem_line );
    line_start_pos = mem_line.find_first_of( ':' );
    line_start_pos++;
    line_end_pos = mem_line.find_first_of( 'k' );
    iss.str( mem_line.substr( line_start_pos, line_end_pos - line_start_pos ) );
    iss >> unused_mem;
    used_mem -= unused_mem;
    }
  meminfo_file.close();

  oss << used_mem / 1024 << '/' << total_mem / 1024 << "MB";

  return oss.str();
}

std::string load_string()
{
  std::ifstream loadavg_file( "/proc/loadavg" );
  std::string load_line;
  std::getline( loadavg_file, load_line );
  loadavg_file.close();

  return load_line.substr( 0, 14 );
}

int main(int argc, char** argv)
{
  unsigned int cpu_usage_delay = 900000;
  unsigned int graph_lines = 10;
  bool use_colors = false;
  try
    {
    std::istringstream iss;
    iss.exceptions ( std::ifstream::failbit | std::ifstream::badbit );
    std::string current_arg;
    unsigned int arg_index = 1;
    if( argc > arg_index )
      {
      if( strcmp( argv[arg_index], "--colors" ) == 0 )
        {
        use_colors = true;
        ++arg_index;
        }
      }
    if( argc > arg_index )
      {
      iss.str( argv[arg_index] );
      unsigned int status_interval;
      iss >> status_interval;
      cpu_usage_delay = status_interval * 1000000 - 100000;
      ++arg_index;
      }
    if( argc > arg_index )
      {
      iss.str( argv[arg_index] );
      iss.clear();
      iss >> graph_lines;
      }
    }
  catch(const std::exception &e)
    {
    std::cerr << "Usage: " << argv[0] << " [--colors] [tmux_status-interval(seconds)] [graph lines]" << std::endl;
    return 1;
    }

  std::cout << use_colors << " " << cpu_usage_delay << " " << graph_lines << std::endl;
  std::cout << mem_string() << ' ' << cpu_string( cpu_usage_delay, graph_lines ) << ' ' << load_string();

  return 0;
}

<|endoftext|>


<commit_before>#include "path.h"
#include "sql/api.h"
#include <limits>
#include <utility>
#include <iostream>

using namespace std;

//construct a path based on a given graph, starting currency, and ending currency
Path::Path(const Graph& graph, const string& start, const string& end) {
  //find and store the optimal path
  DistanceEstimates dists = graph.FindOptimalPaths(start);
  path = graph.GetOptimalPath(dists, end);

  //check that a path was actually found
  if (path.size() == 0) {
    cout << "Error: Path not possible" << endl;
    return;
  }

  cout << "Found optimal path from " << start << " to " << end << ":" << endl;
  for (auto it = path.begin(); it != path.end(); ++it) {
    cout << "\t" << *it << endl;
  }
}

double Path::ConvertStartAmount(const double& amount) {
  API *db = new API();
  int retVal = db->connect();

  auto itrTo = path.begin();
  ++itrTo;
  auto itrFrom = path.begin();

  double result = amount;

  while (itrTo != path.end()) {
    double rate = db->GetForexRate(*itrFrom+*itrTo+"=X");
    result *= rate;
    cout << *itrFrom << "->" << *itrTo << ": " << result << ", rate: " << rate << endl;
    ++itrTo;
    ++itrFrom;
  }

  delete db;
  return result;
}
<commit_msg>Hooked algorithm into DB. The new API calls are temporary, as the tables that should actually be used aren't filled in yet. This is a workaround for testing purposes.<commit_after>#include "path.h"
#include "sql/api.h"
#include <limits>
#include <utility>
#include <iostream>

using namespace std;

//construct a path based on a given graph, starting currency, and ending currency
Path::Path(const Graph& graph, const string& start, const string& end) {
  //find and store the optimal path
  DistanceEstimates dists = graph.FindOptimalPaths(start);
  path = graph.GetOptimalPath(dists, end);

  //check that a path was actually found
  if (path.size() == 0) {
    cout << "Error: Path not possible" << endl;
    return;
  }

  cout << "Found optimal path from " << start << " to " << end << ":" << endl;
  for (auto it = path.begin(); it != path.end(); ++it) {
    cout << "\t" << *it << endl;
  }
}

double Path::ConvertStartAmount(const double& amount) {
  API *db = new API();
  int retVal = db->connect();

  auto itrTo = path.begin();
  ++itrTo;
  auto itrFrom = path.begin();

  double result = amount;

  while (itrTo != path.end()) {
    double rate = db->GetForexRate(*itrFrom+*itrTo+"=X");
    result *= rate;
    cout << *itrFrom << "->" << *itrTo << ": " << result << ", rate: " << rate << endl;
    ++itrTo;
    ++itrFrom;
  }

  delete db;
  return result;
}
<|endoftext|>


<commit_before>/*  This file is part of the Vc library. {{{
Copyright © 2009-2015 Matthias Kretz <kretz@kde.org>

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 names of contributing organizations 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 HOLDER 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.

}}}*/

//#define UNITTEST_ONLY_XTEST 1
#include "unittest.h"
#include "mathreference.h"

using Vc::Detail::doubleConstant;
using vir::test::setFuzzyness;

TEST_TYPES(V, testSincos, RealTypes) //{{{1
{
    typedef typename V::EntryType T;
    setFuzzyness<float>(2);
    setFuzzyness<double>(2);
    Array<SincosReference<T> > reference = sincosReference<T>();
    for (size_t i = 0; i + V::Size - 1 < reference.size; i += V::Size) {
        V x, sref, cref;
        for (size_t j = 0; j < V::Size; ++j) {
            x[j] = reference.data[i + j].x;
            sref[j] = reference.data[i + j].s;
            cref[j] = reference.data[i + j].c;
        }
        V sin, cos;
        Vc::sincos(x, &sin, &cos);
        FUZZY_COMPARE(sin, sref) << " x = " << x << ", i = " << i;
        FUZZY_COMPARE(cos, cref) << " x = " << x << ", i = " << i;
        Vc::sincos(-x, &sin, &cos);
        FUZZY_COMPARE(sin, -sref) << " x = " << -x << ", i = " << i;
        FUZZY_COMPARE(cos, cref) << " x = " << -x << ", i = " << i;
    }
}

TEST_TYPES(V, testSin, RealTypes) //{{{1
{
    typedef typename V::EntryType T;
    setFuzzyness<float>(2);
    setFuzzyness<double>(3);
    Array<SincosReference<T> > reference = sincosReference<T>();
    for (size_t i = 0; i + V::Size - 1 < reference.size; i += V::Size) {
        V x, sref;
        for (size_t j = 0; j < V::Size; ++j) {
            x[j] = reference.data[i + j].x;
            sref[j] = reference.data[i + j].s;
        }
        //std::cout << std::setprecision(30);
        //std::cout << std::defaultfloat << "testing sin(" << x << ") = " << sref << "\n";
        FUZZY_COMPARE(Vc::sin(x), sref) << " x = " << x << ", i = " << i
#if defined Vc_GCC && Vc_GCC >= 0x50100
            << std::hexfloat
            << "\n input:" << x
            << "\n    Vc:" << Vc::sin(x)
            << "\n   ref:" << sref
            << std::defaultfloat
#endif
            ;
        FUZZY_COMPARE(Vc::sin(-x), -sref) << " x = " << x << ", i = " << i;
    }
}

TEST_TYPES(V, testCos, RealTypes) //{{{1
{
    typedef typename V::EntryType T;
    setFuzzyness<float>(2);
    setFuzzyness<double>(3);
    Array<SincosReference<T> > reference = sincosReference<T>();
    for (size_t i = 0; i + V::Size - 1 < reference.size; i += V::Size) {
        V x, cref;
        for (size_t j = 0; j < V::Size; ++j) {
            x[j] = reference.data[i + j].x;
            cref[j] = reference.data[i + j].c;
        }
        FUZZY_COMPARE(Vc::cos(x), cref) << " x = " << x << ", i = " << i;
        FUZZY_COMPARE(Vc::cos(-x), cref) << " x = " << x << ", i = " << i;
    }
}

TEST_TYPES(V, testAsin, RealTypes) //{{{1
{
    typedef typename V::EntryType T;
    setFuzzyness<float>(2);
    setFuzzyness<double>(36);
    Array<Reference<T> > reference = referenceData<T, Asin>();
    for (size_t i = 0; i + V::Size - 1 < reference.size; i += V::Size) {
        V x, ref;
        for (size_t j = 0; j < V::Size; ++j) {
            x[j] = reference.data[i + j].x;
            ref[j] = reference.data[i + j].ref;
        }
        FUZZY_COMPARE(Vc::asin(x), ref) << " x = " << x << ", i = " << i;
        FUZZY_COMPARE(Vc::asin(-x), -ref) << " -x = " << -x << ", i = " << i;
    }
}

const union {
    unsigned int hex;
    float value;
} INF = { 0x7f800000 };

#if defined(__APPLE__)
// On Mac OS X, std::atan and std::atan2 don't return the special values defined in the
// Linux man pages (whether it's C99 or POSIX.1-2001 that specifies the special values is
// not mentioned in the man page). This issue is only relevant for VectorAbi::Scalar. But
// since the SimdArray types can inclue scalar Vector objects in the odd variants, the
// tests must use fuzzy compares in all cases on Mac OS X.
#define ATAN_COMPARE FUZZY_COMPARE
#else
#define ATAN_COMPARE COMPARE
#endif

TEST_TYPES(V, testAtan, RealTypes) //{{{1
{
    typedef typename V::EntryType T;
    setFuzzyness<float>(3);
    setFuzzyness<double>(2);

    {
        const V Pi_2 = T(doubleConstant<1, 0x921fb54442d18ull,  0>());
        V nan; nan.setQnan();
        const V inf = T(INF.value);

        VERIFY(all_of(Vc::isnan(Vc::atan(nan))));
        ATAN_COMPARE(Vc::atan(+inf), +Pi_2);
#ifdef Vc_MSVC
#pragma warning(suppress: 4756) // overflow in constant arithmetic
#endif
        ATAN_COMPARE(Vc::atan(-inf), -Pi_2);
    }

    Array<Reference<T> > reference = referenceData<T, Atan>();
    for (size_t i = 0; i + V::Size - 1 < reference.size; i += V::Size) {
        V x, ref;
        for (size_t j = 0; j < V::Size; ++j) {
            x[j] = reference.data[i + j].x;
            ref[j] = reference.data[i + j].ref;
        }
        FUZZY_COMPARE(Vc::atan(x), ref) << " x = " << x << ", i = " << i;
        FUZZY_COMPARE(Vc::atan(-x), -ref) << " -x = " << -x << ", i = " << i;
    }
}

TEST_TYPES(V, testAtan2, RealTypes) //{{{1
{
    typedef typename V::EntryType T;
    setFuzzyness<float>(3);
    setFuzzyness<double>(2);

    {
        const V Pi   = T(doubleConstant<1, 0x921fb54442d18ull,  1>());
        const V Pi_2 = T(doubleConstant<1, 0x921fb54442d18ull,  0>());
        V nan; nan.setQnan();
        const V inf = T(INF.value);

        // If y is +0 (-0) and x is less than 0, +pi (-pi) is returned.
        ATAN_COMPARE(Vc::atan2(V(T(+0.)), V(T(-3.))), +Pi);
        ATAN_COMPARE(Vc::atan2(V(T(-0.)), V(T(-3.))), -Pi);
        // If y is +0 (-0) and x is greater than 0, +0 (-0) is returned.
        COMPARE(Vc::atan2(V(T(+0.)), V(T(+3.))), V(T(+0.)));
        VERIFY(none_of(isnegative(Vc::atan2(V(T(+0.)), V(T(+3.))))));
        COMPARE(Vc::atan2(V(T(-0.)), V(T(+3.))), V(T(-0.)));
        VERIFY (all_of(isnegative(Vc::atan2(V(T(-0.)), V(T(+3.))))));
        // If y is less than 0 and x is +0 or -0, -pi/2 is returned.
        COMPARE(Vc::atan2(V(T(-3.)), V(T(+0.))), -Pi_2);
        COMPARE(Vc::atan2(V(T(-3.)), V(T(-0.))), -Pi_2);
        // If y is greater than 0 and x is +0 or -0, pi/2 is returned.
        COMPARE(Vc::atan2(V(T(+3.)), V(T(+0.))), +Pi_2);
        COMPARE(Vc::atan2(V(T(+3.)), V(T(-0.))), +Pi_2);
        // If either x or y is NaN, a NaN is returned.
        VERIFY(all_of(Vc::isnan(Vc::atan2(nan, V(T(3.))))));
        VERIFY(all_of(Vc::isnan(Vc::atan2(V(T(3.)), nan))));
        VERIFY(all_of(Vc::isnan(Vc::atan2(nan, nan))));
        // If y is +0 (-0) and x is -0, +pi (-pi) is returned.
        ATAN_COMPARE(Vc::atan2(V(T(+0.)), V(T(-0.))), +Pi);
        ATAN_COMPARE(Vc::atan2(V(T(-0.)), V(T(-0.))), -Pi);
        // If y is +0 (-0) and x is +0, +0 (-0) is returned.
        COMPARE(Vc::atan2(V(T(+0.)), V(T(+0.))), V(T(+0.)));
        COMPARE(Vc::atan2(V(T(-0.)), V(T(+0.))), V(T(-0.)));
        VERIFY(none_of(isnegative(Vc::atan2(V(T(+0.)), V(T(+0.))))));
        VERIFY( all_of(isnegative(Vc::atan2(V(T(-0.)), V(T(+0.))))));
        // If y is a finite value greater (less) than 0, and x is negative infinity, +pi (-pi) is returned.
        ATAN_COMPARE(Vc::atan2(V(T(+1.)), -inf), +Pi);
        ATAN_COMPARE(Vc::atan2(V(T(-1.)), -inf), -Pi);
        // If y is a finite value greater (less) than 0, and x is positive infinity, +0 (-0) is returned.
        COMPARE(Vc::atan2(V(T(+3.)), +inf), V(T(+0.)));
        VERIFY(none_of(isnegative(Vc::atan2(V(T(+3.)), +inf))));
        COMPARE(Vc::atan2(V(T(-3.)), +inf), V(T(-0.)));
        VERIFY( all_of(isnegative(Vc::atan2(V(T(-3.)), +inf))));
        // If y is positive infinity (negative infinity), and x is finite, pi/2 (-pi/2) is returned.
        COMPARE(Vc::atan2(+inf, V(T(+3.))), +Pi_2);
        COMPARE(Vc::atan2(-inf, V(T(+3.))), -Pi_2);
        COMPARE(Vc::atan2(+inf, V(T(-3.))), +Pi_2);
        COMPARE(Vc::atan2(-inf, V(T(-3.))), -Pi_2);
#ifndef _WIN32 // the Microsoft implementation of atan2 fails this test
        const V Pi_4 = T(doubleConstant<1, 0x921fb54442d18ull, -1>());
        // If y is positive infinity (negative infinity) and x is negative	infinity, +3*pi/4 (-3*pi/4) is returned.
        COMPARE(Vc::atan2(+inf, -inf), T(+3.) * Pi_4);
        COMPARE(Vc::atan2(-inf, -inf), T(-3.) * Pi_4);
        // If y is positive infinity (negative infinity) and x is positive infinity, +pi/4 (-pi/4) is returned.
        COMPARE(Vc::atan2(+inf, +inf), +Pi_4);
        COMPARE(Vc::atan2(-inf, +inf), -Pi_4);
#endif
    }

    for (int xoffset = -100; xoffset < 54613; xoffset += 47 * V::Size) {
        for (int yoffset = -100; yoffset < 54613; yoffset += 47 * V::Size) {
            const V data([](T n) { return n; });
            const V x = (data + xoffset) * T(0.15);
            const V y = (data + yoffset) * T(0.15);
            const V reference =
                V::generate([&](size_t i) { return std::atan2(x[i], y[i]); });
            FUZZY_COMPARE(Vc::atan2(x, y), reference) << ", x = " << x << ", y = " << y;
        }
    }
}

//}}}1
// vim: foldmethod=marker
<commit_msg>Bump double fuzzyness for sincos<commit_after>/*  This file is part of the Vc library. {{{
Copyright © 2009-2015 Matthias Kretz <kretz@kde.org>

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 names of contributing organizations 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 HOLDER 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.

}}}*/

//#define UNITTEST_ONLY_XTEST 1
#include "unittest.h"
#include "mathreference.h"

using Vc::Detail::doubleConstant;
using vir::test::setFuzzyness;

TEST_TYPES(V, testSincos, RealTypes) //{{{1
{
    typedef typename V::EntryType T;
    setFuzzyness<float>(2);
    setFuzzyness<double>(3);
    Array<SincosReference<T> > reference = sincosReference<T>();
    for (size_t i = 0; i + V::Size - 1 < reference.size; i += V::Size) {
        V x, sref, cref;
        for (size_t j = 0; j < V::Size; ++j) {
            x[j] = reference.data[i + j].x;
            sref[j] = reference.data[i + j].s;
            cref[j] = reference.data[i + j].c;
        }
        V sin, cos;
        Vc::sincos(x, &sin, &cos);
        FUZZY_COMPARE(sin, sref) << " x = " << x << ", i = " << i;
        FUZZY_COMPARE(cos, cref) << " x = " << x << ", i = " << i;
        Vc::sincos(-x, &sin, &cos);
        FUZZY_COMPARE(sin, -sref) << " x = " << -x << ", i = " << i;
        FUZZY_COMPARE(cos, cref) << " x = " << -x << ", i = " << i;
    }
}

TEST_TYPES(V, testSin, RealTypes) //{{{1
{
    typedef typename V::EntryType T;
    setFuzzyness<float>(2);
    setFuzzyness<double>(3);
    Array<SincosReference<T> > reference = sincosReference<T>();
    for (size_t i = 0; i + V::Size - 1 < reference.size; i += V::Size) {
        V x, sref;
        for (size_t j = 0; j < V::Size; ++j) {
            x[j] = reference.data[i + j].x;
            sref[j] = reference.data[i + j].s;
        }
        //std::cout << std::setprecision(30);
        //std::cout << std::defaultfloat << "testing sin(" << x << ") = " << sref << "\n";
        FUZZY_COMPARE(Vc::sin(x), sref) << " x = " << x << ", i = " << i
#if defined Vc_GCC && Vc_GCC >= 0x50100
            << std::hexfloat
            << "\n input:" << x
            << "\n    Vc:" << Vc::sin(x)
            << "\n   ref:" << sref
            << std::defaultfloat
#endif
            ;
        FUZZY_COMPARE(Vc::sin(-x), -sref) << " x = " << x << ", i = " << i;
    }
}

TEST_TYPES(V, testCos, RealTypes) //{{{1
{
    typedef typename V::EntryType T;
    setFuzzyness<float>(2);
    setFuzzyness<double>(3);
    Array<SincosReference<T> > reference = sincosReference<T>();
    for (size_t i = 0; i + V::Size - 1 < reference.size; i += V::Size) {
        V x, cref;
        for (size_t j = 0; j < V::Size; ++j) {
            x[j] = reference.data[i + j].x;
            cref[j] = reference.data[i + j].c;
        }
        FUZZY_COMPARE(Vc::cos(x), cref) << " x = " << x << ", i = " << i;
        FUZZY_COMPARE(Vc::cos(-x), cref) << " x = " << x << ", i = " << i;
    }
}

TEST_TYPES(V, testAsin, RealTypes) //{{{1
{
    typedef typename V::EntryType T;
    setFuzzyness<float>(2);
    setFuzzyness<double>(36);
    Array<Reference<T> > reference = referenceData<T, Asin>();
    for (size_t i = 0; i + V::Size - 1 < reference.size; i += V::Size) {
        V x, ref;
        for (size_t j = 0; j < V::Size; ++j) {
            x[j] = reference.data[i + j].x;
            ref[j] = reference.data[i + j].ref;
        }
        FUZZY_COMPARE(Vc::asin(x), ref) << " x = " << x << ", i = " << i;
        FUZZY_COMPARE(Vc::asin(-x), -ref) << " -x = " << -x << ", i = " << i;
    }
}

const union {
    unsigned int hex;
    float value;
} INF = { 0x7f800000 };

#if defined(__APPLE__)
// On Mac OS X, std::atan and std::atan2 don't return the special values defined in the
// Linux man pages (whether it's C99 or POSIX.1-2001 that specifies the special values is
// not mentioned in the man page). This issue is only relevant for VectorAbi::Scalar. But
// since the SimdArray types can inclue scalar Vector objects in the odd variants, the
// tests must use fuzzy compares in all cases on Mac OS X.
#define ATAN_COMPARE FUZZY_COMPARE
#else
#define ATAN_COMPARE COMPARE
#endif

TEST_TYPES(V, testAtan, RealTypes) //{{{1
{
    typedef typename V::EntryType T;
    setFuzzyness<float>(3);
    setFuzzyness<double>(2);

    {
        const V Pi_2 = T(doubleConstant<1, 0x921fb54442d18ull,  0>());
        V nan; nan.setQnan();
        const V inf = T(INF.value);

        VERIFY(all_of(Vc::isnan(Vc::atan(nan))));
        ATAN_COMPARE(Vc::atan(+inf), +Pi_2);
#ifdef Vc_MSVC
#pragma warning(suppress: 4756) // overflow in constant arithmetic
#endif
        ATAN_COMPARE(Vc::atan(-inf), -Pi_2);
    }

    Array<Reference<T> > reference = referenceData<T, Atan>();
    for (size_t i = 0; i + V::Size - 1 < reference.size; i += V::Size) {
        V x, ref;
        for (size_t j = 0; j < V::Size; ++j) {
            x[j] = reference.data[i + j].x;
            ref[j] = reference.data[i + j].ref;
        }
        FUZZY_COMPARE(Vc::atan(x), ref) << " x = " << x << ", i = " << i;
        FUZZY_COMPARE(Vc::atan(-x), -ref) << " -x = " << -x << ", i = " << i;
    }
}

TEST_TYPES(V, testAtan2, RealTypes) //{{{1
{
    typedef typename V::EntryType T;
    setFuzzyness<float>(3);
    setFuzzyness<double>(2);

    {
        const V Pi   = T(doubleConstant<1, 0x921fb54442d18ull,  1>());
        const V Pi_2 = T(doubleConstant<1, 0x921fb54442d18ull,  0>());
        V nan; nan.setQnan();
        const V inf = T(INF.value);

        // If y is +0 (-0) and x is less than 0, +pi (-pi) is returned.
        ATAN_COMPARE(Vc::atan2(V(T(+0.)), V(T(-3.))), +Pi);
        ATAN_COMPARE(Vc::atan2(V(T(-0.)), V(T(-3.))), -Pi);
        // If y is +0 (-0) and x is greater than 0, +0 (-0) is returned.
        COMPARE(Vc::atan2(V(T(+0.)), V(T(+3.))), V(T(+0.)));
        VERIFY(none_of(isnegative(Vc::atan2(V(T(+0.)), V(T(+3.))))));
        COMPARE(Vc::atan2(V(T(-0.)), V(T(+3.))), V(T(-0.)));
        VERIFY (all_of(isnegative(Vc::atan2(V(T(-0.)), V(T(+3.))))));
        // If y is less than 0 and x is +0 or -0, -pi/2 is returned.
        COMPARE(Vc::atan2(V(T(-3.)), V(T(+0.))), -Pi_2);
        COMPARE(Vc::atan2(V(T(-3.)), V(T(-0.))), -Pi_2);
        // If y is greater than 0 and x is +0 or -0, pi/2 is returned.
        COMPARE(Vc::atan2(V(T(+3.)), V(T(+0.))), +Pi_2);
        COMPARE(Vc::atan2(V(T(+3.)), V(T(-0.))), +Pi_2);
        // If either x or y is NaN, a NaN is returned.
        VERIFY(all_of(Vc::isnan(Vc::atan2(nan, V(T(3.))))));
        VERIFY(all_of(Vc::isnan(Vc::atan2(V(T(3.)), nan))));
        VERIFY(all_of(Vc::isnan(Vc::atan2(nan, nan))));
        // If y is +0 (-0) and x is -0, +pi (-pi) is returned.
        ATAN_COMPARE(Vc::atan2(V(T(+0.)), V(T(-0.))), +Pi);
        ATAN_COMPARE(Vc::atan2(V(T(-0.)), V(T(-0.))), -Pi);
        // If y is +0 (-0) and x is +0, +0 (-0) is returned.
        COMPARE(Vc::atan2(V(T(+0.)), V(T(+0.))), V(T(+0.)));
        COMPARE(Vc::atan2(V(T(-0.)), V(T(+0.))), V(T(-0.)));
        VERIFY(none_of(isnegative(Vc::atan2(V(T(+0.)), V(T(+0.))))));
        VERIFY( all_of(isnegative(Vc::atan2(V(T(-0.)), V(T(+0.))))));
        // If y is a finite value greater (less) than 0, and x is negative infinity, +pi (-pi) is returned.
        ATAN_COMPARE(Vc::atan2(V(T(+1.)), -inf), +Pi);
        ATAN_COMPARE(Vc::atan2(V(T(-1.)), -inf), -Pi);
        // If y is a finite value greater (less) than 0, and x is positive infinity, +0 (-0) is returned.
        COMPARE(Vc::atan2(V(T(+3.)), +inf), V(T(+0.)));
        VERIFY(none_of(isnegative(Vc::atan2(V(T(+3.)), +inf))));
        COMPARE(Vc::atan2(V(T(-3.)), +inf), V(T(-0.)));
        VERIFY( all_of(isnegative(Vc::atan2(V(T(-3.)), +inf))));
        // If y is positive infinity (negative infinity), and x is finite, pi/2 (-pi/2) is returned.
        COMPARE(Vc::atan2(+inf, V(T(+3.))), +Pi_2);
        COMPARE(Vc::atan2(-inf, V(T(+3.))), -Pi_2);
        COMPARE(Vc::atan2(+inf, V(T(-3.))), +Pi_2);
        COMPARE(Vc::atan2(-inf, V(T(-3.))), -Pi_2);
#ifndef _WIN32 // the Microsoft implementation of atan2 fails this test
        const V Pi_4 = T(doubleConstant<1, 0x921fb54442d18ull, -1>());
        // If y is positive infinity (negative infinity) and x is negative	infinity, +3*pi/4 (-3*pi/4) is returned.
        COMPARE(Vc::atan2(+inf, -inf), T(+3.) * Pi_4);
        COMPARE(Vc::atan2(-inf, -inf), T(-3.) * Pi_4);
        // If y is positive infinity (negative infinity) and x is positive infinity, +pi/4 (-pi/4) is returned.
        COMPARE(Vc::atan2(+inf, +inf), +Pi_4);
        COMPARE(Vc::atan2(-inf, +inf), -Pi_4);
#endif
    }

    for (int xoffset = -100; xoffset < 54613; xoffset += 47 * V::Size) {
        for (int yoffset = -100; yoffset < 54613; yoffset += 47 * V::Size) {
            const V data([](T n) { return n; });
            const V x = (data + xoffset) * T(0.15);
            const V y = (data + yoffset) * T(0.15);
            const V reference =
                V::generate([&](size_t i) { return std::atan2(x[i], y[i]); });
            FUZZY_COMPARE(Vc::atan2(x, y), reference) << ", x = " << x << ", y = " << y;
        }
    }
}

//}}}1
// vim: foldmethod=marker
<|endoftext|>


<commit_before>/*****************************************************************************
 * Media Library
 *****************************************************************************
 * Copyright (C) 2015 Hugo Beauzée-Luyssen, Videolabs
 *
 * Authors: Hugo Beauzée-Luyssen<hugo@beauzee.fr>
 *
 * This program is free software; you can redistribute it and/or modify it
 * under the terms of the GNU Lesser General Public License as published by
 * the Free Software Foundation; either version 2.1 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
 * GNU Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser 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 "Tests.h"

#include "Media.h"
#include "AudioTrack.h"

class AudioTracks : public Tests
{
};

TEST_F( AudioTracks, AddTrack )
{
    auto f = std::static_pointer_cast<Media>( ml->addFile( "file.mp3", nullptr ) );
    bool res = f->addAudioTrack( "PCM", 44100, 128, 2 );
    ASSERT_TRUE( res );
}

TEST_F( AudioTracks, FetchTracks )
{
    auto f = std::static_pointer_cast<Media>( ml->addFile( "file.mp3", nullptr ) );
    f->addAudioTrack( "PCM", 44100, 128, 2 );
    f->addAudioTrack( "WMA", 48000, 128, 2 );

    auto ts = f->audioTracks();
    ASSERT_EQ( ts.size(), 2u );
}

TEST_F( AudioTracks, CheckUnique )
{
    auto f = std::static_pointer_cast<Media>( ml->addFile( "file.mp3", nullptr ) );
    f->addAudioTrack( "PCM", 44100, 128, 2 );

    auto f2 = std::static_pointer_cast<Media>( ml->addFile( "file2.mp3", nullptr ) );
    f2->addAudioTrack( "PCM", 44100, 128, 2 );

    auto ts = f->audioTracks();

    auto ts2 = f2->audioTracks();

    ASSERT_EQ( ts.size(), 1u );
    ASSERT_EQ( ts2.size(), 1u );

    // Check that only 1 track has been created in DB
    ASSERT_EQ( ts[0]->id(), ts2[0]->id() );
}

<commit_msg>tests: AudioTrack: Check for individual properties<commit_after>/*****************************************************************************
 * Media Library
 *****************************************************************************
 * Copyright (C) 2015 Hugo Beauzée-Luyssen, Videolabs
 *
 * Authors: Hugo Beauzée-Luyssen<hugo@beauzee.fr>
 *
 * This program is free software; you can redistribute it and/or modify it
 * under the terms of the GNU Lesser General Public License as published by
 * the Free Software Foundation; either version 2.1 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
 * GNU Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser 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 "Tests.h"

#include "Media.h"
#include "AudioTrack.h"

class AudioTracks : public Tests
{
};

TEST_F( AudioTracks, AddTrack )
{
    auto f = std::static_pointer_cast<Media>( ml->addFile( "file.mp3", nullptr ) );
    bool res = f->addAudioTrack( "PCM", 128, 44100, 2, "fr", "test" );
    ASSERT_TRUE( res );
}

TEST_F( AudioTracks, GetSetProperties )
{
    auto f = std::static_pointer_cast<Media>( ml->addFile( "file.mp3", nullptr ) );
    ASSERT_NE( f, nullptr );
    f->addAudioTrack( "PCM", 128, 44100, 2, "en", "test desc" );
    auto tracks = f->audioTracks();
    ASSERT_EQ( tracks.size(), 1u );
    auto t = tracks[0];
    ASSERT_NE( t, nullptr );
    ASSERT_EQ( t->codec(), "PCM" );
    ASSERT_EQ( t->sampleRate(), 44100u );
    ASSERT_EQ( t->bitrate(), 128u );
    ASSERT_EQ( t->nbChannels(), 2u );
    ASSERT_EQ( t->language(), "en" );
    ASSERT_EQ( t->description(), "test desc" );

    Reload();

    auto f2 = ml->file( "file.mp3" );
    tracks = f2->audioTracks();
    ASSERT_EQ( tracks.size(), 1u );
    t = tracks[0];
    ASSERT_EQ( t->codec(), "PCM" );
    ASSERT_EQ( t->sampleRate(), 44100u );
    ASSERT_EQ( t->bitrate(), 128u );
    ASSERT_EQ( t->nbChannels(), 2u );
    ASSERT_EQ( t->language(), "en" );
    ASSERT_EQ( t->description(), "test desc" );
}

TEST_F( AudioTracks, FetchTracks )
{
    auto f = std::static_pointer_cast<Media>( ml->addFile( "file.mp3", nullptr ) );
    f->addAudioTrack( "PCM", 128, 44100, 2, "en", "test desc" );
    f->addAudioTrack( "WMA", 128, 48000, 2, "fr", "test desc 2" );

    auto ts = f->audioTracks();
    ASSERT_EQ( ts.size(), 2u );
}

TEST_F( AudioTracks, CheckUnique )
{
    auto f = std::static_pointer_cast<Media>( ml->addFile( "file.mp3", nullptr ) );
    f->addAudioTrack( "PCM", 128, 44100, 2, "en", "test desc" );

    auto f2 = std::static_pointer_cast<Media>( ml->addFile( "file2.mp3", nullptr ) );
    f2->addAudioTrack( "PCM", 128, 44100, 2, "en", "test desc" );

    auto ts = f->audioTracks();

    auto ts2 = f2->audioTracks();

    ASSERT_EQ( ts.size(), 1u );
    ASSERT_EQ( ts2.size(), 1u );

    // Check that only 1 track has been created in DB
    ASSERT_EQ( ts[0]->id(), ts2[0]->id() );
}

<|endoftext|>


<commit_before>#define CATCH_CONFIG_MAIN
#include "catch.hpp"

#include <Arduino.h>
#include "../SonoffApplicationCore.h"

class GPIORelay : public Relay
{
 public:
	 GPIORelay(int gpioPin);
	 void open();
	 void close();
	 void addObserver(RelayObserver*);
 private:
	 RelayObserver* obs;
	 int gpioPin;
};

GPIORelay::GPIORelay(int gpioPin)
{
	this->gpioPin = gpioPin;
	pinMode(gpioPin, OUTPUT);
}

void GPIORelay::open() {

};

void GPIORelay::close() {

};

void GPIORelay::addObserver(RelayObserver* obs) {

}

TEST_CASE("GPIO Relay opens and closes", "[GPIORelay]" ) {
	for (int i = 0; i < 12; i++) {
		spyPinMode[i] = 0;
		spyPinState[i] = 0;
	}

	SECTION("Relay setup") {
		GPIORelay relay{12};

	REQUIRE( spyPinMode[12] == OUTPUT );
    	}

	SECTION("Announces state change") {
											//REQUIRE( c.cState == LOW);
											}

}

<commit_msg>Enable raising of OPEN event when relay opened<commit_after>#define CATCH_CONFIG_MAIN
#include "catch.hpp"

#include <Arduino.h>
#include "../SonoffApplicationCore.h"

class GPIORelay : public Relay
{
 public:
	 GPIORelay(int gpioPin);
	 void open();
	 void close();
	 void addObserver(RelayObserver*);
 private:
	 RelayObserver* obs;
	 int gpioPin;
};

GPIORelay::GPIORelay(int gpioPin)
{
	this->gpioPin = gpioPin;
	pinMode(gpioPin, OUTPUT);
}

void GPIORelay::open() {
	this->obs->OPEN();
};

void GPIORelay::close() {

};

void GPIORelay::addObserver(RelayObserver* obs) {
	this->obs=obs;
}

class CapturingRelayObserver : public RelayObserver
{
	public:
		void OPEN()
		{ this->state = sOPEN;
		};
		void CLOSED()
		{ this->state = sCLOSED;
		};
		static int sOPEN;
		static int sCLOSED;
		int state=-1;
};

int CapturingRelayObserver::sOPEN=1;
int CapturingRelayObserver::sCLOSED=1;

TEST_CASE("GPIO Relay opens and closes", "[GPIORelay]" ) {
	for (int i = 0; i < 12; i++) {
		spyPinMode[i] = 0;
		spyPinState[i] = 0;
	}

	SECTION("Relay setup") {
		const int pinno=12;

		GPIORelay relay{pinno};

	REQUIRE( spyPinMode[pinno] == OUTPUT );
    	}

	SECTION("Opening announces state change") {

		CapturingRelayObserver capturingObserver{};

		const int pinno=12;
		GPIORelay relay{pinno};
		relay.addObserver(&capturingObserver);
		relay.open();
		REQUIRE( capturingObserver.state == CapturingRelayObserver::sOPEN);
											}

}

<|endoftext|>


<commit_before>//===----------------------------------------------------------------------===//
// LLVM 'GCCAS' UTILITY
//
// This utility is designed to be used by the GCC frontend for creating bytecode
// files from its intermediate LLVM assembly.  The requirements for this utility
// are thus slightly different than that of the standard `as' util.
//
//===----------------------------------------------------------------------===//

#include "llvm/Module.h"
#include "llvm/PassManager.h"
#include "llvm/Analysis/LoadValueNumbering.h"
#include "llvm/Analysis/Verifier.h"
#include "llvm/Assembly/Parser.h"
#include "llvm/Bytecode/WriteBytecodePass.h"
#include "llvm/Target/TargetData.h"
#include "llvm/Transforms/IPO.h"
#include "llvm/Transforms/Scalar.h"
#include "Support/CommandLine.h"
#include "Support/Signals.h"
#include <memory>
#include <fstream>

namespace {
  cl::opt<std::string>
  InputFilename(cl::Positional,cl::desc("<input llvm assembly>"),cl::init("-"));

  cl::opt<std::string>
  OutputFilename("o", cl::desc("Override output filename"),
                 cl::value_desc("filename"));

  cl::opt<bool>
  Verify("verify", cl::desc("Verify each pass result"));
}

static inline void addPass(PassManager &PM, Pass *P) {
  // Add the pass to the pass manager...
  PM.add(P);

  // If we are verifying all of the intermediate steps, add the verifier...
  if (Verify) PM.add(createVerifierPass());
}

void AddConfiguredTransformationPasses(PassManager &PM) {
  PM.add(createVerifierPass());                  // Verify that input is correct
  addPass(PM, createFunctionResolvingPass());    // Resolve (...) functions
  addPass(PM, createRaiseAllocationsPass());     // call %malloc -> malloc inst
  addPass(PM, createGlobalDCEPass());            // Remove unused globals
  addPass(PM, createPruneEHPass());              // Remove dead EH info
  addPass(PM, createFunctionInliningPass());     // Inline small functions

  addPass(PM, createInstructionCombiningPass()); // Cleanup code for raise
  addPass(PM, createRaisePointerReferencesPass());// Recover type information
  addPass(PM, createTailDuplicationPass());      // Simplify cfg by copying code
  addPass(PM, createCFGSimplificationPass());    // Merge & remove BBs
  addPass(PM, createScalarReplAggregatesPass()); // Break up aggregate allocas
  addPass(PM, createInstructionCombiningPass()); // Combine silly seq's

  addPass(PM, createReassociatePass());          // Reassociate expressions
  addPass(PM, createInstructionCombiningPass()); // Combine silly seq's
  addPass(PM, createCFGSimplificationPass());    // Merge & remove BBs
  addPass(PM, createLICMPass());                 // Hoist loop invariants
  addPass(PM, createLoadValueNumberingPass());   // GVN for load instructions
  addPass(PM, createGCSEPass());                 // Remove common subexprs
  addPass(PM, createSCCPPass());                 // Constant prop with SCCP

  // Run instcombine after redundancy elimination to exploit opportunities
  // opened up by them.
  addPass(PM, createInstructionCombiningPass());
  addPass(PM, createIndVarSimplifyPass());       // Canonicalize indvars
  addPass(PM, createAggressiveDCEPass());        // SSA based 'Aggressive DCE'
  addPass(PM, createCFGSimplificationPass());    // Merge & remove BBs
  addPass(PM, createDeadTypeEliminationPass());  // Eliminate dead types
  addPass(PM, createConstantMergePass());        // Merge dup global constants
}

int main(int argc, char **argv) {
  cl::ParseCommandLineOptions(argc, argv, " llvm .s -> .o assembler for GCC\n");

  std::auto_ptr<Module> M;
  try {
    // Parse the file now...
    M.reset(ParseAssemblyFile(InputFilename));
  } catch (const ParseException &E) {
    std::cerr << argv[0] << ": " << E.getMessage() << "\n";
    return 1;
  }

  if (M.get() == 0) {
    std::cerr << argv[0] << ": assembly didn't read correctly.\n";
    return 1;
  }

  std::ostream *Out = 0;
  if (OutputFilename == "") {   // Didn't specify an output filename?
    if (InputFilename == "-") {
      OutputFilename = "-";
    } else {
      std::string IFN = InputFilename;
      int Len = IFN.length();
      if (IFN[Len-2] == '.' && IFN[Len-1] == 's') {   // Source ends in .s?
        OutputFilename = std::string(IFN.begin(), IFN.end()-2);
      } else {
        OutputFilename = IFN;   // Append a .o to it
      }
      OutputFilename += ".o";
    }
  }

  if (OutputFilename == "-")
    Out = &std::cout;
  else {
    Out = new std::ofstream(OutputFilename.c_str(), std::ios::out);

    // Make sure that the Out file gets unlink'd from the disk if we get a
    // signal
    RemoveFileOnSignal(OutputFilename);
  }

  if (!Out->good()) {
    std::cerr << argv[0] << ": error opening " << OutputFilename << "!\n";
    return 1;
  }

  // In addition to just parsing the input from GCC, we also want to spiff it up
  // a little bit.  Do this now.
  //
  PassManager Passes;

  // Add an appropriate TargetData instance for this module...
  Passes.add(new TargetData("gccas", M.get()));

  // Add all of the transformation passes to the pass manager to do the cleanup
  // and optimization of the GCC output.
  //
  AddConfiguredTransformationPasses(Passes);

  // Write bytecode to file...
  Passes.add(new WriteBytecodePass(Out));

  // Run our queue of passes all at once now, efficiently.
  Passes.run(*M.get());

  if (Out != &std::cout) delete Out;
  return 0;
}
<commit_msg>Enable the setjmp/longjmp lowering pass<commit_after>//===----------------------------------------------------------------------===//
// LLVM 'GCCAS' UTILITY
//
// This utility is designed to be used by the GCC frontend for creating bytecode
// files from its intermediate LLVM assembly.  The requirements for this utility
// are thus slightly different than that of the standard `as' util.
//
//===----------------------------------------------------------------------===//

#include "llvm/Module.h"
#include "llvm/PassManager.h"
#include "llvm/Analysis/LoadValueNumbering.h"
#include "llvm/Analysis/Verifier.h"
#include "llvm/Assembly/Parser.h"
#include "llvm/Bytecode/WriteBytecodePass.h"
#include "llvm/Target/TargetData.h"
#include "llvm/Transforms/IPO.h"
#include "llvm/Transforms/Scalar.h"
#include "Support/CommandLine.h"
#include "Support/Signals.h"
#include <memory>
#include <fstream>

namespace {
  cl::opt<std::string>
  InputFilename(cl::Positional,cl::desc("<input llvm assembly>"),cl::init("-"));

  cl::opt<std::string>
  OutputFilename("o", cl::desc("Override output filename"),
                 cl::value_desc("filename"));

  cl::opt<bool>
  Verify("verify", cl::desc("Verify each pass result"));
}

static inline void addPass(PassManager &PM, Pass *P) {
  // Add the pass to the pass manager...
  PM.add(P);

  // If we are verifying all of the intermediate steps, add the verifier...
  if (Verify) PM.add(createVerifierPass());
}

void AddConfiguredTransformationPasses(PassManager &PM) {
  PM.add(createVerifierPass());                  // Verify that input is correct
  addPass(PM, createLowerSetJmpPass());          // Lower llvm.setjmp/.longjmp
  addPass(PM, createFunctionResolvingPass());    // Resolve (...) functions
  addPass(PM, createRaiseAllocationsPass());     // call %malloc -> malloc inst
  addPass(PM, createGlobalDCEPass());            // Remove unused globals
  addPass(PM, createPruneEHPass());              // Remove dead EH info
  addPass(PM, createFunctionInliningPass());     // Inline small functions

  addPass(PM, createInstructionCombiningPass()); // Cleanup code for raise
  addPass(PM, createRaisePointerReferencesPass());// Recover type information
  addPass(PM, createTailDuplicationPass());      // Simplify cfg by copying code
  addPass(PM, createCFGSimplificationPass());    // Merge & remove BBs
  addPass(PM, createScalarReplAggregatesPass()); // Break up aggregate allocas
  addPass(PM, createInstructionCombiningPass()); // Combine silly seq's

  addPass(PM, createReassociatePass());          // Reassociate expressions
  addPass(PM, createInstructionCombiningPass()); // Combine silly seq's
  addPass(PM, createCFGSimplificationPass());    // Merge & remove BBs
  addPass(PM, createLICMPass());                 // Hoist loop invariants
  addPass(PM, createLoadValueNumberingPass());   // GVN for load instructions
  addPass(PM, createGCSEPass());                 // Remove common subexprs
  addPass(PM, createSCCPPass());                 // Constant prop with SCCP

  // Run instcombine after redundancy elimination to exploit opportunities
  // opened up by them.
  addPass(PM, createInstructionCombiningPass());
  addPass(PM, createIndVarSimplifyPass());       // Canonicalize indvars
  addPass(PM, createAggressiveDCEPass());        // SSA based 'Aggressive DCE'
  addPass(PM, createCFGSimplificationPass());    // Merge & remove BBs
  addPass(PM, createDeadTypeEliminationPass());  // Eliminate dead types
  addPass(PM, createConstantMergePass());        // Merge dup global constants
}

int main(int argc, char **argv) {
  cl::ParseCommandLineOptions(argc, argv, " llvm .s -> .o assembler for GCC\n");

  std::auto_ptr<Module> M;
  try {
    // Parse the file now...
    M.reset(ParseAssemblyFile(InputFilename));
  } catch (const ParseException &E) {
    std::cerr << argv[0] << ": " << E.getMessage() << "\n";
    return 1;
  }

  if (M.get() == 0) {
    std::cerr << argv[0] << ": assembly didn't read correctly.\n";
    return 1;
  }

  std::ostream *Out = 0;
  if (OutputFilename == "") {   // Didn't specify an output filename?
    if (InputFilename == "-") {
      OutputFilename = "-";
    } else {
      std::string IFN = InputFilename;
      int Len = IFN.length();
      if (IFN[Len-2] == '.' && IFN[Len-1] == 's') {   // Source ends in .s?
        OutputFilename = std::string(IFN.begin(), IFN.end()-2);
      } else {
        OutputFilename = IFN;   // Append a .o to it
      }
      OutputFilename += ".o";
    }
  }

  if (OutputFilename == "-")
    Out = &std::cout;
  else {
    Out = new std::ofstream(OutputFilename.c_str(), std::ios::out);

    // Make sure that the Out file gets unlink'd from the disk if we get a
    // signal
    RemoveFileOnSignal(OutputFilename);
  }

  if (!Out->good()) {
    std::cerr << argv[0] << ": error opening " << OutputFilename << "!\n";
    return 1;
  }

  // In addition to just parsing the input from GCC, we also want to spiff it up
  // a little bit.  Do this now.
  //
  PassManager Passes;

  // Add an appropriate TargetData instance for this module...
  Passes.add(new TargetData("gccas", M.get()));

  // Add all of the transformation passes to the pass manager to do the cleanup
  // and optimization of the GCC output.
  //
  AddConfiguredTransformationPasses(Passes);

  // Write bytecode to file...
  Passes.add(new WriteBytecodePass(Out));

  // Run our queue of passes all at once now, efficiently.
  Passes.run(*M.get());

  if (Out != &std::cout) delete Out;
  return 0;
}
<|endoftext|>


<commit_before>/*************************************************************************************
 *  Copyright (C) 2012 by Alejandro Fiestas Olivares <afiestas@kde.org>              *
 *                                                                                *
 *  This program is free software; you can redistribute it and/or                    *
 *  modify it under the terms of the GNU General Public License                      *
 *  as published by the Free Software Foundation; either version 2                   *
 *  of the License, or (at your option) any later version.                           *
 *                                                                                *
 *  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 "loop.h"

#include <kscreen/config.h>
#include <kscreen/output.h>
#include <kscreen/mode.h>
#include <kscreen/configmonitor.h>
#include <kscreen/edid.h>

#include <QX11Info>
#include <QtCore/QDebug>
#include <QtCore/QDateTime>
#include <QtCore/QDir>
#include <QtCore/QTextStream>

#include <X11/X.h>
#include <X11/Xlib.h>
#include <X11/extensions/Xrandr.h>

#include <KStandardDirs>
#include <qjson/parser.h>
#include <qjson/serializer.h>

using namespace KScreen;

Loop::Loop(QObject* parent): QObject(parent)
{
    qDebug() << "START";
    QDateTime date = QDateTime::currentDateTime();
    m_config = Config::current();
    qDebug() << "Config::current() took" << date.msecsTo(QDateTime::currentDateTime()) << "milliseconds";
}

Loop::~Loop()
{

}

void Loop::printConfig()
{
//     KScreen *screen = KScreen::self();
//     qDebug() << "Backend: " << screen->backend();

    qDebug() << "\n============================================================\n"
                "============================================================\n"
                "============================================================\n";

    qDebug() << "Screen:";
    qDebug() << "maxSize:" << m_config->screen()->maxSize();
    qDebug() << "minSize:" << m_config->screen()->minSize();
    qDebug() << "currentSize:" << m_config->screen()->currentSize();

    OutputList outputs = m_config->outputs();
    OutputList outputEnabled;
    Q_FOREACH(Output *output, outputs) {
        qDebug() << "\n-----------------------------------------------------\n";
        qDebug() << "Id: " << output->id();
        qDebug() << "Name: " << output->name();
        qDebug() << "Type: " << output->type();
        qDebug() << "Connected: " << output->isConnected();
        qDebug() << "Enabled: " << output->isEnabled();
        qDebug() << "Primary: " << output->isPrimary();
        qDebug() << "Rotation: " << output->rotation();
        qDebug() << "Pos: " << output->pos();
        if (output->currentMode()) {
            qDebug() << "Size: " << output->mode(output->currentMode())->size();
        }
        qDebug() << "Clones: " << output->clones().isEmpty();
        qDebug() << "Mode: " << output->currentMode();
        qDebug() << "Preferred modes: " << output->preferredModes();
        qDebug() << "Modes: ";

        ModeList modes = output->modes();
        Q_FOREACH(Mode* mode, modes) {
            qDebug() << "\t" << mode->id() << "  " << mode->name() << " " << mode->size() << " " << mode->refreshRate();
        }

        Edid* edid = output->edid();
        qDebug() << "EDID Info: ";
        if (edid != 0) {
            qDebug() << "\tDevice ID: " << edid->deviceId();
            qDebug() << "\tName: " << edid->name();
            qDebug() << "\tVendor: " << edid->vendor();
            qDebug() << "\tSerial: " << edid->serial();
            qDebug() << "\tEISA ID: " << edid->eisaId();
            qDebug() << "\tHash: " << edid->hash();
            qDebug() << "\tWidth: " << edid->width();
            qDebug() << "\tHeight: " << edid->height();
            qDebug() << "\tGamma: " << edid->gamma();
            qDebug() << "\tRed: " << edid->red();
            qDebug() << "\tGreen: " << edid->green();
            qDebug() << "\tBlue: " << edid->blue();
            qDebug() << "\tWhite: " << edid->white();
        } else {
            qDebug() << "\tUnavailable";
        }

        if (output->isEnabled()) {
            outputEnabled.insert(output->id(), output);
        }
    }
}

void Loop::printSerializations()
{
    QTextStream out(stdout);
    QString path = KStandardDirs::locateLocal("data", "kscreen/");
    out << "Configs in: " << path << endl;

    QDir dir(path);
    QStringList files = dir.entryList(QDir::Files);
    out << "Number of files: " << files.count() << endl << endl;

    bool ok;
    QJson::Parser parser;
    QJson::Serializer serializer;
    serializer.setIndentMode(QJson::IndentFull);
    Q_FOREACH(const QString fileName, files) {
        ok = true;
        out << fileName << endl;
        QFile file(path + "/" + fileName);
        file.open(QFile::ReadOnly);
        QVariant data = parser.parse(file.readAll(), &ok);
        if (!ok) {
            out << "    " << "can't parse file" << endl;
            out << "    " << parser.errorString() << endl;
            continue;
        }

        out << serializer.serialize(data) << endl << endl;
    }
}

void Loop::monitor()
{
    ConfigMonitor::instance()->addConfig(m_config);
}

void Loop::monitorAndPrint()
{
    monitor();
    connect(ConfigMonitor::instance(), SIGNAL(configurationChanged()), SLOT(printConfig()));
}

#include <loop.moc>
<commit_msg>Use qDebug in printSerializations<commit_after>/*************************************************************************************
 *  Copyright (C) 2012 by Alejandro Fiestas Olivares <afiestas@kde.org>              *
 *                                                                                *
 *  This program is free software; you can redistribute it and/or                    *
 *  modify it under the terms of the GNU General Public License                      *
 *  as published by the Free Software Foundation; either version 2                   *
 *  of the License, or (at your option) any later version.                           *
 *                                                                                *
 *  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 "loop.h"

#include <kscreen/config.h>
#include <kscreen/output.h>
#include <kscreen/mode.h>
#include <kscreen/configmonitor.h>
#include <kscreen/edid.h>

#include <QX11Info>
#include <QtCore/QDebug>
#include <QtCore/QDateTime>
#include <QtCore/QDir>
#include <QtCore/QTextStream>

#include <X11/X.h>
#include <X11/Xlib.h>
#include <X11/extensions/Xrandr.h>

#include <KStandardDirs>
#include <qjson/parser.h>
#include <qjson/serializer.h>

using namespace KScreen;

Loop::Loop(QObject* parent): QObject(parent)
{
    qDebug() << "START";
    QDateTime date = QDateTime::currentDateTime();
    m_config = Config::current();
    qDebug() << "Config::current() took" << date.msecsTo(QDateTime::currentDateTime()) << "milliseconds";
}

Loop::~Loop()
{

}

void Loop::printConfig()
{
//     KScreen *screen = KScreen::self();
//     qDebug() << "Backend: " << screen->backend();

    qDebug() << "\n============================================================\n"
                "============================================================\n"
                "============================================================\n";

    qDebug() << "Screen:";
    qDebug() << "maxSize:" << m_config->screen()->maxSize();
    qDebug() << "minSize:" << m_config->screen()->minSize();
    qDebug() << "currentSize:" << m_config->screen()->currentSize();

    OutputList outputs = m_config->outputs();
    OutputList outputEnabled;
    Q_FOREACH(Output *output, outputs) {
        qDebug() << "\n-----------------------------------------------------\n";
        qDebug() << "Id: " << output->id();
        qDebug() << "Name: " << output->name();
        qDebug() << "Type: " << output->type();
        qDebug() << "Connected: " << output->isConnected();
        qDebug() << "Enabled: " << output->isEnabled();
        qDebug() << "Primary: " << output->isPrimary();
        qDebug() << "Rotation: " << output->rotation();
        qDebug() << "Pos: " << output->pos();
        if (output->currentMode()) {
            qDebug() << "Size: " << output->mode(output->currentMode())->size();
        }
        qDebug() << "Clones: " << output->clones().isEmpty();
        qDebug() << "Mode: " << output->currentMode();
        qDebug() << "Preferred modes: " << output->preferredModes();
        qDebug() << "Modes: ";

        ModeList modes = output->modes();
        Q_FOREACH(Mode* mode, modes) {
            qDebug() << "\t" << mode->id() << "  " << mode->name() << " " << mode->size() << " " << mode->refreshRate();
        }

        Edid* edid = output->edid();
        qDebug() << "EDID Info: ";
        if (edid != 0) {
            qDebug() << "\tDevice ID: " << edid->deviceId();
            qDebug() << "\tName: " << edid->name();
            qDebug() << "\tVendor: " << edid->vendor();
            qDebug() << "\tSerial: " << edid->serial();
            qDebug() << "\tEISA ID: " << edid->eisaId();
            qDebug() << "\tHash: " << edid->hash();
            qDebug() << "\tWidth: " << edid->width();
            qDebug() << "\tHeight: " << edid->height();
            qDebug() << "\tGamma: " << edid->gamma();
            qDebug() << "\tRed: " << edid->red();
            qDebug() << "\tGreen: " << edid->green();
            qDebug() << "\tBlue: " << edid->blue();
            qDebug() << "\tWhite: " << edid->white();
        } else {
            qDebug() << "\tUnavailable";
        }

        if (output->isEnabled()) {
            outputEnabled.insert(output->id(), output);
        }
    }
}

void Loop::printSerializations()
{
    QString path = KStandardDirs::locateLocal("data", "kscreen/");
    qDebug() << "Configs in: " << path;

    QDir dir(path);
    QStringList files = dir.entryList(QDir::Files);
    qDebug() << "Number of files: " << files.count() << endl;

    bool ok;
    QJson::Parser parser;
    QJson::Serializer serializer;
    serializer.setIndentMode(QJson::IndentFull);
    Q_FOREACH(const QString fileName, files) {
        ok = true;
        qDebug() << fileName;
        QFile file(path + "/" + fileName);
        file.open(QFile::ReadOnly);
        QVariant data = parser.parse(file.readAll(), &ok);
        if (!ok) {
            qDebug() << "    " << "can't parse file";
            qDebug() << "    " << parser.errorString();
            continue;
        }

        qDebug() << serializer.serialize(data) << endl;
    }
}

void Loop::monitor()
{
    ConfigMonitor::instance()->addConfig(m_config);
}

void Loop::monitorAndPrint()
{
    monitor();
    connect(ConfigMonitor::instance(), SIGNAL(configurationChanged()), SLOT(printConfig()));
}

#include <loop.moc>
<|endoftext|>


<commit_before>#include <TROOT.h>
#include "TApplication.h"
#include <TSystem.h>
#include <TStopwatch.h>

void runTest(const char *atest, int estimate) {
   printf("Running test : %s, (takes %d seconds on the ref machine)\n",atest,estimate);
   gSystem->Exec(Form("%s >>stressHepix.log",atest));
}

int main(int argc, char **argv)
{
   TApplication theApp("App", &argc, argv);
   printf("\n\nStarting stressHepix benchmark\n");
   printf("It takes %d seconds on a  800 rootmarks reference machine (P IV 2.8 GHz)\n",11+26+77+116+138);
   printf("It takes %d seconds on a 1500 rootmarks machine (AMD64/280)\n\n",6+18+50+43+101);
   if (gSystem->AccessPathName("atlas.root")) {
      printf("\nPreparing geometry files from http://root.cern.ch\n\n");
      gSystem->Exec("stressGeometry >stressHepix.log");
   }
   TStopwatch timer;
   timer.Start();
   gSystem->Exec("echo stressHepix > stressHepix.log");
   runTest("stressFit Minuit  2000",11);
   runTest("stressLinear",26);
   runTest("stressGeometry",77);
   runTest("stressSpectrum 1000",116);
   runTest("stress -b 3000",138);
   timer.Stop();
   Double_t rt = timer.RealTime();
   //scan log file to accumulate the individual Cpu Times
   FILE *fp = fopen("stressHepix.log","r");
   char line[180];
   float cput;
   Double_t ct = 0;
   {
      while (fgets(line,180,fp)) {
      char *cpu = strstr(line,"Cpu Time =");
      if (cpu) {sscanf(cpu+10,"%g",&cput); ct += cput;}
   }
   }
   fclose(fp);
   Double_t reftime = 278.04; //pcbrun compiled and 368 seconds real time
   const Double_t rootmarks = 800*reftime/ct;

   //Print table with results
   Bool_t UNIX = strcmp(gSystem->GetName(), "Unix") == 0;
   printf("\n\n");
   printf("****************************************************************************\n");
   printf("*                                                                          *\n");
   printf("*               S T R E S S   H E P I X  S U M M A R Y                     *\n");
   printf("*                                                                          *\n");
   printf("*       ROOTMARKS =%6.1f   *  Root%-8s  %d/%d\n",rootmarks,gROOT->GetVersion(),
         gROOT->GetVersionDate(),gROOT->GetVersionTime());
   printf("*                                                                          *\n");
   printf("*  Real Time = %6.1f seconds, CpuTime = %6.1f seconds\n",rt,ct);
   if (UNIX) {
      FILE *fp = gSystem->OpenPipe("uname -a", "r");
      char line[60];
      fgets(line,60,fp); line[59] = 0;
      printf("*  %s\n",line);
      gSystem->ClosePipe(fp);
   } else {
      const char *os = gSystem->Getenv("OS");
      if (!os) printf("*  Windows 95\n");
      else     printf("*  %s %s \n",os,gSystem->Getenv("PROCESSOR_IDENTIFIER"));
   }
   printf("****************************************************************************\n");
}

<commit_msg>Add a few more reference platforms<commit_after>#include <TROOT.h>
#include "TApplication.h"
#include <TSystem.h>
#include <TStopwatch.h>

void runTest(const char *atest, int estimate) {
   printf("Running : %s, (takes %d seconds on the ref machine)\n",atest,estimate);
   gSystem->Exec(Form("%s >>stressHepix.log",atest));
}

int main(int argc, char **argv)
{
   TApplication theApp("App", &argc, argv);
   printf("\n\nStarting stressHepix benchmark\n");
   printf("Takes %d seconds on a  500 rootmarks machine (IBM Thinkpad centrino 1.4GHz VC++7.1)\n\n",56+41+70+209+182);
   printf("Takes %d seconds on a  800 rootmarks reference machine (P IV 2.8 GHz, SLC3 gcc3.2.3)\n",11+26+77+116+138);
   printf("Takes %d seconds on a  924 rootmarks machine (MacBookPro 1.8GHz gcc4.0.1)\n",10+31+47+80+126);
   printf("Takes %d seconds on a 1056 rootmarks machine (MacBookPro 1.8GHz icc9.1)\n",8+26+38+75+106);
   printf("Takes %d seconds on a 1550 rootmarks machine (AMD64/280, FC5 gcc4.1)\n\n",6+18+50+43+101);
   if (gSystem->AccessPathName("atlas.root")) {
      printf("\nPreparing geometry files from http://root.cern.ch\n\n");
      gSystem->Exec("stressGeometry >stressHepix.log");
   }
   TStopwatch timer;
   timer.Start();
   gSystem->Exec("echo stressHepix > stressHepix.log");
   runTest("stressFit Minuit  2000",11);
   runTest("stressLinear",26);
   runTest("stressGeometry",77);
   runTest("stressSpectrum 1000",116);
   runTest("stress -b 3000",138);
   timer.Stop();
   Double_t rt = timer.RealTime();
   //scan log file to accumulate the individual Cpu Times
   FILE *fp = fopen("stressHepix.log","r");
   char line[180];
   float cput;
   Double_t ct = 0;
   {
      while (fgets(line,180,fp)) {
      char *cpu = strstr(line,"Cpu Time =");
      if (cpu) {sscanf(cpu+10,"%g",&cput); ct += cput;}
   }
   }
   fclose(fp);
   Double_t reftime = 278.04; //pcbrun compiled and 368 seconds real time
   const Double_t rootmarks = 800*reftime/ct;

   //Print table with results
   Bool_t UNIX = strcmp(gSystem->GetName(), "Unix") == 0;
   printf("\n\n");
   printf("****************************************************************************\n");
   printf("*                                                                          *\n");
   printf("*               S T R E S S   H E P I X  S U M M A R Y                     *\n");
   printf("*                                                                          *\n");
   printf("*       ROOTMARKS =%6.1f   *  Root%-8s  %d/%d\n",rootmarks,gROOT->GetVersion(),
         gROOT->GetVersionDate(),gROOT->GetVersionTime());
   printf("*                                                                          *\n");
   printf("*  Real Time = %6.1f seconds, CpuTime = %6.1f seconds\n",rt,ct);
   if (UNIX) {
      FILE *fp = gSystem->OpenPipe("uname -a", "r");
      char line[60];
      fgets(line,60,fp); line[59] = 0;
      printf("*  %s\n",line);
      gSystem->ClosePipe(fp);
   } else {
      const char *os = gSystem->Getenv("OS");
      if (!os) printf("*  Windows 95\n");
      else     printf("*  %s %s \n",os,gSystem->Getenv("PROCESSOR_IDENTIFIER"));
   }
   printf("****************************************************************************\n");
}

<|endoftext|>


<commit_before>/*
	Copyright (c) 2003 - 2005, Arvid Norberg, Daniel Wallin
	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 Rasterbar Software nor the names of its
      contributors may be used to endorse or promote products derived
      from this software without specific prior written permission.

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

*/

#include <cassert>
#include <iostream>
#include <vector>
#include <utility>
#include <set>

#include "libtorrent/buffer.hpp"
#include "libtorrent/chained_buffer.hpp"
#include "libtorrent/socket.hpp"

#include "test.hpp"

using namespace libtorrent;

/*
template<class T>
T const& min_(T const& x, T const& y)
{
	return x < y ? x : y;
}

void test_speed()
{
	buffer b;

	char data[32];

	srand(0);

	boost::timer t;

	int const iterations = 5000000;
	int const step = iterations / 20;

	for (int i = 0; i < iterations; ++i)
	{
		int x = rand();

		if (i % step == 0) std::cerr << ".";

		std::size_t n = rand() % 32;
		n = 32;

		if (x % 2)
		{
			b.insert(data, data + n);
		}
		else
		{
			b.erase(min_(b.size(), n));
		}
	}

	float t1 = t.elapsed();
	std::cerr << "buffer elapsed: " << t.elapsed() << "\n";

	std::vector<char> v;

	srand(0);
	t.restart();

	for (int i = 0; i < iterations; ++i)
	{
		int x = rand();

		if (i % step == 0) std::cerr << ".";

		std::size_t n = rand() % 32;
		n = 32;

		if (x % 2)
		{
			v.insert(v.end(), data, data + n);
		}
		else
		{
			v.erase(v.begin(), v.begin() + min_(v.size(), n));
		}
	}

	float t2 = t.elapsed();
	std::cerr << "std::vector elapsed: " << t.elapsed() << "\n";

	assert(t1 < t2);
}
*/

// -- test buffer --

void test_buffer()
{
	char data[] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9};

	buffer b;

	TEST_CHECK(b.size() == 0);
	TEST_CHECK(b.capacity() == 0);
	TEST_CHECK(b.empty());

	b.resize(10);
	TEST_CHECK(b.size() == 10);
	TEST_CHECK(b.capacity() == 10);

	std::memcpy(b.begin(), data, 10);
	b.reserve(50);
	TEST_CHECK(std::memcmp(b.begin(), data, 10) == 0);
	TEST_CHECK(b.capacity() == 50);

	b.erase(b.begin() + 6, b.end());
	TEST_CHECK(std::memcmp(b.begin(), data, 6) == 0);
	TEST_CHECK(b.capacity() == 50);
	TEST_CHECK(b.size() == 6);

	b.insert(b.begin(), data + 5, data + 10);
	TEST_CHECK(b.capacity() == 50);
	TEST_CHECK(b.size() == 11);
	TEST_CHECK(std::memcmp(b.begin(), data + 5, 5) == 0);

	b.clear();
	TEST_CHECK(b.size() == 0);
	TEST_CHECK(b.capacity() == 50);

	b.insert(b.end(), data, data + 10);
	TEST_CHECK(b.size() == 10);
	TEST_CHECK(std::memcmp(b.begin(), data, 10) == 0);

	b.erase(b.begin(), b.end());
	TEST_CHECK(b.capacity() == 50);
	TEST_CHECK(b.size() == 0);

	buffer().swap(b);
	TEST_CHECK(b.capacity() == 0);

}

// -- test chained buffer --

std::set<char*> buffer_list;

void free_buffer(char* m)
{
	std::set<char*>::iterator i = buffer_list.find(m);
	TEST_CHECK(i != buffer_list.end());

	buffer_list.erase(i);
	std::free(m);
}

char* allocate_buffer(int size)
{
	char* mem = (char*)std::malloc(size);
	buffer_list.insert(mem);
	return mem;
}

template <class T>
int copy_buffers(T const& b, char* target)
{
	int copied = 0;
	for (typename T::const_iterator i = b.begin()
		, end(b.end()); i != end; ++i)
	{
		memcpy(target, libtorrent::asio::buffer_cast<char const*>(*i), libtorrent::asio::buffer_size(*i));
		target += libtorrent::asio::buffer_size(*i);
		copied += libtorrent::asio::buffer_size(*i);
	}
	return copied;
}

bool compare_chained_buffer(chained_buffer& b, char const* mem, int size)
{
	if (size == 0) return true;
	std::vector<char> flat(size);
	std::list<libtorrent::asio::const_buffer> const& iovec2 = b.build_iovec(size);
	int copied = copy_buffers(iovec2, &flat[0]);
	TEST_CHECK(copied == size);
	return std::memcmp(&flat[0], mem, size) == 0;
}

void test_chained_buffer()
{
	char data[] = "foobar";
	{
		chained_buffer b;

		TEST_CHECK(b.empty());
		TEST_CHECK(b.capacity() == 0);
		TEST_CHECK(b.size() == 0);
		TEST_CHECK(b.space_in_last_buffer() == 0);
		TEST_CHECK(buffer_list.empty());

		char* b1 = allocate_buffer(512);
		std::memcpy(b1, data, 6);
		b.append_buffer(b1, 512, 6, (void(*)(char*))&free_buffer);
		TEST_CHECK(buffer_list.size() == 1);

		TEST_CHECK(b.capacity() == 512);
		TEST_CHECK(b.size() == 6);
		TEST_CHECK(!b.empty());
		TEST_CHECK(b.space_in_last_buffer() == 512 - 6);

		b.pop_front(3);

		TEST_CHECK(b.capacity() == 512);
		TEST_CHECK(b.size() == 3);
		TEST_CHECK(!b.empty());
		TEST_CHECK(b.space_in_last_buffer() == 512 - 6);

		bool ret = b.append(data, 6);

		TEST_CHECK(ret == true);
		TEST_CHECK(b.capacity() == 512);
		TEST_CHECK(b.size() == 9);
		TEST_CHECK(!b.empty());
		TEST_CHECK(b.space_in_last_buffer() == 512 - 12);

		ret = b.append(data, 1024);

		TEST_CHECK(ret == false);

		char* b2 = allocate_buffer(512);
		std::memcpy(b2, data, 6);
		b.append_buffer(b2, 512, 6, (void(*)(char*))&free_buffer);
		TEST_CHECK(buffer_list.size() == 2);

		char* b3 = allocate_buffer(512);
		std::memcpy(b3, data, 6);
		b.append_buffer(b3, 512, 6, (void(*)(char*))&free_buffer);
		TEST_CHECK(buffer_list.size() == 3);

		TEST_CHECK(b.capacity() == 512 * 3);
		TEST_CHECK(b.size() == 21);
		TEST_CHECK(!b.empty());
		TEST_CHECK(b.space_in_last_buffer() == 512 - 6);

		TEST_CHECK(compare_chained_buffer(b, "barfoobar", 9));

		for (int i = 1; i < 21; ++i)
			TEST_CHECK(compare_chained_buffer(b, "barfoobarfoobarfoobar", i));

		b.pop_front(5 + 6);

		TEST_CHECK(buffer_list.size() == 2);
		TEST_CHECK(b.capacity() == 512 * 2);
		TEST_CHECK(b.size() == 10);
		TEST_CHECK(!b.empty());
		TEST_CHECK(b.space_in_last_buffer() == 512 - 6);

		char const* str = "obarfooba";
		TEST_CHECK(compare_chained_buffer(b, str, 9));

		for (int i = 0; i < 9; ++i)
		{
			b.pop_front(1);
			++str;
			TEST_CHECK(compare_chained_buffer(b, str, 8 - i));
			TEST_CHECK(b.size() == 9 - i);
		}

		char* b4 = allocate_buffer(20);
		std::memcpy(b4, data, 6);
		std::memcpy(b4 + 6, data, 6);
		b.append_buffer(b4, 20, 12, (void(*)(char*))&free_buffer);
		TEST_CHECK(b.space_in_last_buffer() == 8);

		ret = b.append(data, 6);
		TEST_CHECK(ret == true);
		TEST_CHECK(b.space_in_last_buffer() == 2);
		std::cout << b.space_in_last_buffer() << std::endl;
		ret = b.append(data, 2);
		TEST_CHECK(ret == true);
		TEST_CHECK(b.space_in_last_buffer() == 0);
		std::cout << b.space_in_last_buffer() << std::endl;

		char* b5 = allocate_buffer(20);
		std::memcpy(b4, data, 6);
		b.append_buffer(b5, 20, 6, (void(*)(char*))&free_buffer);

		b.pop_front(22);
		TEST_CHECK(b.size() == 5);
	}
	TEST_CHECK(buffer_list.empty());
}

int test_main()
{
	test_buffer();
	test_chained_buffer();
	return 0;
}

<commit_msg>fix potential buffer overrun in unit test<commit_after>/*
	Copyright (c) 2003 - 2005, Arvid Norberg, Daniel Wallin
	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 Rasterbar Software nor the names of its
      contributors may be used to endorse or promote products derived
      from this software without specific prior written permission.

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

*/

#include <cassert>
#include <iostream>
#include <vector>
#include <utility>
#include <set>

#include "libtorrent/buffer.hpp"
#include "libtorrent/chained_buffer.hpp"
#include "libtorrent/socket.hpp"

#include "test.hpp"

using namespace libtorrent;

/*
template<class T>
T const& min_(T const& x, T const& y)
{
	return x < y ? x : y;
}

void test_speed()
{
	buffer b;

	char data[32];

	srand(0);

	boost::timer t;

	int const iterations = 5000000;
	int const step = iterations / 20;

	for (int i = 0; i < iterations; ++i)
	{
		int x = rand();

		if (i % step == 0) std::cerr << ".";

		std::size_t n = rand() % 32;
		n = 32;

		if (x % 2)
		{
			b.insert(data, data + n);
		}
		else
		{
			b.erase(min_(b.size(), n));
		}
	}

	float t1 = t.elapsed();
	std::cerr << "buffer elapsed: " << t.elapsed() << "\n";

	std::vector<char> v;

	srand(0);
	t.restart();

	for (int i = 0; i < iterations; ++i)
	{
		int x = rand();

		if (i % step == 0) std::cerr << ".";

		std::size_t n = rand() % 32;
		n = 32;

		if (x % 2)
		{
			v.insert(v.end(), data, data + n);
		}
		else
		{
			v.erase(v.begin(), v.begin() + min_(v.size(), n));
		}
	}

	float t2 = t.elapsed();
	std::cerr << "std::vector elapsed: " << t.elapsed() << "\n";

	assert(t1 < t2);
}
*/

// -- test buffer --

void test_buffer()
{
	char data[] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9};

	buffer b;

	TEST_CHECK(b.size() == 0);
	TEST_CHECK(b.capacity() == 0);
	TEST_CHECK(b.empty());

	b.resize(10);
	TEST_CHECK(b.size() == 10);
	TEST_CHECK(b.capacity() == 10);

	std::memcpy(b.begin(), data, 10);
	b.reserve(50);
	TEST_CHECK(std::memcmp(b.begin(), data, 10) == 0);
	TEST_CHECK(b.capacity() == 50);

	b.erase(b.begin() + 6, b.end());
	TEST_CHECK(std::memcmp(b.begin(), data, 6) == 0);
	TEST_CHECK(b.capacity() == 50);
	TEST_CHECK(b.size() == 6);

	b.insert(b.begin(), data + 5, data + 10);
	TEST_CHECK(b.capacity() == 50);
	TEST_CHECK(b.size() == 11);
	TEST_CHECK(std::memcmp(b.begin(), data + 5, 5) == 0);

	b.clear();
	TEST_CHECK(b.size() == 0);
	TEST_CHECK(b.capacity() == 50);

	b.insert(b.end(), data, data + 10);
	TEST_CHECK(b.size() == 10);
	TEST_CHECK(std::memcmp(b.begin(), data, 10) == 0);

	b.erase(b.begin(), b.end());
	TEST_CHECK(b.capacity() == 50);
	TEST_CHECK(b.size() == 0);

	buffer().swap(b);
	TEST_CHECK(b.capacity() == 0);

}

// -- test chained buffer --

std::set<char*> buffer_list;

void free_buffer(char* m)
{
	std::set<char*>::iterator i = buffer_list.find(m);
	TEST_CHECK(i != buffer_list.end());

	buffer_list.erase(i);
	std::free(m);
}

char* allocate_buffer(int size)
{
	char* mem = (char*)std::malloc(size);
	buffer_list.insert(mem);
	return mem;
}

template <class T>
int copy_buffers(T const& b, char* target)
{
	int copied = 0;
	for (typename T::const_iterator i = b.begin()
		, end(b.end()); i != end; ++i)
	{
		memcpy(target, libtorrent::asio::buffer_cast<char const*>(*i), libtorrent::asio::buffer_size(*i));
		target += libtorrent::asio::buffer_size(*i);
		copied += libtorrent::asio::buffer_size(*i);
	}
	return copied;
}

bool compare_chained_buffer(chained_buffer& b, char const* mem, int size)
{
	if (size == 0) return true;
	std::vector<char> flat(size);
	std::list<libtorrent::asio::const_buffer> const& iovec2 = b.build_iovec(size);
	int copied = copy_buffers(iovec2, &flat[0]);
	TEST_CHECK(copied == size);
	return std::memcmp(&flat[0], mem, size) == 0;
}

void test_chained_buffer()
{
	char data[] = "foobar";
	{
		chained_buffer b;

		TEST_CHECK(b.empty());
		TEST_CHECK(b.capacity() == 0);
		TEST_CHECK(b.size() == 0);
		TEST_CHECK(b.space_in_last_buffer() == 0);
		TEST_CHECK(buffer_list.empty());

		char* b1 = allocate_buffer(512);
		std::memcpy(b1, data, 6);
		b.append_buffer(b1, 512, 6, (void(*)(char*))&free_buffer);
		TEST_CHECK(buffer_list.size() == 1);

		TEST_CHECK(b.capacity() == 512);
		TEST_CHECK(b.size() == 6);
		TEST_CHECK(!b.empty());
		TEST_CHECK(b.space_in_last_buffer() == 512 - 6);

		b.pop_front(3);

		TEST_CHECK(b.capacity() == 512);
		TEST_CHECK(b.size() == 3);
		TEST_CHECK(!b.empty());
		TEST_CHECK(b.space_in_last_buffer() == 512 - 6);

		bool ret = b.append(data, 6);

		TEST_CHECK(ret == true);
		TEST_CHECK(b.capacity() == 512);
		TEST_CHECK(b.size() == 9);
		TEST_CHECK(!b.empty());
		TEST_CHECK(b.space_in_last_buffer() == 512 - 12);

		char data2[1024];
		ret = b.append(data2, 1024);

		TEST_CHECK(ret == false);

		char* b2 = allocate_buffer(512);
		std::memcpy(b2, data, 6);
		b.append_buffer(b2, 512, 6, (void(*)(char*))&free_buffer);
		TEST_CHECK(buffer_list.size() == 2);

		char* b3 = allocate_buffer(512);
		std::memcpy(b3, data, 6);
		b.append_buffer(b3, 512, 6, (void(*)(char*))&free_buffer);
		TEST_CHECK(buffer_list.size() == 3);

		TEST_CHECK(b.capacity() == 512 * 3);
		TEST_CHECK(b.size() == 21);
		TEST_CHECK(!b.empty());
		TEST_CHECK(b.space_in_last_buffer() == 512 - 6);

		TEST_CHECK(compare_chained_buffer(b, "barfoobar", 9));

		for (int i = 1; i < 21; ++i)
			TEST_CHECK(compare_chained_buffer(b, "barfoobarfoobarfoobar", i));

		b.pop_front(5 + 6);

		TEST_CHECK(buffer_list.size() == 2);
		TEST_CHECK(b.capacity() == 512 * 2);
		TEST_CHECK(b.size() == 10);
		TEST_CHECK(!b.empty());
		TEST_CHECK(b.space_in_last_buffer() == 512 - 6);

		char const* str = "obarfooba";
		TEST_CHECK(compare_chained_buffer(b, str, 9));

		for (int i = 0; i < 9; ++i)
		{
			b.pop_front(1);
			++str;
			TEST_CHECK(compare_chained_buffer(b, str, 8 - i));
			TEST_CHECK(b.size() == 9 - i);
		}

		char* b4 = allocate_buffer(20);
		std::memcpy(b4, data, 6);
		std::memcpy(b4 + 6, data, 6);
		b.append_buffer(b4, 20, 12, (void(*)(char*))&free_buffer);
		TEST_CHECK(b.space_in_last_buffer() == 8);

		ret = b.append(data, 6);
		TEST_CHECK(ret == true);
		TEST_CHECK(b.space_in_last_buffer() == 2);
		std::cout << b.space_in_last_buffer() << std::endl;
		ret = b.append(data, 2);
		TEST_CHECK(ret == true);
		TEST_CHECK(b.space_in_last_buffer() == 0);
		std::cout << b.space_in_last_buffer() << std::endl;

		char* b5 = allocate_buffer(20);
		std::memcpy(b4, data, 6);
		b.append_buffer(b5, 20, 6, (void(*)(char*))&free_buffer);

		b.pop_front(22);
		TEST_CHECK(b.size() == 5);
	}
	TEST_CHECK(buffer_list.empty());
}

int test_main()
{
	test_buffer();
	test_chained_buffer();
	return 0;
}

<|endoftext|>


<commit_before>#include <iostream>
#include <fstream>
#include <string>
#include <boost/regex.hpp>

// Iod to C++14 compiler.
//
//    Simple but useful syntaxic sugar on top of C++14.
//
//    Access to a symbol:                  @symbol      translated to    s::_Symbol
//    Access to a member via a symbol:     o@symbol     translated to    s::_Symbol.member_access(o);
//    Call to a method via a symbol:       o@symbol(42) translated to    s::_Symbol.method_call(o, 42);
//
//    All the symbols used in a C++ file are declared at the beginning of the generated file.
//
int main(int argc, char* argv[])
{
  using namespace std;

  if (argc != 3)
  {
    cout << "Usage: " << argv[0] << " input_iod_cpp_file output_cpp_file" << endl;
    return 1;
  }

  ifstream f(argv[1]);
  if (!f)
  {
    std::cerr << "Cannot open file " << argv[1] << " for reading." << std::endl;
    return 1;
  }

  set<string> symbols;

  //  prefix identifier @ symbol_identifier (
  boost::regex symbol_regex("([[:alnum:]]*)([[:blank:]]*)@[[:blank:]]*([[:alnum:]]+)[[:blank:]]*(([(][[:blank:]]*[)]?)?)");
  // Matches:
  // 1: variable name
  // 2: spaces
  // 3: symbol
  // 4: parenthesis

  vector<string> lines;

  auto to_safe_alias = [] (string s) {
    return string("_") + std::string(1, toupper(s[0])) + s.substr(1, s.size() - 1);
  };

  std::string line;
  bool in_raw_string = false;
  while (!f.eof())
  {
    getline(f, line);

    std::vector<int> dbl_quotes_pos;
    bool escaped = false;
    for (int i = 0; i < line.size(); i++)
    {
      if (line[i] == '"' and !escaped) dbl_quotes_pos.push_back(i);
      else if (line[i] == '\\') escaped = !escaped;
      else escaped = false;
    }

    auto is_in_string = [&] (int p) {
      int i = 0;
      while (i < dbl_quotes_pos.size() and dbl_quotes_pos[i] <= p) i++;
      return i % 2;
    };

    auto fmt = [&] (const boost::smatch& s) -> std::string {
      if (is_in_string(s.position())) return s[0];
      else
      {
        std::string symbol, variable_name, parenthesis;
        variable_name = s[1];
        string spaces = s[2];
        symbol = s[3];
        parenthesis = s[4];
        symbols.insert(symbol);
        ostringstream ss;

        if (variable_name.length() > 0)
        {
          ss << "s::" << to_safe_alias(symbol);
          if (parenthesis.length())
          {
            ss << ".method_call(" << variable_name;
            if (parenthesis.back() == ')') ss << ")";
            else ss << ", ";
          }
          else
            ss << ".member_access(" << variable_name << ")";
        }
        else ss << spaces << "s::" << to_safe_alias(symbol) << parenthesis;

        return ss.str();
      }
    };

    line = boost::regex_replace(line, symbol_regex, fmt);
    lines.push_back(line);
  }

  std::ofstream os(argv[2]);
  if (!os)
  {
    std::cerr << "Cannot open file " << argv[2] << " for writting." << std::endl;
    return 2;
  }

  os << "// Generated by the iod compiler."  << endl;
  os << "#include <iod/symbol.hh>" << endl;
  for (string s : symbols)
  {
    std::string safe_alias = to_safe_alias(s);
    os << "#ifndef IOD_SYMBOL_" << safe_alias << endl
       << "  iod_define_symbol(" <<  s << ", " << safe_alias << ")" << endl
       << "#endif" << endl;
  }

  int i = 1;
  for (auto line : lines)
  {
    os << "# " << i << '"' << argv[1] << '"' << std::endl;
    os << line << endl;
    i++;
  }
}
<commit_msg>Underscore in ids, missing define.<commit_after>#include <iostream>
#include <fstream>
#include <string>
#include <boost/regex.hpp>

// Iod to C++14 compiler.
//
//    Simple but useful syntaxic sugar on top of C++14.
//
//    Access to a symbol:                  @symbol      translated to    s::_Symbol
//    Access to a member via a symbol:     o@symbol     translated to    s::_Symbol.member_access(o);
//    Call to a method via a symbol:       o@symbol(42) translated to    s::_Symbol.method_call(o, 42);
//
//    All the symbols used in a C++ file are declared at the beginning of the generated file.
//
int main(int argc, char* argv[])
{
  using namespace std;

  if (argc != 3)
  {
    cout << "Usage: " << argv[0] << " input_iod_cpp_file output_cpp_file" << endl;
    return 1;
  }

  ifstream f(argv[1]);
  if (!f)
  {
    std::cerr << "Cannot open file " << argv[1] << " for reading." << std::endl;
    return 1;
  }

  set<string> symbols;

  //  prefix identifier @ symbol_identifier (
  boost::regex symbol_regex("([[:alnum:]_]*)([[:blank:]]*)@[[:blank:]]*([[:alnum:]_]+)[[:blank:]]*(([(][[:blank:]]*[)]?)?)");
  // Matches:
  // 1: variable name
  // 2: spaces
  // 3: symbol
  // 4: parenthesis

  vector<string> lines;

  auto to_safe_alias = [] (string s) {
    return string("_") + std::string(1, toupper(s[0])) + s.substr(1, s.size() - 1);
  };

  std::string line;
  bool in_raw_string = false;
  while (!f.eof())
  {
    getline(f, line);

    std::vector<int> dbl_quotes_pos;
    bool escaped = false;
    for (int i = 0; i < line.size(); i++)
    {
      if (line[i] == '"' and !escaped) dbl_quotes_pos.push_back(i);
      else if (line[i] == '\\') escaped = !escaped;
      else escaped = false;
    }

    auto is_in_string = [&] (int p) {
      int i = 0;
      while (i < dbl_quotes_pos.size() and dbl_quotes_pos[i] <= p) i++;
      return i % 2;
    };

    auto fmt = [&] (const boost::smatch& s) -> std::string {
      if (is_in_string(s.position())) return s[0];
      else
      {
        std::string symbol, variable_name, parenthesis;
        variable_name = s[1];
        string spaces = s[2];
        symbol = s[3];
        parenthesis = s[4];
        symbols.insert(symbol);
        ostringstream ss;

        if (variable_name.length() > 0)
        {
          ss << "s::" << to_safe_alias(symbol);
          if (parenthesis.length())
          {
            ss << ".method_call(" << variable_name;
            if (parenthesis.back() == ')') ss << ")";
            else ss << ", ";
          }
          else
            ss << ".member_access(" << variable_name << ")";
        }
        else ss << spaces << "s::" << to_safe_alias(symbol) << parenthesis;

        return ss.str();
      }
    };

    line = boost::regex_replace(line, symbol_regex, fmt);
    lines.push_back(line);
  }

  std::ofstream os(argv[2]);
  if (!os)
  {
    std::cerr << "Cannot open file " << argv[2] << " for writting." << std::endl;
    return 2;
  }

  os << "// Generated by the iod compiler."  << endl;
  os << "#include <iod/symbol.hh>" << endl;
  for (string s : symbols)
  {
    std::string safe_alias = to_safe_alias(s);
    os << "#ifndef IOD_SYMBOL_" << safe_alias << endl
       << "  #define IOD_SYMBOL_" << safe_alias << endl
       << "  iod_define_symbol(" <<  s << ", " << safe_alias << ")" << endl
       << "#endif" << endl;
  }

  int i = 1;
  for (auto line : lines)
  {
    os << "# " << i << '"' << argv[1] << '"' << std::endl;
    os << line << endl;
    i++;
  }
}
<|endoftext|>


<commit_before><commit_msg>Added Insertion Sort algorithm<commit_after><|endoftext|>


<commit_before><commit_msg>Fixed compiler errors<commit_after><|endoftext|>