<commit_before>#include "../kontsevich_graph_series.hpp"
#include "../kontsevich_graph_operator.hpp"
#include "../util/partitions.hpp"
#include "../util/factorial.hpp"
#include <ginac/ginac.h>
#include <iostream>
#include <vector>
#include <fstream>
#include <limits>
using namespace std;
using namespace GiNaC;

size_t order = 4;

int main()
{
    map< size_t, set<KontsevichGraph> > relevants;
    map<KontsevichGraph, ex> weights;
    cout << "Reading in known graphs and their weights...";
    ifstream weights_file("data/known_weights.txt");
    weights_file.ignore(numeric_limits<streamsize>::max(), '\n'); // ignore first line with column headers
    KontsevichGraph graph;
    int numerator, denominator;
    char slash;
    while (weights_file >> graph >> numerator >> slash >> denominator)
    {
        ex weight = numerator/(ex)denominator;
        weights[graph] = weight;
        relevants[graph.internal()].insert(graph);
    }
    cout << " done." << endl;
    cout << "Listing relevant graphs (prime, positive differential order, nonzero, modulo mirror images) at order " << order << "...";
    cout.flush();
    relevants[order] = KontsevichGraph::graphs(order, 2, true, true,
                    [](KontsevichGraph g) -> bool
                    {
                        return g.positive_differential_order() && g.is_prime() && !g.is_zero();
                    });
    cout << " done." << endl;
    cout << "Making a table of primes and weights...";
    map< size_t, vector<KontsevichGraph> > primes;
    size_t weight_count = 0;
    lst weight_vars;
    for (size_t n = 1; n <= order; ++n)
    {
        primes[n].reserve(2*relevants[n].size());
        for (KontsevichGraph g : relevants[n])
        {
            if (n == order)
            {
                symbol weight("w_" + to_string(weight_count++));
                weights[g] = weight;
                weight_vars.append(weight);
            }
            primes[n].push_back(g);
            KontsevichGraph mirror = g.mirror_image();
            if (g.abs() != mirror.abs())
            {
                weights[mirror] = weights[g];
                if (n % 2 == 1)
                    weights[mirror] *= -1;
                primes[n].push_back(mirror);
            }
        }
    }
    cout << " done." << endl;
    cout << "Constructing star product at order";
    KontsevichGraphSeries<ex> star_product;
    star_product[0] = KontsevichGraphSum<ex> { { 1, KontsevichGraph(0, 2, {}) } };
    for (size_t n = 1; n <= order; ++n)
    {
        cout << " " << n << ",";
        cout.flush();
        ex major_coeff = 1/(ex)factorial(n);
        Partitions partitions(n);
        for (auto partition = partitions.begin(); partition != partitions.end(); ++partition)
        {
            // count multiplicities of parts
            std::map<size_t, std::vector<size_t> > multiplicity;
            for (size_t i = 0; i != (*partition).size(); ++i)
                multiplicity[(*partition)[i]].push_back(i);
            // ignore multiplicity 1
            for (auto part : *partition)
                if (multiplicity[part].size() == 1)
                    multiplicity.erase(part);

            std::vector<size_t> prime_sizes((*partition).size());
            for (size_t i = 0; i != (*partition).size(); ++i)
                prime_sizes[i] = primes[(*partition)[i]].size();
            CartesianProduct decompositions(prime_sizes);
            for (auto decomposition = decompositions.begin(); decomposition != decompositions.end(); ++decomposition)
            {
                bool accept = true;
                for (auto& part : multiplicity)
                {
                    size_t prev = 0;
                    for (auto& idx : part.second) // when drawing from multiple equal sets
                    {
                        size_t current = (*decomposition)[idx];
                        if (current < prev) // accept only non-decreasing indices, to avoid duplicates
                            accept = false;
                        prev = current;
                    }
                }
                if (!accept)
                    continue;

                KontsevichGraph composite(0, 2, {});
                ex coeff = major_coeff;
                for (size_t i = 0; i != (*partition).size(); ++i)
                {
                    composite *= primes[(*partition)[i]][(*decomposition)[i]];
                    coeff *= weights[primes[(*partition)[i]][(*decomposition)[i]]];
                }
                coeff *= composite.multiplicity();
                star_product[n] += KontsevichGraphSum<ex>({ { coeff, composite} });
            }
        }
        // TODO: n is not yet considered a partition of n, so treat it separately for now:
        for (KontsevichGraph prime : primes[n])
        {
            star_product[n] += KontsevichGraphSum<ex>({ { major_coeff * weights[prime] * prime.multiplicity(), prime } });
        }
    }
    cout << " done:" << endl;
    cout << star_product << "\n";
    cout << "Number of terms in star product:\n";
    for (size_t n = 0; n <= order; ++n)
    {
        cout << "h^" << n << ": " << star_product[n].size() << " total\n";
        for (std::vector<size_t> indegrees : star_product[n].in_degrees())
        {
            for (size_t j = 0; j != indegrees.size(); ++j)
                cout << indegrees[j] << " ";
            cout << ": " << star_product[n][indegrees].size() << "\n";
        }
    }
    cout << "Computing associator...";
    cout.flush();
    KontsevichGraphSeries<ex> arg = { { 0, { { 1, KontsevichGraph(0, 1, {}) } }} };
    KontsevichGraphSeries<ex> assoc = star_product({ star_product, arg }) - star_product({ arg, star_product });
    cout << endl;
    cout << "Reducing associator...";
    cout.flush();
    assoc.reduce();
    cout << endl;
    cout << "Number of terms in associator:\n";
    lst weight_system;
    for (size_t n = 0; n <= order; ++n)
    {
        cout << "h^" << n << ":\n";
        cout << assoc[n].size() << " total\n";
        for (std::vector<size_t> indegrees : assoc[n].in_degrees())
        {
            for (size_t j = 0; j != indegrees.size(); ++j)
                cout << indegrees[j] << " ";
            cout << ": " << assoc[n][indegrees].size() << "\n";

            symbol x("x"), y("y"), z("z");
            ex h = 1/4 * pow(x,5)*pow(y,3)*pow(z,4) + pow(y,5)*z*x + pow(z,5)*pow(x,2);

            std::vector<PoissonStructure> poisson_structures {
                { { x, y, z }, { {0, h.diff(z), -h.diff(y)},
                                 {-h.diff(z), 0, h.diff(x) },
                                 { h.diff(y), -h.diff(x), 0 } } },
            };
            map< vector<symbol>, vector<ex> > arguments {
                { { x, y, z }, { pow(x,3)*z*pow(y,2), pow(y,3) + y*pow(x,10), pow(z,4) * y * pow(x,2) } }
            };

            for (PoissonStructure& poisson : poisson_structures)
            {
                ex result = evaluate(assoc[n][indegrees], poisson, arguments[poisson.coordinates]).expand();
                vector<size_t> degrees;
                for (symbol& variable : poisson.coordinates)
                    degrees.push_back(result.degree(variable));
                CartesianProduct monomialdegrees_list(degrees);
                for (auto monomialdegrees = monomialdegrees_list.begin(); monomialdegrees != monomialdegrees_list.end(); ++monomialdegrees)
                {
                    ex result2 = result;
                    for (size_t i = 0; i != poisson.coordinates.size(); ++i)
                    {
                        result2 = result2.coeff(poisson.coordinates[i], (*monomialdegrees)[i]).expand();
                    }
                    if (result2 != 0)
                    {
                        weight_system.append(result2 == 0);
                        cout << result2 << " == 0\n";
                    }
                }
            }
        }
    }
    cout << "Got system of " << weight_system.nops() << " linear equations in " << weight_vars.nops() << " unknowns:\n";
    for (ex eq : weight_system)
        if (eq.lhs() != eq.rhs()) // not a tautology
            cout << eq << endl;
    cout << "Solving it...\n";
    for (ex eq : lsolve(weight_system, weight_vars))
        if (eq.lhs() != eq.rhs()) // not a tautology
            cout << eq << endl;
}
<commit_msg>Generate weight equations more effectively.<commit_after>#include "../kontsevich_graph_series.hpp"
#include "../kontsevich_graph_operator.hpp"
#include "../util/partitions.hpp"
#include "../util/factorial.hpp"
#include <ginac/ginac.h>
#include <iostream>
#include <vector>
#include <fstream>
#include <limits>
using namespace std;
using namespace GiNaC;

size_t order = 4;

int main()
{
    map< size_t, set<KontsevichGraph> > relevants;
    map<KontsevichGraph, ex> weights;
    cout << "Reading in known graphs and their weights...";
    ifstream weights_file("data/known_weights.txt");
    weights_file.ignore(numeric_limits<streamsize>::max(), '\n'); // ignore first line with column headers
    KontsevichGraph graph;
    int numerator, denominator;
    char slash;
    while (weights_file >> graph >> numerator >> slash >> denominator)
    {
        ex weight = numerator/(ex)denominator;
        weights[graph] = weight;
        relevants[graph.internal()].insert(graph);
    }
    cout << " done." << endl;
    cout << "Listing relevant graphs (prime, positive differential order, nonzero, modulo mirror images) at order " << order << "...";
    cout.flush();
    relevants[order] = KontsevichGraph::graphs(order, 2, true, true,
                    [](KontsevichGraph g) -> bool
                    {
                        return g.positive_differential_order() && g.is_prime() && !g.is_zero();
                    });
    cout << " done." << endl;
    cout << "Making a table of primes and weights...";
    map< size_t, vector<KontsevichGraph> > primes;
    size_t weight_count = 0;
    lst weight_vars;
    for (size_t n = 1; n <= order; ++n)
    {
        primes[n].reserve(2*relevants[n].size());
        for (KontsevichGraph g : relevants[n])
        {
            if (n == order)
            {
                symbol weight("w_" + to_string(weight_count++));
                weights[g] = weight;
                weight_vars.append(weight);
            }
            primes[n].push_back(g);
            KontsevichGraph mirror = g.mirror_image();
            if (g.abs() != mirror.abs())
            {
                weights[mirror] = weights[g];
                if (n % 2 == 1)
                    weights[mirror] *= -1;
                primes[n].push_back(mirror);
            }
        }
    }
    cout << " done." << endl;
    cout << "Constructing star product at order";
    KontsevichGraphSeries<ex> star_product;
    star_product[0] = KontsevichGraphSum<ex> { { 1, KontsevichGraph(0, 2, {}) } };
    for (size_t n = 1; n <= order; ++n)
    {
        cout << " " << n << ",";
        cout.flush();
        ex major_coeff = 1/(ex)factorial(n);
        Partitions partitions(n);
        for (auto partition = partitions.begin(); partition != partitions.end(); ++partition)
        {
            // count multiplicities of parts
            std::map<size_t, std::vector<size_t> > multiplicity;
            for (size_t i = 0; i != (*partition).size(); ++i)
                multiplicity[(*partition)[i]].push_back(i);
            // ignore multiplicity 1
            for (auto part : *partition)
                if (multiplicity[part].size() == 1)
                    multiplicity.erase(part);

            std::vector<size_t> prime_sizes((*partition).size());
            for (size_t i = 0; i != (*partition).size(); ++i)
                prime_sizes[i] = primes[(*partition)[i]].size();
            CartesianProduct decompositions(prime_sizes);
            for (auto decomposition = decompositions.begin(); decomposition != decompositions.end(); ++decomposition)
            {
                bool accept = true;
                for (auto& part : multiplicity)
                {
                    size_t prev = 0;
                    for (auto& idx : part.second) // when drawing from multiple equal sets
                    {
                        size_t current = (*decomposition)[idx];
                        if (current < prev) // accept only non-decreasing indices, to avoid duplicates
                            accept = false;
                        prev = current;
                    }
                }
                if (!accept)
                    continue;

                KontsevichGraph composite(0, 2, {});
                ex coeff = major_coeff;
                for (size_t i = 0; i != (*partition).size(); ++i)
                {
                    composite *= primes[(*partition)[i]][(*decomposition)[i]];
                    coeff *= weights[primes[(*partition)[i]][(*decomposition)[i]]];
                }
                coeff *= composite.multiplicity();
                star_product[n] += KontsevichGraphSum<ex>({ { coeff, composite} });
            }
        }
        // TODO: n is not yet considered a partition of n, so treat it separately for now:
        for (KontsevichGraph prime : primes[n])
        {
            star_product[n] += KontsevichGraphSum<ex>({ { major_coeff * weights[prime] * prime.multiplicity(), prime } });
        }
    }
    cout << " done:" << endl;
    cout << star_product << "\n";
    cout << "Number of terms in star product:\n";
    for (size_t n = 0; n <= order; ++n)
    {
        cout << "h^" << n << ": " << star_product[n].size() << " total\n";
        for (std::vector<size_t> indegrees : star_product[n].in_degrees())
        {
            for (size_t j = 0; j != indegrees.size(); ++j)
                cout << indegrees[j] << " ";
            cout << ": " << star_product[n][indegrees].size() << "\n";
        }
    }
    cout << "Computing associator...";
    cout.flush();
    KontsevichGraphSeries<ex> arg = { { 0, { { 1, KontsevichGraph(0, 1, {}) } }} };
    KontsevichGraphSeries<ex> assoc = star_product({ star_product, arg }) - star_product({ arg, star_product });
    cout << endl;
    cout << "Reducing associator...";
    cout.flush();
    assoc.reduce();
    cout << endl;
    cout << "Number of terms in associator:\n";
    set<ex, ex_is_less> weight_system;
    for (size_t n = 0; n <= order; ++n)
    {
        cout << "h^" << n << ":\n";
        cout << assoc[n].size() << " total\n";
        for (std::vector<size_t> indegrees : assoc[n].in_degrees())
        {
            for (size_t j = 0; j != indegrees.size(); ++j)
                cout << indegrees[j] << " ";
            cout << ": " << assoc[n][indegrees].size() << "\n";

            symbol x("x"), y("y"), z("z");
            ex h = 1/4 * pow(x,5)*pow(y,3)*pow(z,4) + pow(y,5)*z*x + pow(z,5)*pow(x,2);

            std::vector<PoissonStructure> poisson_structures {
                { { x, y, z }, { {0, h.diff(z), -h.diff(y)},
                                 {-h.diff(z), 0, h.diff(x) },
                                 { h.diff(y), -h.diff(x), 0 } } },
            };

            for (PoissonStructure& poisson : poisson_structures)
            {
                for (auto& result_pair : evaluate_coefficients(assoc[n][indegrees], poisson))
                {
                    ex result = result_pair.second.expand();

                    // for polynomial, equate coefficients (alternative: fill in some numbers)
                    vector<size_t> degrees;
                    for (symbol& variable : poisson.coordinates)
                        degrees.push_back(result.degree(variable));
                    CartesianProduct monomialdegrees_list(degrees);
                    for (auto monomialdegrees = monomialdegrees_list.begin(); monomialdegrees != monomialdegrees_list.end(); ++monomialdegrees)
                    {
                        // extract coefficient (not very efficiently):
                        ex result2 = result;
                        for (size_t i = 0; i != poisson.coordinates.size(); ++i)
                        {
                            result2 = result2.coeff(poisson.coordinates[i], (*monomialdegrees)[i]).expand();
                        }
                        // normalize the equation:
                        for (ex var : weight_vars)
                        {
                            if (result2.coeff(var) != 0) // first weight variable occurring in expression
                            {
                                result2 /= result2.coeff(var); // divide by its coefficient
                                break;
                            }
                        }
                        if (result2 != 0)
                        {
                            weight_system.insert(result2 == 0);
                            cout << result2 << " == 0\n";
                        }
                    }
                }
            }
        }
    }
    cout << "Got system of " << weight_system.size() << " linear equations in " << weight_vars.nops() << " unknowns:\n";
    lst weight_system_lst;
    for (ex eq : weight_system)
    {
        if (eq.lhs() != eq.rhs()) // not a tautology
        {
            cout << eq << endl;
            weight_system_lst.append(eq);
        }
    }
    cout << "Solving it...\n";
    for (ex eq : lsolve(weight_system_lst, weight_vars))
        if (eq.lhs() != eq.rhs()) // not a tautology
            cout << eq << endl;
}
<|endoftext|>


<commit_before>/*
    Title:  save_vec.cpp - The save vector holds temporary values that may move as
    the result of a garbage collection.

    Copyright (c) 2006 David C.J. Matthews

    This library is free software; you can redistribute it and/or
    modify it under the terms of the GNU Lesser General Public
    License as published by the Free Software Foundation; either
    version 2.1 of the License, or (at your option) any later version.

    This library is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
    Lesser General Public License for more details.

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

*/

#ifdef WIN32
#include "winconfig.h"
#else
#include "config.h"
#endif

#ifdef HAVE_ASSERT_H
#include <assert.h>
#define ASSERT(x)   assert(x)
#else
#define ASSERT(x)
#endif

#include "globals.h"
#include "save_vec.h"
#include "check_objects.h"
#include "scanaddrs.h"

#define SVEC_SIZE 1000

SaveVec::SaveVec()
{
    save_vec = new SaveVecEntry[SVEC_SIZE];
    save_vec_addr = save_vec;
}

SaveVec::~SaveVec()
{
    delete[](save_vec);
}

// DCJM - I've used this in a few cases where we iterate over a list
// and want to avoid overflowing the save vec.  I've assumed that simply
// resetting the list doesn't actually destroy the entry on the save vec
// and it's safe to still use it provided that doesn't result in allocation.
void SaveVec::reset(Handle old_value)
{
    ASSERT(old_value >= save_vec && old_value <= save_vec_addr);
    save_vec_addr = old_value;
}

Handle SaveVec::push(PolyWord valu) /* Push a PolyWord onto the save vec. */
{
    ASSERT(save_vec_addr < save_vec+SVEC_SIZE);

    Check(valu);

    *save_vec_addr = SaveVecEntry(valu);
    return save_vec_addr++;
}

/******************************************************************************/
/*                                                                            */
/*      run_time_gc - utility function, called indirectly                     */
/*                                                                            */
/******************************************************************************/
void SaveVec::gcScan(ScanAddress *process)
/* Ensures that all the objects are retained and their addresses updated. */
{
    for (Handle sv = save_vec; sv < save_vec_addr; sv++)
    {
        PolyWord *saved = &(sv->m_Handle);
        if ((*saved).IsTagged()) {} // Don't need to do anything
        else {
            // If it's not a tagged integer then it should be a data pointer.
            // We shouldn't get code addresses here, should we?
            ASSERT((*saved).IsDataPtr());
            PolyObject *obj = (*saved).AsObjPtr();
            process->ScanRuntimeAddress(&obj, ScanAddress::STRENGTH_STRONG);
            *saved = obj;
        }
    }
}

// We just have one of these.
static SaveVec save;

SaveVec *gSaveVec = &save;
<commit_msg>Process code addresses on save_vec. save_vec may contain code addresses as a result of a call to set_code_constant. This itself doesn't allocate so can't result in a GC but another thread may have requested a GC.<commit_after>/*
    Title:  save_vec.cpp - The save vector holds temporary values that may move as
    the result of a garbage collection.

    Copyright (c) 2006 David C.J. Matthews

    This library is free software; you can redistribute it and/or
    modify it under the terms of the GNU Lesser General Public
    License as published by the Free Software Foundation; either
    version 2.1 of the License, or (at your option) any later version.

    This library is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
    Lesser General Public License for more details.

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

*/

#ifdef WIN32
#include "winconfig.h"
#else
#include "config.h"
#endif

#ifdef HAVE_ASSERT_H
#include <assert.h>
#define ASSERT(x)   assert(x)
#else
#define ASSERT(x)
#endif

#include "globals.h"
#include "save_vec.h"
#include "check_objects.h"
#include "scanaddrs.h"

#define SVEC_SIZE 1000

SaveVec::SaveVec()
{
    save_vec = new SaveVecEntry[SVEC_SIZE];
    save_vec_addr = save_vec;
}

SaveVec::~SaveVec()
{
    delete[](save_vec);
}

// DCJM - I've used this in a few cases where we iterate over a list
// and want to avoid overflowing the save vec.  I've assumed that simply
// resetting the list doesn't actually destroy the entry on the save vec
// and it's safe to still use it provided that doesn't result in allocation.
void SaveVec::reset(Handle old_value)
{
    ASSERT(old_value >= save_vec && old_value <= save_vec_addr);
    save_vec_addr = old_value;
}

Handle SaveVec::push(PolyWord valu) /* Push a PolyWord onto the save vec. */
{
    ASSERT(save_vec_addr < save_vec+SVEC_SIZE);

    Check(valu);

    *save_vec_addr = SaveVecEntry(valu);
    return save_vec_addr++;
}

/******************************************************************************/
/*                                                                            */
/*      run_time_gc - utility function, called indirectly                     */
/*                                                                            */
/******************************************************************************/
void SaveVec::gcScan(ScanAddress *process)
/* Ensures that all the objects are retained and their addresses updated. */
{
    for (Handle sv = save_vec; sv < save_vec_addr; sv++)
    {
        PolyWord *saved = &(sv->m_Handle);
        if ((*saved).IsTagged()) {} // Don't need to do anything
        else if ((*saved).IsCodePtr())
        {
            // We can have code pointers in set_code_address.
            // Find the start of the code segment
            PolyObject *obj = ObjCodePtrToPtr(saved->AsCodePtr());
            // Calculate the byte offset of this value within the code object.
            POLYUNSIGNED offset = saved->AsCodePtr() - (byte*)obj;
            process->ScanRuntimeAddress(&obj, ScanAddress::STRENGTH_STRONG);
            *saved = PolyWord::FromCodePtr((byte*)obj + offset);

        }
        else {
            ASSERT((*saved).IsDataPtr());
            PolyObject *obj = (*saved).AsObjPtr();
            process->ScanRuntimeAddress(&obj, ScanAddress::STRENGTH_STRONG);
            *saved = obj;
        }
    }
}

// We just have one of these.
static SaveVec save;

SaveVec *gSaveVec = &save;
<|endoftext|>


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

  Program:   Insight Segmentation & Registration Toolkit
  Module:    itkImageBase.cxx
  Language:  C++
  Date:      $Date$
  Version:   $Revision$

  Copyright (c) 2000 National Library of Medicine
  All rights reserved.

  See COPYRIGHT.txt for copyright details.

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

namespace itk
{

/**
 *
 */
ImageBase
::ImageBase()
{
  m_Size = 0;
  m_Spacing = 0;
  m_Origin = 0;
}

/**
 *
 */
ImageBase
::~ImageBase()
{
  this->Initialize();
}

/**
 *
 */
void
ImageBase
::Initialize()
{
  if ( m_Size != 0 )
    {
    delete [] m_Size;
    delete [] m_Spacing;
    delete [] m_Origin;
    }
  this->DataObject::Initialize();
}

/**
 *
 */
void
ImageBase
::SetDimension(unsigned int dim)
{
  if ( dim != this->GetDimension() )
    {
    this->Initialize();

    this->DataObject::SetDimension(dim);
    m_Size = new unsigned long [dim];
    m_Spacing = new float [dim];
    m_Origin = new float [dim];

    this->Modified();
    }
}

/**
 *
 */
void
ImageBase
::SetSize(unsigned long *size)
{
  bool modified = false;

  for (unsigned int i=0; i<this->GetDimension(); i++)
    {
    if ( m_Size[i] != size[i] )
      {
      m_Size[i] = size[i];
      modified = true;
      }
    }

  if ( modified )
    {
    this->Modified();
    }
}

//-------------------------------------------------------------------------
/**
 *
 */
void
ImageBase
::SetSpacing(float *spacing)
{
  bool modified = false;

  for (unsigned int i=0; i<this->GetDimension(); i++)
    {
    if ( m_Spacing[i] != spacing[i] )
      {
      m_Spacing[i] = spacing[i];
      modified = true;
      }
    }

  if ( modified )
    {
    this->Modified();
    }
}

/**
 *
 */
void
ImageBase
::SetOrigin(float *origin)
{
  bool modified = false;

  for (unsigned int i=0; i<this->GetDimension(); i++)
    {
    if ( m_Origin[i] != origin[i] )
      {
      m_Origin[i] = origin[i];
      modified = true;
      }
    }

  if ( modified )
    {
    this->Modified();
    }
}

/**
 *
 */
void
ImageBase
::PrintSelf(std::ostream& os, Indent indent)
{
  DataObject::PrintSelf(os,indent);
}

} // namespace itk
<commit_msg>ENH:  Modified ImageBase::SetDimension to initialize the image origin (m_Origin) to 0.0 and the spacing (m_Spacing) to 1.0.  That is, physical coordinates are initialized to be the same as index coordinates.<commit_after>/*=========================================================================

  Program:   Insight Segmentation & Registration Toolkit
  Module:    itkImageBase.cxx
  Language:  C++
  Date:      $Date$
  Version:   $Revision$

  Copyright (c) 2000 National Library of Medicine
  All rights reserved.

  See COPYRIGHT.txt for copyright details.

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

namespace itk
{

/**
 *
 */
ImageBase
::ImageBase()
{
  m_Size = 0;
  m_Spacing = 0;
  m_Origin = 0;
}

/**
 *
 */
ImageBase
::~ImageBase()
{
  this->Initialize();
}

/**
 *
 */
void
ImageBase
::Initialize()
{
  if ( m_Size != 0 )
    {
    delete [] m_Size;
    delete [] m_Spacing;
    delete [] m_Origin;
    }
  this->DataObject::Initialize();
}

/**
 *
 */
void
ImageBase
::SetDimension(unsigned int dim)
{
  if ( dim != this->GetDimension() )
    {
    this->Initialize();

    this->DataObject::SetDimension(dim);
    m_Size = new unsigned long [dim];
    m_Spacing = new float [dim];
    m_Origin = new float [dim];

    for (int i = 0; i < dim; i++) {
	m_Origin [i] = 0.0;
	m_Spacing[i] = 1.0;
    }

    this->Modified();
    }
}

/**
 *
 */
void
ImageBase
::SetSize(unsigned long *size)
{
  bool modified = false;

  for (unsigned int i=0; i<this->GetDimension(); i++)
    {
    if ( m_Size[i] != size[i] )
      {
      m_Size[i] = size[i];
      modified = true;
      }
    }

  if ( modified )
    {
    this->Modified();
    }
}

//-------------------------------------------------------------------------
/**
 *
 */
void
ImageBase
::SetSpacing(float *spacing)
{
  bool modified = false;

  for (unsigned int i=0; i<this->GetDimension(); i++)
    {
    if ( m_Spacing[i] != spacing[i] )
      {
      m_Spacing[i] = spacing[i];
      modified = true;
      }
    }

  if ( modified )
    {
    this->Modified();
    }
}

/**
 *
 */
void
ImageBase
::SetOrigin(float *origin)
{
  bool modified = false;

  for (unsigned int i=0; i<this->GetDimension(); i++)
    {
    if ( m_Origin[i] != origin[i] )
      {
      m_Origin[i] = origin[i];
      modified = true;
      }
    }

  if ( modified )
    {
    this->Modified();
    }
}

/**
 *
 */
void
ImageBase
::PrintSelf(std::ostream& os, Indent indent)
{
  DataObject::PrintSelf(os,indent);
}

} // namespace itk
<|endoftext|>


<commit_before>
#include <qpdf/QPDF_Stream.hh>

#include <qpdf/QEXC.hh>
#include <qpdf/QUtil.hh>
#include <qpdf/Pipeline.hh>
#include <qpdf/Pl_Flate.hh>
#include <qpdf/Pl_PNGFilter.hh>
#include <qpdf/Pl_RC4.hh>
#include <qpdf/Pl_Buffer.hh>
#include <qpdf/Pl_ASCII85Decoder.hh>
#include <qpdf/Pl_ASCIIHexDecoder.hh>
#include <qpdf/Pl_LZWDecoder.hh>

#include <qpdf/QTC.hh>
#include <qpdf/QPDF.hh>
#include <qpdf/QPDFExc.hh>
#include <qpdf/Pl_QPDFTokenizer.hh>

QPDF_Stream::QPDF_Stream(QPDF* qpdf, int objid, int generation,
			 QPDFObjectHandle stream_dict,
			 off_t offset, int length) :
    qpdf(qpdf),
    objid(objid),
    generation(generation),
    stream_dict(stream_dict),
    offset(offset),
    length(length)
{
    if (! stream_dict.isDictionary())
    {
	throw QEXC::Internal("stream object instantiated with non-dictionary "
			     "object for dictionary");
    }
}

QPDF_Stream::~QPDF_Stream()
{
}

std::string
QPDF_Stream::unparse()
{
    // Unparse stream objects as indirect references
    return QUtil::int_to_string(this->objid) + " " +
	QUtil::int_to_string(this->generation) + " R";
}

QPDFObjectHandle
QPDF_Stream::getDict() const
{
    return this->stream_dict;
}

PointerHolder<Buffer>
QPDF_Stream::getStreamData()
{
    Pl_Buffer buf("stream data buffer");
    if (! pipeStreamData(&buf, true, false, false))
    {
	throw QPDFExc("getStreamData called on unfilterable stream");
    }
    return buf.getBuffer();
}

bool
QPDF_Stream::filterable(std::vector<std::string>& filters,
			int& predictor, int& columns,
			bool& early_code_change)
{
    // Initialize values to their defaults as per the PDF spec
    predictor = 1;
    columns = 0;
    early_code_change = true;

    bool filterable = true;

    // See if we can support any decode parameters that are specified.

    QPDFObjectHandle decode_obj =
	this->stream_dict.getKey("/DecodeParms");
    if (decode_obj.isNull())
    {
	// no problem
    }
    else if (decode_obj.isDictionary())
    {
	std::set<std::string> keys = decode_obj.getKeys();
	for (std::set<std::string>::iterator iter = keys.begin();
	     iter != keys.end(); ++iter)
	{
	    std::string const& key = *iter;
	    if (key == "/Predictor")
	    {
		QPDFObjectHandle predictor_obj = decode_obj.getKey(key);
		if (predictor_obj.isInteger())
		{
		    predictor = predictor_obj.getIntValue();
		    if (! ((predictor == 1) || (predictor == 12)))
		    {
			filterable = false;
		    }
		}
		else
		{
		    filterable = false;
		}
	    }
	    else if (key == "/EarlyChange")
	    {
		QPDFObjectHandle earlychange_obj = decode_obj.getKey(key);
		if (earlychange_obj.isInteger())
		{
		    int earlychange = earlychange_obj.getIntValue();
		    early_code_change = (earlychange == 1);
		    if (! ((earlychange == 0) || (earlychange == 1)))
		    {
			filterable = false;
		    }
		}
		else
		{
		    filterable = false;
		}
	    }
	    else if (key == "/Columns")
	    {
		QPDFObjectHandle columns_obj = decode_obj.getKey(key);
		if (columns_obj.isInteger())
		{
		    columns = columns_obj.getIntValue();
		}
		else
		{
		    filterable = false;
		}
	    }
	    else
	    {
		filterable = false;
	    }
	}
    }
    else
    {
	// Ignore for now -- some filter types, like CCITTFaxDecode,
	// use types other than dictionary for this.
    }

    if ((predictor > 1) && (columns == 0))
    {
	// invalid
	filterable = false;
    }

    if (! filterable)
    {
	return false;
    }

    // Check filters

    QPDFObjectHandle filter_obj = this->stream_dict.getKey("/Filter");
    bool filters_okay = true;

    if (filter_obj.isNull())
    {
	// No filters
    }
    else if (filter_obj.isName())
    {
	// One filter
	filters.push_back(filter_obj.getName());
    }
    else if (filter_obj.isArray())
    {
	// Potentially multiple filters
	int n = filter_obj.getArrayNItems();
	for (int i = 0; i < n; ++i)
	{
	    QPDFObjectHandle item = filter_obj.getArrayItem(i);
	    if (item.isName())
	    {
		filters.push_back(item.getName());
	    }
	    else
	    {
		filters_okay = false;
	    }
	}
    }
    else
    {
	filters_okay = false;
    }

    if (! filters_okay)
    {
	QTC::TC("qpdf", "QPDF_Stream invalid filter");
	throw QPDFExc(qpdf->getFilename(), this->offset,
		      "invalid filter object type for this stream");
    }

    // `filters' now contains a list of filters to be applied in
    // order.  See which ones we can support.

    for (std::vector<std::string>::iterator iter = filters.begin();
	 iter != filters.end(); ++iter)
    {
	std::string const& filter = *iter;
	if (! ((filter == "/FlateDecode") ||
	       (filter == "/LZWDecode") ||
	       (filter == "/ASCII85Decode") ||
	       (filter == "/ASCIIHexDecode")))
	{
	    filterable = false;
	}
    }

    return filterable;
}

bool
QPDF_Stream::pipeStreamData(Pipeline* pipeline, bool filter,
			    bool normalize, bool compress)
{
    std::vector<std::string> filters;
    int predictor = 1;
    int columns = 0;
    bool early_code_change = true;
    if (filter)
    {
	filter = filterable(filters, predictor, columns, early_code_change);
    }

    if (pipeline == 0)
    {
	QTC::TC("qpdf", "QPDF_Stream pipeStreamData with null pipeline");
	return filter;
    }

    // Construct the pipeline in reverse order.  Force pipelines we
    // create to be deleted when this function finishes.
    std::vector<PointerHolder<Pipeline> > to_delete;

    if (filter)
    {
	if (compress)
	{
	    pipeline = new Pl_Flate("compress object stream", pipeline,
				    Pl_Flate::a_deflate);
	    to_delete.push_back(pipeline);
	}

	if (normalize)
	{
	    pipeline = new Pl_QPDFTokenizer("normalizer", pipeline);
	    to_delete.push_back(pipeline);
	}

	for (std::vector<std::string>::reverse_iterator iter = filters.rbegin();
	     iter != filters.rend(); ++iter)
	{
	    std::string const& filter = *iter;
	    if (filter == "/FlateDecode")
	    {
		if (predictor == 12)
		{
		    QTC::TC("qpdf", "QPDF_Stream PNG filter");
		    pipeline = new Pl_PNGFilter(
			"png decode", pipeline, Pl_PNGFilter::a_decode,
			columns, 0 /* not used */);
		    to_delete.push_back(pipeline);
		}

		pipeline = new Pl_Flate("stream inflate",
					pipeline, Pl_Flate::a_inflate);
		to_delete.push_back(pipeline);
	    }
	    else if (filter == "/ASCII85Decode")
	    {
		pipeline = new Pl_ASCII85Decoder("ascii85 decode", pipeline);
		to_delete.push_back(pipeline);
	    }
	    else if (filter == "/ASCIIHexDecode")
	    {
		pipeline = new Pl_ASCIIHexDecoder("asciiHex decode", pipeline);
		to_delete.push_back(pipeline);
	    }
	    else if (filter == "/LZWDecode")
	    {
		pipeline = new Pl_LZWDecoder("lzw decode", pipeline,
					     early_code_change);
		to_delete.push_back(pipeline);
	    }
	    else
	    {
		throw QEXC::Internal("QPDFStream: unknown filter "
				     "encountered after check");
	    }
	}
    }

    QPDF::Pipe::pipeStreamData(this->qpdf, this->objid, this->generation,
			       this->offset, this->length,
			       this->stream_dict, pipeline);

    return filter;
}
<commit_msg>filterable = false for stream with unknown decode parameters<commit_after>
#include <qpdf/QPDF_Stream.hh>

#include <qpdf/QEXC.hh>
#include <qpdf/QUtil.hh>
#include <qpdf/Pipeline.hh>
#include <qpdf/Pl_Flate.hh>
#include <qpdf/Pl_PNGFilter.hh>
#include <qpdf/Pl_RC4.hh>
#include <qpdf/Pl_Buffer.hh>
#include <qpdf/Pl_ASCII85Decoder.hh>
#include <qpdf/Pl_ASCIIHexDecoder.hh>
#include <qpdf/Pl_LZWDecoder.hh>

#include <qpdf/QTC.hh>
#include <qpdf/QPDF.hh>
#include <qpdf/QPDFExc.hh>
#include <qpdf/Pl_QPDFTokenizer.hh>

QPDF_Stream::QPDF_Stream(QPDF* qpdf, int objid, int generation,
			 QPDFObjectHandle stream_dict,
			 off_t offset, int length) :
    qpdf(qpdf),
    objid(objid),
    generation(generation),
    stream_dict(stream_dict),
    offset(offset),
    length(length)
{
    if (! stream_dict.isDictionary())
    {
	throw QEXC::Internal("stream object instantiated with non-dictionary "
			     "object for dictionary");
    }
}

QPDF_Stream::~QPDF_Stream()
{
}

std::string
QPDF_Stream::unparse()
{
    // Unparse stream objects as indirect references
    return QUtil::int_to_string(this->objid) + " " +
	QUtil::int_to_string(this->generation) + " R";
}

QPDFObjectHandle
QPDF_Stream::getDict() const
{
    return this->stream_dict;
}

PointerHolder<Buffer>
QPDF_Stream::getStreamData()
{
    Pl_Buffer buf("stream data buffer");
    if (! pipeStreamData(&buf, true, false, false))
    {
	throw QPDFExc("getStreamData called on unfilterable stream");
    }
    return buf.getBuffer();
}

bool
QPDF_Stream::filterable(std::vector<std::string>& filters,
			int& predictor, int& columns,
			bool& early_code_change)
{
    // Initialize values to their defaults as per the PDF spec
    predictor = 1;
    columns = 0;
    early_code_change = true;

    bool filterable = true;

    // See if we can support any decode parameters that are specified.

    QPDFObjectHandle decode_obj =
	this->stream_dict.getKey("/DecodeParms");
    if (decode_obj.isNull())
    {
	// no problem
    }
    else if (decode_obj.isDictionary())
    {
	std::set<std::string> keys = decode_obj.getKeys();
	for (std::set<std::string>::iterator iter = keys.begin();
	     iter != keys.end(); ++iter)
	{
	    std::string const& key = *iter;
	    if (key == "/Predictor")
	    {
		QPDFObjectHandle predictor_obj = decode_obj.getKey(key);
		if (predictor_obj.isInteger())
		{
		    predictor = predictor_obj.getIntValue();
		    if (! ((predictor == 1) || (predictor == 12)))
		    {
			filterable = false;
		    }
		}
		else
		{
		    filterable = false;
		}
	    }
	    else if (key == "/EarlyChange")
	    {
		QPDFObjectHandle earlychange_obj = decode_obj.getKey(key);
		if (earlychange_obj.isInteger())
		{
		    int earlychange = earlychange_obj.getIntValue();
		    early_code_change = (earlychange == 1);
		    if (! ((earlychange == 0) || (earlychange == 1)))
		    {
			filterable = false;
		    }
		}
		else
		{
		    filterable = false;
		}
	    }
	    else if (key == "/Columns")
	    {
		QPDFObjectHandle columns_obj = decode_obj.getKey(key);
		if (columns_obj.isInteger())
		{
		    columns = columns_obj.getIntValue();
		}
		else
		{
		    filterable = false;
		}
	    }
	    else
	    {
		filterable = false;
	    }
	}
    }
    else
    {
	// Ignore for now -- some filter types, like CCITTFaxDecode,
	// use types other than dictionary for this.
	filterable = false;
    }

    if ((predictor > 1) && (columns == 0))
    {
	// invalid
	filterable = false;
    }

    if (! filterable)
    {
	return false;
    }

    // Check filters

    QPDFObjectHandle filter_obj = this->stream_dict.getKey("/Filter");
    bool filters_okay = true;

    if (filter_obj.isNull())
    {
	// No filters
    }
    else if (filter_obj.isName())
    {
	// One filter
	filters.push_back(filter_obj.getName());
    }
    else if (filter_obj.isArray())
    {
	// Potentially multiple filters
	int n = filter_obj.getArrayNItems();
	for (int i = 0; i < n; ++i)
	{
	    QPDFObjectHandle item = filter_obj.getArrayItem(i);
	    if (item.isName())
	    {
		filters.push_back(item.getName());
	    }
	    else
	    {
		filters_okay = false;
	    }
	}
    }
    else
    {
	filters_okay = false;
    }

    if (! filters_okay)
    {
	QTC::TC("qpdf", "QPDF_Stream invalid filter");
	throw QPDFExc(qpdf->getFilename(), this->offset,
		      "invalid filter object type for this stream");
    }

    // `filters' now contains a list of filters to be applied in
    // order.  See which ones we can support.

    for (std::vector<std::string>::iterator iter = filters.begin();
	 iter != filters.end(); ++iter)
    {
	std::string const& filter = *iter;
	if (! ((filter == "/FlateDecode") ||
	       (filter == "/LZWDecode") ||
	       (filter == "/ASCII85Decode") ||
	       (filter == "/ASCIIHexDecode")))
	{
	    filterable = false;
	}
    }

    return filterable;
}

bool
QPDF_Stream::pipeStreamData(Pipeline* pipeline, bool filter,
			    bool normalize, bool compress)
{
    std::vector<std::string> filters;
    int predictor = 1;
    int columns = 0;
    bool early_code_change = true;
    if (filter)
    {
	filter = filterable(filters, predictor, columns, early_code_change);
    }

    if (pipeline == 0)
    {
	QTC::TC("qpdf", "QPDF_Stream pipeStreamData with null pipeline");
	return filter;
    }

    // Construct the pipeline in reverse order.  Force pipelines we
    // create to be deleted when this function finishes.
    std::vector<PointerHolder<Pipeline> > to_delete;

    if (filter)
    {
	if (compress)
	{
	    pipeline = new Pl_Flate("compress object stream", pipeline,
				    Pl_Flate::a_deflate);
	    to_delete.push_back(pipeline);
	}

	if (normalize)
	{
	    pipeline = new Pl_QPDFTokenizer("normalizer", pipeline);
	    to_delete.push_back(pipeline);
	}

	for (std::vector<std::string>::reverse_iterator iter = filters.rbegin();
	     iter != filters.rend(); ++iter)
	{
	    std::string const& filter = *iter;
	    if (filter == "/FlateDecode")
	    {
		if (predictor == 12)
		{
		    QTC::TC("qpdf", "QPDF_Stream PNG filter");
		    pipeline = new Pl_PNGFilter(
			"png decode", pipeline, Pl_PNGFilter::a_decode,
			columns, 0 /* not used */);
		    to_delete.push_back(pipeline);
		}

		pipeline = new Pl_Flate("stream inflate",
					pipeline, Pl_Flate::a_inflate);
		to_delete.push_back(pipeline);
	    }
	    else if (filter == "/ASCII85Decode")
	    {
		pipeline = new Pl_ASCII85Decoder("ascii85 decode", pipeline);
		to_delete.push_back(pipeline);
	    }
	    else if (filter == "/ASCIIHexDecode")
	    {
		pipeline = new Pl_ASCIIHexDecoder("asciiHex decode", pipeline);
		to_delete.push_back(pipeline);
	    }
	    else if (filter == "/LZWDecode")
	    {
		pipeline = new Pl_LZWDecoder("lzw decode", pipeline,
					     early_code_change);
		to_delete.push_back(pipeline);
	    }
	    else
	    {
		throw QEXC::Internal("QPDFStream: unknown filter "
				     "encountered after check");
	    }
	}
    }

    QPDF::Pipe::pipeStreamData(this->qpdf, this->objid, this->generation,
			       this->offset, this->length,
			       this->stream_dict, pipeline);

    return filter;
}
<|endoftext|>


<commit_before>// -------------------------------------------------------------------
//
// hot_backup_test.cc
//
// Copyright (c) 2016 Basho Technologies, Inc. All Rights Reserved.
//
// This file is provided to you 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 <fcntl.h>
#include <libgen.h>
#include <string.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <unistd.h>

#include "util/testharness.h"
#include "util/testutil.h"

#include "db/dbformat.h"
#include "db/db_impl.h"
#include "util/hot_backup.h"

/**
 * Execution routine
 */
int main(int argc, char** argv)
{
  return leveldb::test::RunAllTests();
}

namespace leveldb {

/**
 * Wrapper class for tests.  Holds working variables
 * and helper functions.
 */
class HotBackupTester
{
public:
    HotBackupTester()
    {
    };

    ~HotBackupTester()
    {
    };
};  // class HotBackupTester

/**
 * Initial code used the existance of /etc/riak/hot_backup file
 *  as flag to start a backup.
 */
TEST(HotBackupTester, FileTriggerTest)
{
    char * dup_path, *path;
    int ret_val;
    bool ret_flag;
    uint64_t perf_before, perf_after;

    perf_before=gPerfCounters->Value(ePerfSyslogWrite);

    // cleanup anything existing, likely fails
    ///  hmm, should there be a way to move this trigger
    ///  to a "safe" area like /tmp?
    unlink(config::kTriggerFileName);

    // does parent path exist?
    dup_path=strdup(config::kTriggerFileName);
    path=dirname(dup_path);
    if (0!=access(path, F_OK))
    {
        // assumes only one path level needed
        //  (and that we are allowed to create it, unlikely in /etc)
        ret_val=mkdir(path, 0666);
        ASSERT_EQ(0, ret_val);
    }   // if
    free(dup_path);
    dup_path=NULL;

    // is a trigger seen (hope not)
    ret_flag=IsHotBackupTriggerSet();
    ASSERT_TRUE(!ret_flag);

    // make a trigger
    ret_val=open(config::kTriggerFileName, O_CREAT | O_RDWR, S_IRUSR | S_IWUSR);
    ASSERT_TRUE(-1!=ret_val);
    close(ret_val);

    // test the trigger
    ret_flag=IsHotBackupTriggerSet();
    ASSERT_TRUE(ret_flag);

    // pretend to be back process
    /// schedule twice
    HotBackupScheduled();
    HotBackupScheduled();

    // trigger still there?
    ret_flag=IsHotBackupTriggerSet();
    ASSERT_TRUE(ret_flag);

    // release one, trigger goes away
    HotBackupFinished();
    ret_flag=IsHotBackupTriggerSet();
    ASSERT_TRUE(!ret_flag);

    // did our simulation create a syslog entry?
    //  (bonus if you manually check /var/log/syslog for actual entries)
    perf_after=gPerfCounters->Value(ePerfSyslogWrite) - perf_before;
    ASSERT_TRUE( 1==perf_after );

    // clean up
    HotBackupFinished();

}   // FileTriggerTest

}  // namespace leveldb

<commit_msg>skip all tests if unable to access /etc/riak for writes<commit_after>// -------------------------------------------------------------------
//
// hot_backup_test.cc
//
// Copyright (c) 2016 Basho Technologies, Inc. All Rights Reserved.
//
// This file is provided to you 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 <fcntl.h>
#include <libgen.h>
#include <string.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <unistd.h>

#include "util/testharness.h"
#include "util/testutil.h"

#include "db/dbformat.h"
#include "db/db_impl.h"
#include "util/hot_backup.h"

/**
 * Execution routine
 */
int main(int argc, char** argv)
{
    char * dup_path, *path;
    int ret_val(0);

    // does parent path exist?
    //  bypass test if it does not ... Travis CI and
    //  other users might not be able to access /etc/riak
    dup_path=strdup(leveldb::config::kTriggerFileName);
    path=dirname(dup_path);

    if (0==access(path, R_OK | W_OK))
        ret_val=leveldb::test::RunAllTests();

    free(dup_path);
    dup_path=NULL;

    return(ret_val);
}

namespace leveldb {

/**
 * Wrapper class for tests.  Holds working variables
 * and helper functions.
 */
class HotBackupTester
{
public:
    HotBackupTester()
    {
    };

    ~HotBackupTester()
    {
    };
};  // class HotBackupTester

/**
 * Initial code used the existance of /etc/riak/hot_backup file
 *  as flag to start a backup.
 */
TEST(HotBackupTester, FileTriggerTest)
{
    char * dup_path, *path;
    int ret_val;
    bool ret_flag;
    uint64_t perf_before, perf_after;

    perf_before=gPerfCounters->Value(ePerfSyslogWrite);

    // cleanup anything existing, likely fails
    ///  hmm, should there be a way to move this trigger
    ///  to a "safe" area like /tmp?
    unlink(config::kTriggerFileName);

    // does parent path exist?
    //  bypass test if it does not ... Travis CI and
    //  other users might not be able to access /etc/riak
    dup_path=strdup(config::kTriggerFileName);
    path=dirname(dup_path);
    ret_val=access(path, R_OK | W_OK);
    ASSERT_TRUE(-1!=ret_val);
    free(dup_path);
    dup_path=NULL;

    // is a trigger seen (hope not)
    ret_flag=IsHotBackupTriggerSet();
    ASSERT_TRUE(!ret_flag);

    // make a trigger
    ret_val=open(config::kTriggerFileName, O_CREAT | O_RDWR, S_IRUSR | S_IWUSR);
    ASSERT_TRUE(-1!=ret_val);
    close(ret_val);

    // test the trigger
    ret_flag=IsHotBackupTriggerSet();
    ASSERT_TRUE(ret_flag);

    // pretend to be back process
    /// schedule twice
    HotBackupScheduled();
    HotBackupScheduled();

    // trigger still there?
    ret_flag=IsHotBackupTriggerSet();
    ASSERT_TRUE(ret_flag);

    // release one, trigger goes away
    HotBackupFinished();
    ret_flag=IsHotBackupTriggerSet();
    ASSERT_TRUE(!ret_flag);

    // did our simulation create a syslog entry?
    //  (bonus if you manually check /var/log/syslog for actual entries)
    perf_after=gPerfCounters->Value(ePerfSyslogWrite) - perf_before;
    ASSERT_TRUE( 1==perf_after );

    // clean up second count.
    HotBackupFinished();

}   // FileTriggerTest

}  // namespace leveldb

<|endoftext|>


<commit_before>// Ceres Solver - A fast non-linear least squares minimizer
// Copyright 2012 Google Inc. All rights reserved.
// http://code.google.com/p/ceres-solver/
//
// 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 Google Inc. nor the names of its contributors may be
//   used to endorse or promote products derived from this software without
//   specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
// POSSIBILITY OF SUCH DAMAGE.
//
// Author: keir@google.com (Keir Mierle)

#include "ceres/block_jacobi_preconditioner.h"

#include "Eigen/Cholesky"
#include "ceres/block_sparse_matrix.h"
#include "ceres/block_structure.h"
#include "ceres/casts.h"
#include "ceres/integral_types.h"
#include "ceres/internal/eigen.h"

namespace ceres {
namespace internal {

BlockJacobiPreconditioner::BlockJacobiPreconditioner(
    const LinearOperator& A)
    : block_structure_(
        *(down_cast<const BlockSparseMatrix*>(&A)->block_structure())),
      num_rows_(A.num_rows()) {
  // Calculate the amount of storage needed.
  int storage_needed = 0;
  for (int c = 0; c < block_structure_.cols.size(); ++c) {
    int size = block_structure_.cols[c].size;
    storage_needed += size * size;
  }

  // Size the offsets and storage.
  blocks_.resize(block_structure_.cols.size());
  block_storage_.resize(storage_needed);

  // Put pointers to the storage in the offsets.
  double* block_cursor = &block_storage_[0];
  for (int c = 0; c < block_structure_.cols.size(); ++c) {
    int size = block_structure_.cols[c].size;
    blocks_[c] = block_cursor;
    block_cursor += size * size;
  }
}

BlockJacobiPreconditioner::~BlockJacobiPreconditioner() {
}

void BlockJacobiPreconditioner::Update(const LinearOperator& matrix, const double* D) {
  const BlockSparseMatrix& A = *(down_cast<const BlockSparseMatrix*>(&matrix));
  const CompressedRowBlockStructure* bs = A.block_structure();

  // Compute the diagonal blocks by block inner products.
  std::fill(block_storage_.begin(), block_storage_.end(), 0.0);
  for (int r = 0; r < bs->rows.size(); ++r) {
    const int row_block_size = bs->rows[r].block.size;
    const vector<Cell>& cells = bs->rows[r].cells;
    const double* row_values = A.RowBlockValues(r);
    for (int c = 0; c < cells.size(); ++c) {
      const int col_block_size = bs->cols[cells[c].block_id].size;
      ConstMatrixRef m(row_values + cells[c].position,
                       row_block_size,
                       col_block_size);

      MatrixRef(blocks_[cells[c].block_id],
                col_block_size,
                col_block_size).noalias() += m.transpose() * m;

      // TODO(keir): Figure out when the below expression is actually faster
      // than doing the full rank update. The issue is that for smaller sizes,
      // the rankUpdate() function is slower than the full product done above.
      //
      // On the typical bundling problems, the above product is ~5% faster.
      //
      //   MatrixRef(blocks_[cells[c].block_id],
      //             col_block_size,
      //             col_block_size).selfadjointView<Eigen::Upper>().rankUpdate(m);
      //
    }
  }

  // Add the diagonal and invert each block.
  for (int c = 0; c < bs->cols.size(); ++c) {
    const int size = block_structure_.cols[c].size;
    const int position = block_structure_.cols[c].position;
    MatrixRef DD(blocks_[c], size, size);

    DD.diagonal() += ConstVectorRef(D + position, size).array().square().matrix();

    DD = DD.selfadjointView<Eigen::Upper>()
           .ldlt()
           .solve(Matrix::Identity(size, size));
  }
}

void BlockJacobiPreconditioner::RightMultiply(const double* x, double* y) const {
  for (int c = 0; c < block_structure_.cols.size(); ++c) {
    const int size = block_structure_.cols[c].size;
    const int position = block_structure_.cols[c].position;
    ConstMatrixRef D(blocks_[c], size, size);
    ConstVectorRef x_block(x + position, size);
    VectorRef y_block(y + position, size);
    y_block += D * x_block;
  }
}

void BlockJacobiPreconditioner::LeftMultiply(const double* x, double* y) const {
  RightMultiply(x, y);
}

}  // namespace internal
}  // namespace ceres
<commit_msg>Small tweaks to the block jacobi preconditioner.<commit_after>// Ceres Solver - A fast non-linear least squares minimizer
// Copyright 2012 Google Inc. All rights reserved.
// http://code.google.com/p/ceres-solver/
//
// 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 Google Inc. nor the names of its contributors may be
//   used to endorse or promote products derived from this software without
//   specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
// POSSIBILITY OF SUCH DAMAGE.
//
// Author: keir@google.com (Keir Mierle)

#include "ceres/block_jacobi_preconditioner.h"

#include "Eigen/Cholesky"
#include "ceres/block_sparse_matrix.h"
#include "ceres/block_structure.h"
#include "ceres/casts.h"
#include "ceres/integral_types.h"
#include "ceres/internal/eigen.h"

namespace ceres {
namespace internal {

BlockJacobiPreconditioner::BlockJacobiPreconditioner(
    const LinearOperator& A)
    : block_structure_(
        *(down_cast<const BlockSparseMatrix*>(&A)->block_structure())),
      num_rows_(A.num_rows()) {
  // Calculate the amount of storage needed.
  int storage_needed = 0;
  for (int c = 0; c < block_structure_.cols.size(); ++c) {
    int size = block_structure_.cols[c].size;
    storage_needed += size * size;
  }

  // Size the offsets and storage.
  blocks_.resize(block_structure_.cols.size());
  block_storage_.resize(storage_needed);

  // Put pointers to the storage in the offsets.
  double* block_cursor = &block_storage_[0];
  for (int c = 0; c < block_structure_.cols.size(); ++c) {
    int size = block_structure_.cols[c].size;
    blocks_[c] = block_cursor;
    block_cursor += size * size;
  }
}

BlockJacobiPreconditioner::~BlockJacobiPreconditioner() {
}

void BlockJacobiPreconditioner::Update(const LinearOperator& matrix, const double* D) {
  const BlockSparseMatrix& A = *(down_cast<const BlockSparseMatrix*>(&matrix));
  const CompressedRowBlockStructure* bs = A.block_structure();

  // Compute the diagonal blocks by block inner products.
  std::fill(block_storage_.begin(), block_storage_.end(), 0.0);
  for (int r = 0; r < bs->rows.size(); ++r) {
    const int row_block_size = bs->rows[r].block.size;
    const vector<Cell>& cells = bs->rows[r].cells;
    const double* row_values = A.RowBlockValues(r);
    for (int c = 0; c < cells.size(); ++c) {
      const int col_block_size = bs->cols[cells[c].block_id].size;
      ConstMatrixRef m(row_values + cells[c].position,
                       row_block_size,
                       col_block_size);

      MatrixRef(blocks_[cells[c].block_id],
                col_block_size,
                col_block_size).noalias() += m.transpose() * m;

      // TODO(keir): Figure out when the below expression is actually faster
      // than doing the full rank update. The issue is that for smaller sizes,
      // the rankUpdate() function is slower than the full product done above.
      //
      // On the typical bundling problems, the above product is ~5% faster.
      //
      //   MatrixRef(blocks_[cells[c].block_id],
      //             col_block_size,
      //             col_block_size).selfadjointView<Eigen::Upper>().rankUpdate(m);
      //
    }
  }

  // Add the diagonal and invert each block.
  for (int c = 0; c < bs->cols.size(); ++c) {
    const int size = block_structure_.cols[c].size;
    const int position = block_structure_.cols[c].position;
    MatrixRef block(blocks_[c], size, size);

    if (D != NULL) {
      block.diagonal() += ConstVectorRef(D + position, size).array().square().matrix();
    }

    block = block.selfadjointView<Eigen::Upper>()
                 .ldlt()
                 .solve(Matrix::Identity(size, size));
  }
}

void BlockJacobiPreconditioner::RightMultiply(const double* x, double* y) const {
  for (int c = 0; c < block_structure_.cols.size(); ++c) {
    const int size = block_structure_.cols[c].size;
    const int position = block_structure_.cols[c].position;
    ConstMatrixRef D(blocks_[c], size, size);
    ConstVectorRef x_block(x + position, size);
    VectorRef y_block(y + position, size);
    y_block += D * x_block;
  }
}

void BlockJacobiPreconditioner::LeftMultiply(const double* x, double* y) const {
  RightMultiply(x, y);
}

}  // namespace internal
}  // namespace ceres
<|endoftext|>


<commit_before>#include <stdio.h>
#include <stdlib.h>

#define N_FIELDS 7
#define N_FUNCS 128
#define FUNCSPACING 10
#define N_STRUCTS 300 /* 1280 */
// FIXME: Need final overrider logic for 3 or more if we turn on virtual base
//        class dups
#define N_BASES 30 /* 30 */

const char *simple_types[] = { "bool", "char", "short", "int", "float",
			       "double", "long double", "wchar_t", "void *",
			       "char *"
};

void gl(const char *c) {
  printf("%s\n", c);
}

void g(const char *c) {
  printf("%s", c);
}

void g(int i) {
  printf("%d", i);
}

int vfn = 0;
char base_present[N_STRUCTS][N_STRUCTS];

bool is_ambiguous(int s, int base) {
  for (int i = 0; i < N_STRUCTS; ++i) {
    if ((base_present[base][i] & base_present[s][i])
	// FIXME: todo this, we need final overrider additions
	/*== 1 */)
      return true;
  }
  return false;
}

void add_bases(int s, int base) {
  for (int i = 0; i < N_STRUCTS; ++i)
    base_present[s][i] |= base_present[base][i];
}

void gs(int s) {
  bool polymorphic = false;

  static int bases[N_BASES];
  int i_bases = random() % (N_BASES*2);
  if (i_bases >= N_BASES)
    // PARAM: 1/2 of all clases should have no bases
    i_bases = 0;
  int n_bases = 0;
  bool first_base = true;

  // PARAM: 3/4 of all should be class, the rest are structs
  if (random() % 4 == 0)
    g("struct s");
  else
    g("class s");
  g(s);
  int old_base = -1;
  if (s == 0)
    i_bases = 0;
  while (i_bases) {
    --i_bases;
    int base = random() % s;
    if (!base_present[s][base]) {
      if (is_ambiguous(s, base))
	continue;
      if (first_base) {
	first_base = false;
	g(": ");
      } else
	g(", ");
      int base_type = 1;
      if (random()%8 == 0) {
	// PARAM: 1/8th the bases are virtual
	g("virtual ");
	polymorphic = true;
	base_type = 3;
      }
      switch (random()%8) {
      case 0:
      case 1:
      case 2:
      case 3:
	break;
      case 4:
      case 5:
	g("public "); break;
      case 6:
	g("private "); break;
      case 7:
	g("protected "); break;
      }
      g("s");
      add_bases(s, base);
      bases[n_bases] = base;
      base_present[s][base] = base_type;
      ++n_bases;
      g(base);
      old_base = base;
    }
  }
  gl(" {");

  /* Fields */
  int n_fields = random() % (N_FIELDS*4);
  // PARAM: 3/4 of all structs should have no members
  if (n_fields >= N_FIELDS)
    n_fields = 0;
  for (int i = 0; i < n_fields; ++i) {
    int t = random() % (sizeof(simple_types) / sizeof(simple_types[0]));
    g("  "); g(simple_types[t]); g(" field"); g(i); gl(";");
  }

  /* Virtual functions */
  static int funcs[N_FUNCS];
  int n_funcs = random() % N_FUNCS;
  int old_func = -1;
  for (int i = 0; i < n_funcs; ++i) {
    int fn = old_func + random() % FUNCSPACING + 1;
    funcs[i] = fn;
    g("  virtual void fun"); g(fn); g("(char *t) { mix((char *)this - t); mix("); g(++vfn); gl("); }");
    old_func = fn;
  }

  gl("public:");
  gl("  void calc(char *t) {");

  // mix in the type number
  g("    mix("); g(s); gl(");");
  // mix in the size
  g("    mix(sizeof (s"); g(s); gl("));");
  // mix in the this offset
  gl("    mix((char *)this - t);");
  if (n_funcs)
    polymorphic = true;
  if (polymorphic) {
    // mix in offset to the complete object under construction
    gl("    mix(t - (char *)dynamic_cast<void*>(this));");
  }

  /* check base layout and overrides */
  for (int i = 0; i < n_bases; ++i) {
    g("    calc_s"); g(bases[i]); gl("(t);");
  }

  if (polymorphic) {
    /* check dynamic_cast to each direct base */
    for (int i = 0; i < n_bases; ++i) {
      g("    if ((char *)dynamic_cast<s"); g(bases[i]); gl("*>(this))");
      g("      mix(t - (char *)dynamic_cast<s"); g(bases[i]); gl("*>(this));");
      gl("    else mix(666);");
    }
  }

  /* check field layout */
  for (int i = 0; i < n_fields; ++i) {
    g("    mix((char *)&field"); g(i); gl(" - (char *)this);");
  }
  if (n_fields == 0)
    gl("    mix(42);");

  /* check functions */
  for (int i = 0; i < n_funcs; ++i) {
    g("    fun"); g(funcs[i]); gl("(t);");
  }
  if (n_funcs == 0)
    gl("    mix(13);");

  gl("  }");

  // default ctor
  g("  s"); g(s); g("() ");
  first_base = true;
  for (int i = 0; i < n_bases; ++i) {
    if (first_base) {
      g(": ");
      first_base = false;
    } else
      g(", ");
    g("s"); g(bases[i]); g("((char *)this)");
  }
  gl(" { calc((char *)this); }");
  g("  ~s"); g(s); gl("() { calc((char *)this); }");

 // ctor with this to the complete object
  g("  s"); g(s); gl("(char *t) { calc(t); }");
  g("  void calc_s"); g(s); gl("(char *t) { calc(t); }");
  g("} a"); g(s); gl(";");
}

main(int argc, char **argv) {
  unsigned seed = 0;
  char state[16];
  if (argc > 1)
    seed = atol(argv[1]);

  initstate(seed, state, sizeof(state));
  gl("extern \"C\" int printf(const char *...);");
  gl("");
  gl("long long sum;");
  gl("void mix(long long i) {");
  // If this ever becomes too slow, we can remove this after we improve the
  // mixing function
  gl("  printf(\"%llx\\n\", i);");
  gl("  sum += ((sum ^ i) << 3) + (sum<<1) - i;");
  gl("}");
  gl("");
  // PARAM: Randomly size testcases or large testcases?
  int n_structs = /* random() % */ N_STRUCTS;
  for (int i = 0; i < n_structs; ++i)
    gs(i);
  gl("int main() {");
  gl("  printf(\"%llx\\n\", sum);");
  gl("}");
  return 0;
}
<commit_msg>Add a descriptive tag to each line to make the exact differences easier to understand.<commit_after>#include <stdio.h>
#include <stdlib.h>

#define N_FIELDS 7
#define N_FUNCS 128
#define FUNCSPACING 10
#define N_STRUCTS 300 /* 1280 */
// FIXME: Need final overrider logic for 3 or more if we turn on virtual base
//        class dups
#define N_BASES 30 /* 30 */

const char *simple_types[] = { "bool", "char", "short", "int", "float",
			       "double", "long double", "wchar_t", "void *",
			       "char *"
};

void gl(const char *c) {
  printf("%s\n", c);
}

void g(const char *c) {
  printf("%s", c);
}

void g(int i) {
  printf("%d", i);
}

int vfn = 0;
char base_present[N_STRUCTS][N_STRUCTS];

bool is_ambiguous(int s, int base) {
  for (int i = 0; i < N_STRUCTS; ++i) {
    if ((base_present[base][i] & base_present[s][i])
	// FIXME: todo this, we need final overrider additions
	/*== 1 */)
      return true;
  }
  return false;
}

void add_bases(int s, int base) {
  for (int i = 0; i < N_STRUCTS; ++i)
    base_present[s][i] |= base_present[base][i];
}

void gs(int s) {
  bool polymorphic = false;

  static int bases[N_BASES];
  int i_bases = random() % (N_BASES*2);
  if (i_bases >= N_BASES)
    // PARAM: 1/2 of all clases should have no bases
    i_bases = 0;
  int n_bases = 0;
  bool first_base = true;

  // PARAM: 3/4 of all should be class, the rest are structs
  if (random() % 4 == 0)
    g("struct s");
  else
    g("class s");
  g(s);
  int old_base = -1;
  if (s == 0)
    i_bases = 0;
  while (i_bases) {
    --i_bases;
    int base = random() % s;
    if (!base_present[s][base]) {
      if (is_ambiguous(s, base))
	continue;
      if (first_base) {
	first_base = false;
	g(": ");
      } else
	g(", ");
      int base_type = 1;
      if (random()%8 == 0) {
	// PARAM: 1/8th the bases are virtual
	g("virtual ");
	polymorphic = true;
	base_type = 3;
      }
      switch (random()%8) {
      case 0:
      case 1:
      case 2:
      case 3:
	break;
      case 4:
      case 5:
	g("public "); break;
      case 6:
	g("private "); break;
      case 7:
	g("protected "); break;
      }
      g("s");
      add_bases(s, base);
      bases[n_bases] = base;
      base_present[s][base] = base_type;
      ++n_bases;
      g(base);
      old_base = base;
    }
  }
  gl(" {");

  /* Fields */
  int n_fields = random() % (N_FIELDS*4);
  // PARAM: 3/4 of all structs should have no members
  if (n_fields >= N_FIELDS)
    n_fields = 0;
  for (int i = 0; i < n_fields; ++i) {
    int t = random() % (sizeof(simple_types) / sizeof(simple_types[0]));
    g("  "); g(simple_types[t]); g(" field"); g(i); gl(";");
  }

  /* Virtual functions */
  static int funcs[N_FUNCS];
  int n_funcs = random() % N_FUNCS;
  int old_func = -1;
  for (int i = 0; i < n_funcs; ++i) {
    int fn = old_func + random() % FUNCSPACING + 1;
    funcs[i] = fn;
    g("  virtual void fun"); g(fn); g("(char *t) { mix(\"vfn this offset\", (char *)this - t); mix(\"vfn uuid\", "); g(++vfn); gl("); }");
    old_func = fn;
  }

  gl("public:");
  gl("  void calc(char *t) {");

  // mix in the type number
  g("    mix(\"type num\", "); g(s); gl(");");
  // mix in the size
  g("    mix(\"type size\", sizeof (s"); g(s); gl("));");
  // mix in the this offset
  gl("    mix(\"subobject offset\", (char *)this - t);");
  if (n_funcs)
    polymorphic = true;
  if (polymorphic) {
    // mix in offset to the complete object under construction
    gl("    mix(\"real top v current top\", t - (char *)dynamic_cast<void*>(this));");
  }

  /* check base layout and overrides */
  for (int i = 0; i < n_bases; ++i) {
    g("    calc_s"); g(bases[i]); gl("(t);");
  }

  if (polymorphic) {
    /* check dynamic_cast to each direct base */
    for (int i = 0; i < n_bases; ++i) {
      g("    if ((char *)dynamic_cast<s"); g(bases[i]); gl("*>(this))");
      g("      mix(\"base dyn cast\", t - (char *)dynamic_cast<s"); g(bases[i]); gl("*>(this));");
      gl("    else mix(\"no dyncast\", 666);");
    }
  }

  /* check field layout */
  for (int i = 0; i < n_fields; ++i) {
    g("    mix(\"field offset\", (char *)&field"); g(i); gl(" - (char *)this);");
  }
  if (n_fields == 0)
    gl("    mix(\"no fields\", 42);");

  /* check functions */
  for (int i = 0; i < n_funcs; ++i) {
    g("    fun"); g(funcs[i]); gl("(t);");
  }
  if (n_funcs == 0)
    gl("    mix(\"no funcs\", 13);");

  gl("  }");

  // default ctor
  g("  s"); g(s); g("() ");
  first_base = true;
  for (int i = 0; i < n_bases; ++i) {
    if (first_base) {
      g(": ");
      first_base = false;
    } else
      g(", ");
    g("s"); g(bases[i]); g("((char *)this)");
  }
  gl(" { calc((char *)this); }");
  g("  ~s"); g(s); gl("() { calc((char *)this); }");

 // ctor with this to the complete object
  g("  s"); g(s); gl("(char *t) { calc(t); }");
  g("  void calc_s"); g(s); gl("(char *t) { calc(t); }");
  g("} a"); g(s); gl(";");
}

main(int argc, char **argv) {
  unsigned seed = 0;
  char state[16];
  if (argc > 1)
    seed = atol(argv[1]);

  initstate(seed, state, sizeof(state));
  gl("extern \"C\" int printf(const char *...);");
  gl("");
  gl("long long sum;");
  gl("void mix(const char *desc, long long i) {");
  // If this ever becomes too slow, we can remove this after we improve the
  // mixing function
  gl("  printf(\"%s: %lld\\n\", desc, i);");
  gl("  sum += ((sum ^ i) << 3) + (sum<<1) - i;");
  gl("}");
  gl("");
  // PARAM: Randomly size testcases or large testcases?
  int n_structs = /* random() % */ N_STRUCTS;
  for (int i = 0; i < n_structs; ++i)
    gs(i);
  gl("int main() {");
  gl("  printf(\"%llx\\n\", sum);");
  gl("}");
  return 0;
}
<|endoftext|>


<commit_before><commit_msg>vcldemo: initial bitmap tests.<commit_after><|endoftext|>


<commit_before>/*************************************************************************
 *
 *  $RCSfile: TestCppComponent.cxx,v $
 *
 *  $Revision: 1.5 $
 *
 *  last change: $Author: kz $ $Date: 2006-11-06 14:59:41 $
 *
 *  The Contents of this file are made available subject to the terms of
 *  the BSD license.
 *
 *  Copyright (c) 2003 by Sun Microsystems, Inc.
 *  All rights reserved.
 *
 *  Redistribution and use in source and binary forms, with or without
 *  modification, are permitted provided that the following conditions
 *  are met:
 *  1. Redistributions of source code must retain the above copyright
 *     notice, this list of conditions and the following disclaimer.
 *  2. 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.
 *  3. Neither the name of Sun Microsystems, Inc. nor the names of its
 *     contributors may be used to endorse or promote products derived
 *     from this software without specific prior written permission.
 *
 *  THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 *  "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
 *  LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
 *  FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
 *  COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
 *  INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
 *  BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
 *  OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
 *  ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR
 *  TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE
 *  USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 *
 *************************************************************************/

#include <iostream>
#include <cppuhelper/bootstrap.hxx>
#include <com/sun/star/bridge/XUnoUrlResolver.hpp>
#include <com/sun/star/frame/XComponentLoader.hpp>
#include <my_module/MyService1.hpp>
#include <my_module/MyService2.hpp>

using namespace std;
using namespace rtl;
using namespace com::sun::star::uno;
//namespace cssuno = ::com::sun::star::uno;
using namespace com::sun::star::lang;
using namespace com::sun::star::frame;

int SAL_CALL main( int, char ** )
{
    try
    {
        // get the remote office component context
        Reference< XComponentContext > xContext( ::cppu::bootstrap() );
        cout << "\nconnected to a running office...\n";

        // create a new instance of MyService1
        Reference<my_module::XSomething> xSomething =
            my_module::MyService1::create(xContext);

        // call methodOne and print the return value on stdout
        OUString s = xSomething->methodOne(OUString(RTL_CONSTASCII_USTRINGPARAM("Hello World!")));
        cout << "\nCreate new instance of MyService1\n"
             << "Call of XSomething.methOne at MyService1 = "
             << OUStringToOString( s, RTL_TEXTENCODING_ASCII_US ).getStr();

        // create a new instance of MyService2 with the specified string argument
        xSomething = my_module::MyService2::create(xContext, OUString(RTL_CONSTASCII_USTRINGPARAM("Hello My World!")));

        // call methodTwo and print the return value of methodTwo
        s = xSomething->methodTwo();
        cout << "\n\nCreate new instance of MyService2 with argument\n"
             << "Call of XSomething.methTwo at MyService2 = "
             << OUStringToOString( s, RTL_TEXTENCODING_ASCII_US ).getStr();

        cout <<"\n\nPlease press 'return' to finish the example!\n";
        getchar();
    }
    catch ( ::cppu::BootstrapException & e )
    {
        cerr << "\ncaught BootstrapException: "
             << OUStringToOString( e.getMessage(), RTL_TEXTENCODING_ASCII_US ).getStr()
             << '\n';
        return 1;
    }
    catch ( Exception & e )
    {
        cerr << "\ncaught UNO exception: "
             << OUStringToOString( e.Message, RTL_TEXTENCODING_ASCII_US ).getStr()
             << '\n';
        return 1;
    }

    return 0;
}
<commit_msg>INTEGRATION: CWS jsc21 (1.5.92); FILE MERGED 2008/07/07 11:37:32 jsc 1.5.92.1: #i88797# adapted<commit_after>/*************************************************************************
 *
 *  $RCSfile: TestCppComponent.cxx,v $
 *
 *  $Revision: 1.6 $
 *
 *  last change: $Author: rt $ $Date: 2008-07-11 14:18:02 $
 *
 *  The Contents of this file are made available subject to the terms of
 *  the BSD license.
 *
 *  Copyright (c) 2003 by Sun Microsystems, Inc.
 *  All rights reserved.
 *
 *  Redistribution and use in source and binary forms, with or without
 *  modification, are permitted provided that the following conditions
 *  are met:
 *  1. Redistributions of source code must retain the above copyright
 *     notice, this list of conditions and the following disclaimer.
 *  2. 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.
 *  3. Neither the name of Sun Microsystems, Inc. nor the names of its
 *     contributors may be used to endorse or promote products derived
 *     from this software without specific prior written permission.
 *
 *  THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 *  "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
 *  LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
 *  FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
 *  COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
 *  INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
 *  BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
 *  OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
 *  ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR
 *  TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE
 *  USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 *
 *************************************************************************/

#include <stdio.h>
#include <cppuhelper/bootstrap.hxx>
#include <com/sun/star/bridge/XUnoUrlResolver.hpp>
#include <com/sun/star/frame/XComponentLoader.hpp>
#include <my_module/MyService1.hpp>
#include <my_module/MyService2.hpp>

using namespace rtl;
using namespace com::sun::star::uno;
//namespace cssuno = ::com::sun::star::uno;
using namespace com::sun::star::lang;
using namespace com::sun::star::frame;

int SAL_CALL main( int, char ** )
{
    try
    {
        // get the remote office component context
        Reference< XComponentContext > xContext( ::cppu::bootstrap() );
        fprintf(stdout, "\nconnected to a running office...\n");

        // create a new instance of MyService1
        Reference<my_module::XSomething> xSomething =
            my_module::MyService1::create(xContext);

        // call methodOne and print the return value on stdout
        OUString s = xSomething->methodOne(OUString(RTL_CONSTASCII_USTRINGPARAM("Hello World!")));
        fprintf(stdout,"\nCreate new instance of MyService1\nCall of XSomething.methOne at MyService1 = %s", OUStringToOString( s, RTL_TEXTENCODING_ASCII_US ).getStr());

        // create a new instance of MyService2 with the specified string argument
        xSomething = my_module::MyService2::create(xContext, OUString(RTL_CONSTASCII_USTRINGPARAM("Hello My World!")));

        // call methodTwo and print the return value of methodTwo
        s = xSomething->methodTwo();
        fprintf(stdout, "\n\nCreate new instance of MyService2 with argument\nCall of XSomething.methTwo at MyService2 = %s", OUStringToOString( s, RTL_TEXTENCODING_ASCII_US ).getStr());

        fprintf(stdout, "\n\nPlease press 'return' to finish the example!\n");
        getchar();
    }
    catch ( ::cppu::BootstrapException & e )
    {
        fprintf(stderr, "\ncaught BootstrapException: %s\n",
                OUStringToOString( e.getMessage(), RTL_TEXTENCODING_ASCII_US ).getStr());
        return 1;
    }
    catch ( Exception & e )
    {
        fprintf(stderr, "\ncaught UNO exception: %s\n",
                OUStringToOString( e.Message, RTL_TEXTENCODING_ASCII_US ).getStr());
        return 1;
    }

    return 0;
}
<|endoftext|>


<commit_before>/* component.cpp
   Copyright (C) 2005 Tommi Maekitalo

This file is part of tntnet.

Tntnet 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.

Tntnet 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 tntnet; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330,
Boston, MA  02111-1307  USA
*/

#include "tnt/ecppc/component.h"

namespace tnt
{
  namespace ecppc
  {
    ////////////////////////////////////////////////////////////////////////
    // component
    //
    void component::getBody(std::ostream& body) const
    {

      body << "  // <%args>\n";

      getArgs(body);

      body << "  // </%args>\n\n";

      getScopevars(body);

      body << "  // <%cpp>\n";

      compbody.getBody(body);

      body << "  // <%/cpp>\n"
           << "  return HTTP_OK;\n";
    }

    void component::getArgs(std::ostream& body) const
    {
      for (variables_type::const_iterator it = args.begin();
           it != args.end(); ++it)
        it->getParamCode(body);
    }

    void component::getScopevars(std::ostream& body) const
    {
      for (scopevars_type::const_iterator it = scopevars.begin();
           it != scopevars.end(); ++it)
      {
        it->get(body);
      }
    }
  }
}
<commit_msg>define scopevars before query-args, so they can be used as default values<commit_after>/* component.cpp
   Copyright (C) 2005 Tommi Maekitalo

This file is part of tntnet.

Tntnet 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.

Tntnet 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 tntnet; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330,
Boston, MA  02111-1307  USA
*/

#include "tnt/ecppc/component.h"

namespace tnt
{
  namespace ecppc
  {
    ////////////////////////////////////////////////////////////////////////
    // component
    //
    void component::getBody(std::ostream& body) const
    {
      getScopevars(body);

      body << "  // <%args>\n";

      getArgs(body);

      body << "  // </%args>\n\n";

      body << "  // <%cpp>\n";

      compbody.getBody(body);

      body << "  // <%/cpp>\n"
           << "  return HTTP_OK;\n";
    }

    void component::getArgs(std::ostream& body) const
    {
      for (variables_type::const_iterator it = args.begin();
           it != args.end(); ++it)
        it->getParamCode(body);
    }

    void component::getScopevars(std::ostream& body) const
    {
      for (scopevars_type::const_iterator it = scopevars.begin();
           it != scopevars.end(); ++it)
      {
        it->get(body);
      }
    }
  }
}
<|endoftext|>


<commit_before>// #include <boost/test/unit_test.hpp>
#include <boost/test/minimal.hpp>
#include "qwerty_keyboard.h"

int test_main(int, char *[]) {

    Qwerty_keyboard kb;

    BOOST_CHECK(kb.letter_at_offset_from(-1, 'y') == 't');
    BOOST_CHECK(kb.letter_at_offset_from(1, 'y') == 'u');

    // Boundary conditions
    BOOST_CHECK(kb.letter_at_offset_from(1, 'p') == 'q');
    BOOST_CHECK(kb.letter_at_offset_from(-1, 'q') == 'p');

    BOOST_CHECK(kb.letter_at_offset_from(2, 'l') == 's');
    BOOST_CHECK(kb.letter_at_offset_from(-2, 'z') == 'n');

    BOOST_CHECK(kb.letter_at_offset_from(1, 'G') == 'h');

    const std::string input = "Gwkki";
    const std::string expected = "hello";
    std::string output = "";
    for(char c : input)
        output += kb.letter_at_offset_from(1, c);
    BOOST_CHECK(output == expected);

    //  Should throw exception.
    BOOST_CHECK_THROW(kb.letter_at_offset_from(1, '/'), std::runtime_error);

    return 0;
}<commit_msg>Does not compile. Fix later.<commit_after>// qwerty_keyboard_test.cpp
// Build using: g++ -ggdb -std=c++0x -Wall -o qk_test qwerty_keyboard_test.cpp -lboost_unit_test_framework
// #include <boost/test/unit_test.hpp>
#include <boost/test/minimal.hpp>
#include "../qwerty_keyboard.h"

int test_main(int, char *[]) {

    Qwerty_keyboard kb;

    BOOST_CHECK(kb.letter_at_offset_from(-1, 'y') == 't');
    BOOST_CHECK(kb.letter_at_offset_from(1, 'y') == 'u');

    // Boundary conditions
    BOOST_CHECK(kb.letter_at_offset_from(1, 'p') == 'q');
    BOOST_CHECK(kb.letter_at_offset_from(-1, 'q') == 'p');

    BOOST_CHECK(kb.letter_at_offset_from(2, 'l') == 's');
    BOOST_CHECK(kb.letter_at_offset_from(-2, 'z') == 'n');

    BOOST_CHECK(kb.letter_at_offset_from(1, 'G') == 'h');

    const std::string input = "Gwkki";
    const std::string expected = "hello";
    std::string output = "";
    for(char c : input)
        output += kb.letter_at_offset_from(1, c);
    BOOST_CHECK(output == expected);

    //  Should throw exception.
    BOOST_CHECK_THROW(kb.letter_at_offset_from(1, '/'), std::runtime_error);

    return 0;
}<|endoftext|>