<commit_before>
//! [Activator]
#include "DictionaryService.h"

#include <usModuleActivator.h>
#include <usModuleContext.h>
#include <usServiceProperties.h>

// Replace that include with your own base class declaration
#include US_BASECLASS_HEADER

#include <algorithm>
#include <memory>

US_USE_NAMESPACE

/**
 * This class implements a module activator that uses the module
 * context to register an English language dictionary service
 * with the C++ Micro Services registry during static initialization
 * of the module. The dictionary service interface is
 * defined in a separate file and is implemented by a nested class.
 */
class US_ABI_LOCAL MyActivator : public ModuleActivator
{

private:

  /**
   * A private inner class that implements a dictionary service;
   * see DictionaryService for details of the service.
   */
  class DictionaryImpl : public US_BASECLASS_NAME, public DictionaryService
  {
    // The set of words contained in the dictionary.
    US_UNORDERED_SET_TYPE<std::string> m_dictionary;

  public:

    DictionaryImpl()
    {
      m_dictionary.insert("welcome");
      m_dictionary.insert("to");
      m_dictionary.insert("the");
      m_dictionary.insert("micro");
      m_dictionary.insert("services");
      m_dictionary.insert("tutorial");
    }

    /**
     * Implements DictionaryService.checkWord(). Determines
     * if the passed in word is contained in the dictionary.
     * @param word the word to be checked.
     * @return true if the word is in the dictionary,
     *         false otherwise.
     **/
    bool checkWord(const std::string& word)
    {
      std::string lword(word);
      std::transform(lword.begin(), lword.end(), lword.begin(), ::tolower);

      return m_dictionary.find(lword) != m_dictionary.end();
    }
  };

  std::auto_ptr<DictionaryImpl> m_dictionaryService;

public:

  /**
   * Implements ModuleActivator::Load(). Registers an
   * instance of a dictionary service using the module context;
   * attaches properties to the service that can be queried
   * when performing a service look-up.
   * @param context the context for the module.
   */
  void Load(ModuleContext* context)
  {
    m_dictionaryService.reset(new DictionaryImpl);
    ServiceProperties props;
    props["Language"] = std::string("English");
    context->RegisterService<DictionaryService>(m_dictionaryService.get(), props);
  }

  /**
   * Implements ModuleActivator::Unload(). Does nothing since
   * the C++ Micro Services library will automatically unregister any registered services.
   * @param context the context for the module.
   */
  void Unload(ModuleContext* /*context*/)
  {
    // NOTE: The service is automatically unregistered
  }

};

US_EXPORT_MODULE_ACTIVATOR(DictionaryServiceModule, MyActivator)
//![Activator]

#include <usModuleInitialization.h>

US_INITIALIZE_MODULE("DictionaryServiceModule", "", "", "1.0.0")

int main(int /*argc*/, char* /*argv*/[])
{
  //![GetDictionaryService]
  ServiceReference dictionaryServiceRef = GetModuleContext()->GetServiceReference<DictionaryService>();
  if (dictionaryServiceRef)
  {
    DictionaryService* dictionaryService = GetModuleContext()->GetService<DictionaryService>(dictionaryServiceRef);
    if (dictionaryService)
    {
      std::cout << "Dictionary contains 'Tutorial': " << dictionaryService->checkWord("Tutorial") << std::endl;
    }
  }
  //![GetDictionaryService]
  return 0;
}
<commit_msg>Do not used private defines in example code.<commit_after>
//! [Activator]
#include "DictionaryService.h"

#include <usModuleActivator.h>
#include <usModuleContext.h>
#include <usServiceProperties.h>

// Replace that include with your own base class declaration
#include US_BASECLASS_HEADER

#include <set>
#include <algorithm>
#include <memory>

US_USE_NAMESPACE

/**
 * This class implements a module activator that uses the module
 * context to register an English language dictionary service
 * with the C++ Micro Services registry during static initialization
 * of the module. The dictionary service interface is
 * defined in a separate file and is implemented by a nested class.
 */
class US_ABI_LOCAL MyActivator : public ModuleActivator
{

private:

  /**
   * A private inner class that implements a dictionary service;
   * see DictionaryService for details of the service.
   */
  class DictionaryImpl : public US_BASECLASS_NAME, public DictionaryService
  {
    // The set of words contained in the dictionary.
    std::set<std::string> m_dictionary;

  public:

    DictionaryImpl()
    {
      m_dictionary.insert("welcome");
      m_dictionary.insert("to");
      m_dictionary.insert("the");
      m_dictionary.insert("micro");
      m_dictionary.insert("services");
      m_dictionary.insert("tutorial");
    }

    /**
     * Implements DictionaryService.checkWord(). Determines
     * if the passed in word is contained in the dictionary.
     * @param word the word to be checked.
     * @return true if the word is in the dictionary,
     *         false otherwise.
     **/
    bool checkWord(const std::string& word)
    {
      std::string lword(word);
      std::transform(lword.begin(), lword.end(), lword.begin(), ::tolower);

      return m_dictionary.find(lword) != m_dictionary.end();
    }
  };

  std::auto_ptr<DictionaryImpl> m_dictionaryService;

public:

  /**
   * Implements ModuleActivator::Load(). Registers an
   * instance of a dictionary service using the module context;
   * attaches properties to the service that can be queried
   * when performing a service look-up.
   * @param context the context for the module.
   */
  void Load(ModuleContext* context)
  {
    m_dictionaryService.reset(new DictionaryImpl);
    ServiceProperties props;
    props["Language"] = std::string("English");
    context->RegisterService<DictionaryService>(m_dictionaryService.get(), props);
  }

  /**
   * Implements ModuleActivator::Unload(). Does nothing since
   * the C++ Micro Services library will automatically unregister any registered services.
   * @param context the context for the module.
   */
  void Unload(ModuleContext* /*context*/)
  {
    // NOTE: The service is automatically unregistered
  }

};

US_EXPORT_MODULE_ACTIVATOR(DictionaryServiceModule, MyActivator)
//![Activator]

#include <usModuleInitialization.h>

US_INITIALIZE_MODULE("DictionaryServiceModule", "", "", "1.0.0")

int main(int /*argc*/, char* /*argv*/[])
{
  //![GetDictionaryService]
  ServiceReference dictionaryServiceRef = GetModuleContext()->GetServiceReference<DictionaryService>();
  if (dictionaryServiceRef)
  {
    DictionaryService* dictionaryService = GetModuleContext()->GetService<DictionaryService>(dictionaryServiceRef);
    if (dictionaryService)
    {
      std::cout << "Dictionary contains 'Tutorial': " << dictionaryService->checkWord("Tutorial") << std::endl;
    }
  }
  //![GetDictionaryService]
  return 0;
}
<|endoftext|>


<commit_before>#ifndef DUNE_DETAILED_DISCRETIZATIONS_MAPPER_CONTINUOUS_LAGRANGE_HH
#define DUNE_DETAILED_DISCRETIZATIONS_MAPPER_CONTINUOUS_LAGRANGE_HH

// dune-fem includes
#include <dune/fem/space/lagrangespace/lagrangespace.hh>

//// dune-functionals includes
//#include <dune/functionals/discretefunctionspace/continuous/lagrangefemadapter.hh>

namespace Dune {

namespace DetailedDiscretizations {

namespace Mapper {

namespace Continuous {

template <class FunctionSpaceImp, class GridPartImp, int polOrder>
class Lagrange
{
public:
  typedef FunctionSpaceImp FunctionSpaceType;

  typedef GridPartImp GridPartType;

  enum
  {
    polynomialOrder = polOrder
  };

  typedef Lagrange<FunctionSpaceType, GridPartType, polynomialOrder> ThisType;

  typedef LagrangePointSet<GridPartType, polynomialOrder> LagrangePointSetType;

private:
  typedef typename GridPartType::GridType GridType;

  typedef Dune::LagrangeDiscreteFunctionSpaceTraits<FunctionSpaceType, GridPartType, polynomialOrder>
      LagrangeDiscreteFunctionSpaceTraitsType;

  typedef typename LagrangeDiscreteFunctionSpaceTraitsType::MapperType MapperType;

  typedef typename LagrangeDiscreteFunctionSpaceTraitsType::BlockMapperType BlockMapperType;

  typedef std::map<const GeometryType, const LagrangePointSetType*> LagrangePointSetMapType;

  typedef typename LagrangeDiscreteFunctionSpaceTraitsType::IndexSetType IndexSetType;

  typedef LagrangeMapperSingletonKey<GridPartType, LagrangePointSetMapType> MapperSingletonKeyType;

  typedef LagrangeMapperSingletonFactory<MapperSingletonKeyType, BlockMapperType> BlockMapperSingletonFactoryType;

  typedef SingletonList<MapperSingletonKeyType, BlockMapperType, BlockMapperSingletonFactoryType>
      BlockMapperProviderType;

public:
  //! does, whatever the constructor of the fem LagrangeDiscreteFunctionSpace does
  Lagrange(const GridPartType& gridPart)
    : gridPart_(gridPart)
    , lagrangePointSet_()
    , mapper_(0)
    , blockMapper_(0)
  {
    const IndexSetType& indexSet = gridPart_.indexSet();

    AllGeomTypes<IndexSetType, GridType> allGeometryTypes(indexSet);

    const std::vector<GeometryType>& geometryTypes = allGeometryTypes.geomTypes(0);

    for (unsigned int i = 0; i < geometryTypes.size(); ++i) {
      const GeometryType& geometryType = geometryTypes[i];

      if (lagrangePointSet_.find(geometryType) == lagrangePointSet_.end()) {
        const LagrangePointSetType* lagrangePointSet = new LagrangePointSetType(geometryType, polynomialOrder);
        assert(lagrangePointSet != NULL);
        lagrangePointSet_[geometryType] = lagrangePointSet;
      }
    }

    MapperSingletonKeyType key(gridPart_, lagrangePointSet_, polynomialOrder);

    blockMapper_ = &(BlockMapperProviderType::getObject(key));
    assert(blockMapper_ != 0);

    mapper_ = new MapperType(*blockMapper_);
    assert(mapper_ != 0);
  }

  //! does, whatever the destructor of the fem LagrangeDiscreteFunctionSpace does
  ~Lagrange()
  {
    delete mapper_;

    BlockMapperProviderType::removeObject(*blockMapper_);

    typedef typename LagrangePointSetMapType::iterator LPIteratorType;

    LPIteratorType lpend = lagrangePointSet_.end();
    for (LPIteratorType it = lagrangePointSet_.begin(); it != lpend; ++it) {
      const LagrangePointSetType* lagrangePointSet = (*it).second;
      if (lagrangePointSet != NULL)
        delete lagrangePointSet;
    }
  }

  const GridPartType& gridPart() const
  {
    return gridPart_;
  }

  template <class EntityType>
  unsigned int toGlobal(const EntityType& entity, const unsigned int localDofNumber) const
  {
    return mapper_->mapToGlobal(entity, localDofNumber);
  }

  unsigned int size() const
  {
    return mapper_->size();
  }

  unsigned int maxLocalSize() const
  {
    return mapper_->maxNumDofs();
  }

  template <class EntityType>
  const LagrangePointSetType& lagrangePointSet(const EntityType& entity) const
  {
    assert(lagrangePointSet_.find(entity.type()) != lagrangePointSet_.end());
    assert(lagrangePointSet_[entity.type()] != NULL);
    return *(lagrangePointSet_[entity.type()]);
  }

private:
  //! copy constructor
  Lagrange(const ThisType&);

  //! assignment operator
  ThisType& operator=(const ThisType&);

  //  template< class >
  //  friend class Dune::Functionals::DiscreteFunctionSpace::Continuous::LagrangeFemAdapter;

  const GridPartType& gridPart_;
  mutable LagrangePointSetMapType lagrangePointSet_;
  MapperType* mapper_;
  BlockMapperType* blockMapper_;

}; // end class Lagrange

} // end namespace Mapper

} // end namespace Continuous

} // end namespace DetailedDiscretizations

} // end namespace Dune

#endif // DUNE_DETAILED_DISCRETIZATIONS_MAPPER_CONTINUOUS_LAGRANGE_HH
<commit_msg>[mapper.continuous.lagrange] compatible to dune-fem release 1.2.1<commit_after>#ifndef DUNE_DETAILED_DISCRETIZATIONS_MAPPER_CONTINUOUS_LAGRANGE_HH
#define DUNE_DETAILED_DISCRETIZATIONS_MAPPER_CONTINUOUS_LAGRANGE_HH

// dune-fem includes
#include <dune/fem/space/lagrangespace/lagrangespace.hh>

//// dune-functionals includes
//#include <dune/functionals/discretefunctionspace/continuous/lagrangefemadapter.hh>

namespace Dune {

namespace DetailedDiscretizations {

namespace Mapper {

namespace Continuous {

template <class FunctionSpaceImp, class GridPartImp, int polOrder>
class Lagrange
{
public:
  typedef FunctionSpaceImp FunctionSpaceType;

  typedef GridPartImp GridPartType;

  enum
  {
    polynomialOrder = polOrder
  };

  typedef Lagrange<FunctionSpaceType, GridPartType, polynomialOrder> ThisType;

  typedef LagrangePointSet<GridPartType, polynomialOrder> LagrangePointSetType;

private:
  typedef typename GridPartType::GridType GridType;

  typedef Dune::LagrangeDiscreteFunctionSpaceTraits<FunctionSpaceType, GridPartType, polynomialOrder>
      LagrangeDiscreteFunctionSpaceTraitsType;

  typedef typename LagrangeDiscreteFunctionSpaceTraitsType::MapperType MapperType;

  typedef typename LagrangeDiscreteFunctionSpaceTraitsType::BlockMapperType BlockMapperType;

  typedef std::map<const GeometryType, const LagrangePointSetType*> LagrangePointSetMapType;

  typedef typename LagrangeDiscreteFunctionSpaceTraitsType::IndexSetType IndexSetType;

  typedef LagrangeMapperSingletonKey<GridPartType, LagrangePointSetMapType> MapperSingletonKeyType;

  typedef LagrangeMapperSingletonFactory<MapperSingletonKeyType, BlockMapperType> BlockMapperSingletonFactoryType;

  typedef SingletonList<MapperSingletonKeyType, BlockMapperType, BlockMapperSingletonFactoryType>
      BlockMapperProviderType;

public:
  //! does, whatever the constructor of the fem LagrangeDiscreteFunctionSpace does
  Lagrange(const GridPartType& gridPart)
    : gridPart_(gridPart)
    , lagrangePointSet_()
    , mapper_(0)
    , blockMapper_(0)
  {
    const IndexSetType& indexSet = gridPart_.indexSet();

    AllGeomTypes<IndexSetType, GridType> allGeometryTypes(indexSet);

    const std::vector<GeometryType>& geometryTypes = allGeometryTypes.geomTypes(0);

    for (unsigned int i = 0; i < geometryTypes.size(); ++i) {
      const GeometryType& geometryType = geometryTypes[i];

      if (lagrangePointSet_.find(geometryType) == lagrangePointSet_.end()) {
        const LagrangePointSetType* lagrangePointSet = new LagrangePointSetType(geometryType);
        assert(lagrangePointSet != NULL);
        lagrangePointSet_[geometryType] = lagrangePointSet;
      }
    }

    MapperSingletonKeyType key(gridPart_, lagrangePointSet_, polynomialOrder);

    blockMapper_ = &(BlockMapperProviderType::getObject(key));
    assert(blockMapper_ != 0);

    mapper_ = new MapperType(*blockMapper_);
    assert(mapper_ != 0);
  }

  //! does, whatever the destructor of the fem LagrangeDiscreteFunctionSpace does
  ~Lagrange()
  {
    delete mapper_;

    BlockMapperProviderType::removeObject(*blockMapper_);

    typedef typename LagrangePointSetMapType::iterator LPIteratorType;

    LPIteratorType lpend = lagrangePointSet_.end();
    for (LPIteratorType it = lagrangePointSet_.begin(); it != lpend; ++it) {
      const LagrangePointSetType* lagrangePointSet = (*it).second;
      if (lagrangePointSet != NULL)
        delete lagrangePointSet;
    }
  }

  const GridPartType& gridPart() const
  {
    return gridPart_;
  }

  template <class EntityType>
  unsigned int toGlobal(const EntityType& entity, const unsigned int localDofNumber) const
  {
    return mapper_->mapToGlobal(entity, localDofNumber);
  }

  unsigned int size() const
  {
    return mapper_->size();
  }

  unsigned int maxLocalSize() const
  {
    return mapper_->maxNumDofs();
  }

  template <class EntityType>
  const LagrangePointSetType& lagrangePointSet(const EntityType& entity) const
  {
    assert(lagrangePointSet_.find(entity.type()) != lagrangePointSet_.end());
    assert(lagrangePointSet_[entity.type()] != NULL);
    return *(lagrangePointSet_[entity.type()]);
  }

private:
  //! copy constructor
  Lagrange(const ThisType&);

  //! assignment operator
  ThisType& operator=(const ThisType&);

  //  template< class >
  //  friend class Dune::Functionals::DiscreteFunctionSpace::Continuous::LagrangeFemAdapter;

  const GridPartType& gridPart_;
  mutable LagrangePointSetMapType lagrangePointSet_;
  MapperType* mapper_;
  BlockMapperType* blockMapper_;

}; // end class Lagrange

} // end namespace Mapper

} // end namespace Continuous

} // end namespace DetailedDiscretizations

} // end namespace Dune

#endif // DUNE_DETAILED_DISCRETIZATIONS_MAPPER_CONTINUOUS_LAGRANGE_HH
<|endoftext|>


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

#include "absl/strings/str_format.h"
#include "ortools/sat/cp_model.h"
// [END import]
namespace operations_research {
namespace sat {

void AssignmentTeams() {
  // Data
  // [START data]
  const std::vector<std::vector<int>> costs = {{
    {{90, 76, 75, 70}},
    {{35, 85, 55, 65}},
    {{125, 95, 90, 105}},
    {{45, 110, 95, 115}},
    {{60, 105, 80, 75}},
    {{45, 65, 110, 95}},
  }};
  const int num_workers = costs.size();
  std::vector<int> all_workers(num_workers);
  std::iota(all_workers.begin(), all_workers.end(), 0);

  const int num_tasks = costs[0].size();
  std::vector<int> all_tasks(num_tasks);
  std::iota(all_tasks.begin(), all_tasks.end(), 0);

  const std::vector<int64_t> team1 = {{ 0, 2, 4 }};
  const std::vector<int64_t> team2 = {{ 1, 3, 5 }};
  // Maximum total of tasks for any team
  const int team_max = 2;
  // [END data]

  // Model
  // [START model]
  CpModelBuilder cp_model;
  // [END model]

  // Variables
  // [START variables]
  // x[i][j] is an array of Boolean variables. x[i][j] is true
  // if worker i is assigned to task j.
  std::vector<std::vector<BoolVar>> x(num_workers,
                                      std::vector<BoolVar>(num_tasks));
  for (int worker : all_workers) {
    for (int task : all_tasks) {
      x[worker][task] = cp_model.NewBoolVar().WithName(
          absl::StrFormat("x[%d,%d]", worker, task));
    }
  }
  // [END variables]

  // Constraints
  // [START constraints]
  // Each worker is assigned to at most one task.
  for (int worker : all_workers) {
    cp_model.AddLessOrEqual(LinearExpr::Sum(x[worker]), 1);
  }
  // Each task is assigned to exactly one worker.
  for (int task : all_tasks) {
    LinearExpr task_sum;
    for (int worker : all_workers) {
      task_sum.AddTerm(x[worker][task], 1);
    }
    cp_model.AddEquality(task_sum, 1);
  }

  // Each team takes at most two tasks.
  LinearExpr team1_tasks;
  for (int worker : team1) {
        for (int task : all_tasks) {
            team1_tasks.AddTerm(x[worker][task], 1);
        }
  }
  cp_model.AddLessOrEqual(team1_tasks, team_max);

  LinearExpr team2_tasks;
  for (int worker : team2) {
        for (int task : all_tasks) {
            team2_tasks.AddTerm(x[worker][task], 1);
        }
  }
  cp_model.AddLessOrEqual(team2_tasks, team_max);
  // [END constraints]

  // Objective
  // [START objective]
  LinearExpr total_cost;
  for (int worker : all_workers) {
    for (int task : all_tasks) {
      total_cost += x[worker][task] * costs[worker][task];
    }
  }
  cp_model.Minimize(total_cost);
  // [END objective]

  // Solve
  // [START solve]
  const CpSolverResponse response = Solve(cp_model.Build());
  // [END solve]

  // Print solution.
  // [START print_solution]
  if (response.status() == CpSolverStatus::INFEASIBLE) {
    LOG(FATAL) << "No solution found.";
  }
  LOG(INFO) << "Total cost: " << response.objective_value();
  LOG(INFO);
  for (int worker : all_workers) {
    for (int task : all_tasks) {
      if (SolutionBooleanValue(response, x[worker][task])) {
        LOG(INFO) << "Worker " << worker << " assigned to task " << task
                  << ".  Cost: " << costs[worker][task];
      }
    }
  }
  // [END print_solution]
}
}  // namespace sat
}  // namespace operations_research

int main(int argc, char** argv) {
  operations_research::sat::AssignmentTeams();
  return EXIT_SUCCESS;
}
// [END program]
<commit_msg>Fixup assignment_teams_sat.cc<commit_after>// Copyright 2010-2021 Google LLC
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// [START program]
// Solve a simple assignment problem.
// [START import]
#include <cstdint>
#include <numeric>
#include <vector>

#include "absl/strings/str_format.h"
#include "ortools/sat/cp_model.h"
// [END import]
namespace operations_research {
namespace sat {

void AssignmentTeamsSat() {
  // Data
  // [START data]
  const std::vector<std::vector<int>> costs = {{
    {{90, 76, 75, 70}},
    {{35, 85, 55, 65}},
    {{125, 95, 90, 105}},
    {{45, 110, 95, 115}},
    {{60, 105, 80, 75}},
    {{45, 65, 110, 95}},
  }};
  const int num_workers = costs.size();
  std::vector<int> all_workers(num_workers);
  std::iota(all_workers.begin(), all_workers.end(), 0);

  const int num_tasks = costs[0].size();
  std::vector<int> all_tasks(num_tasks);
  std::iota(all_tasks.begin(), all_tasks.end(), 0);

  const std::vector<int64_t> team1 = {{ 0, 2, 4 }};
  const std::vector<int64_t> team2 = {{ 1, 3, 5 }};
  // Maximum total of tasks for any team
  const int team_max = 2;
  // [END data]

  // Model
  // [START model]
  CpModelBuilder cp_model;
  // [END model]

  // Variables
  // [START variables]
  // x[i][j] is an array of Boolean variables. x[i][j] is true
  // if worker i is assigned to task j.
  std::vector<std::vector<BoolVar>> x(num_workers,
                                      std::vector<BoolVar>(num_tasks));
  for (int worker : all_workers) {
    for (int task : all_tasks) {
      x[worker][task] = cp_model.NewBoolVar().WithName(
          absl::StrFormat("x[%d,%d]", worker, task));
    }
  }
  // [END variables]

  // Constraints
  // [START constraints]
  // Each worker is assigned to at most one task.
  for (int worker : all_workers) {
    cp_model.AddLessOrEqual(LinearExpr::Sum(x[worker]), 1);
  }
  // Each task is assigned to exactly one worker.
  for (int task : all_tasks) {
    LinearExpr task_sum;
    for (int worker : all_workers) {
      task_sum.AddTerm(x[worker][task], 1);
    }
    cp_model.AddEquality(task_sum, 1);
  }

  // Each team takes at most two tasks.
  LinearExpr team1_tasks;
  for (int worker : team1) {
        for (int task : all_tasks) {
            team1_tasks.AddTerm(x[worker][task], 1);
        }
  }
  cp_model.AddLessOrEqual(team1_tasks, team_max);

  LinearExpr team2_tasks;
  for (int worker : team2) {
        for (int task : all_tasks) {
            team2_tasks.AddTerm(x[worker][task], 1);
        }
  }
  cp_model.AddLessOrEqual(team2_tasks, team_max);
  // [END constraints]

  // Objective
  // [START objective]
  LinearExpr total_cost;
  for (int worker : all_workers) {
    for (int task : all_tasks) {
      total_cost += x[worker][task] * costs[worker][task];
    }
  }
  cp_model.Minimize(total_cost);
  // [END objective]

  // Solve
  // [START solve]
  const CpSolverResponse response = Solve(cp_model.Build());
  // [END solve]

  // Print solution.
  // [START print_solution]
  if (response.status() == CpSolverStatus::INFEASIBLE) {
    LOG(FATAL) << "No solution found.";
  }
  LOG(INFO) << "Total cost: " << response.objective_value();
  LOG(INFO);
  for (int worker : all_workers) {
    for (int task : all_tasks) {
      if (SolutionBooleanValue(response, x[worker][task])) {
        LOG(INFO) << "Worker " << worker << " assigned to task " << task
                  << ".  Cost: " << costs[worker][task];
      }
    }
  }
  // [END print_solution]
}
}  // namespace sat
}  // namespace operations_research

int main(int argc, char** argv) {
  operations_research::sat::AssignmentTeamsSat();
  return EXIT_SUCCESS;
}
// [END program]
<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  $RCSfile: provider.cxx,v $
 *
 *  $Revision: 1.11 $
 *
 *  last change: $Author: abi $ $Date: 2002-05-31 10:31:38 $
 *
 *  The Contents of this file are made available subject to the terms of
 *  either of the following licenses
 *
 *         - GNU Lesser General Public License Version 2.1
 *         - Sun Industry Standards Source License Version 1.1
 *
 *  Sun Microsystems Inc., October, 2000
 *
 *  GNU Lesser General Public License Version 2.1
 *  =============================================
 *  Copyright 2000 by Sun Microsystems, Inc.
 *  901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *  This library is free software; you can redistribute it and/or
 *  modify it under the terms of the GNU Lesser General Public
 *  License version 2.1, as published by the Free Software Foundation.
 *
 *  This library is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *  Lesser General Public License for more details.
 *
 *  You should have received a copy of the GNU Lesser General Public
 *  License along with this library; if not, write to the Free Software
 *  Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *  MA  02111-1307  USA
 *
 *
 *  Sun Industry Standards Source License Version 1.1
 *  =================================================
 *  The contents of this file are subject to the Sun Industry Standards
 *  Source License Version 1.1 (the "License"); You may not use this file
 *  except in compliance with the License. You may obtain a copy of the
 *  License at http://www.openoffice.org/license.html.
 *
 *  Software provided under this License is provided on an "AS IS" basis,
 *  WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
 *  WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
 *  MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
 *  See the License for the specific provisions governing your rights and
 *  obligations concerning the Software.
 *
 *  The Initial Developer of the Original Code is: Sun Microsystems, Inc.
 *
 *  Copyright: 2000 by Sun Microsystems, Inc.
 *
 *  All Rights Reserved.
 *
 *  Contributor(s): _______________________________________
 *
 *
 ************************************************************************/

/**************************************************************************
                                TODO
 **************************************************************************

 *************************************************************************/

#include <stdio.h>

#ifndef _VOS_DIAGNOSE_HXX_
#include <vos/diagnose.hxx>
#endif
#ifndef _UCBHELPER_CONTENTIDENTIFIER_HXX
#include <ucbhelper/contentidentifier.hxx>
#endif
#ifndef _DATABASES_HXX_
#include <provider/databases.hxx>
#endif
#ifndef _PROVIDER_HXX
#include <provider/provider.hxx>
#endif
#ifndef _CONTENT_HXX
#include <provider/content.hxx>
#endif
#ifndef _DATABASES_HXX_
#include <provider/databases.hxx>
#endif
#ifndef _COM_SUN_STAR_FRAME_XCONFIGMANAGER_HPP_
#include <com/sun/star/frame/XConfigManager.hpp>
#endif
#ifndef _COM_SUN_STAR_BEANS_PROPERTYATTRIBBUTE_HPP_
#include <com/sun/star/beans/PropertyAttribute.hpp>
#endif
#ifndef _COM_SUN_STAR_BEANS_PROPERTYVALUE_HPP_
#include <com/sun/star/beans/PropertyValue.hpp>
#endif
#ifndef _COM_SUN_STAR_BEANS_PROPERTYSTATE_HPP_
#include <com/sun/star/beans/PropertyState.hpp>
#endif
#ifndef _COM_SUN_STAR_CONTAINER_XCONTAINER_HPP_
#include <com/sun/star/container/XContainer.hpp>
#endif
#ifndef _COM_SUN_STAR_CONTAINER_XNAMEACCESS_HPP_
#include <com/sun/star/container/XNameAccess.hpp>
#endif
#ifndef _COM_SUN_STAR_CONTAINER_XNAMEREPLACE_HPP_
#include <com/sun/star/container/XNameReplace.hpp>
#endif

using namespace com::sun::star::frame;
using namespace com::sun::star::beans;
using namespace com::sun::star::container;
using namespace com::sun::star::lang;
using namespace com::sun::star::ucb;
using namespace com::sun::star::uno;
using namespace rtl;

using namespace chelp;

//=========================================================================
//=========================================================================
//
// ContentProvider Implementation.
//
//=========================================================================
//=========================================================================

ContentProvider::ContentProvider( const Reference< XMultiServiceFactory >& rSMgr )
    : ::ucb::ContentProviderImplHelper( rSMgr ),
        isInitialized( false ),
        m_aScheme( OUString::createFromAscii( MYUCP_URL_SCHEME ) ),
        m_pDatabases( 0 )
{
}

//=========================================================================
// virtual
ContentProvider::~ContentProvider()
{
    delete m_pDatabases;
}

//=========================================================================
//
// XInterface methods.
//
//=========================================================================

XINTERFACE_IMPL_5( ContentProvider,
                   XTypeProvider,
                   XServiceInfo,
                   XContentProvider,
                   XComponent,
                   XContainerListener);

//=========================================================================
//
// XTypeProvider methods.
//
//=========================================================================

XTYPEPROVIDER_IMPL_5( ContentProvider,
                         XTypeProvider,
                         XServiceInfo,
                         XContentProvider,
                      XComponent,
                      XContainerListener);

//=========================================================================
//
// XServiceInfo methods.
//
//=========================================================================

XSERVICEINFO_IMPL_1( ContentProvider,
                     OUString::createFromAscii(
                             "CHelpContentProvider" ),
                     OUString::createFromAscii(
                             MYUCP_CONTENT_PROVIDER_SERVICE_NAME ) );

//=========================================================================
//
// Service factory implementation.
//
//=========================================================================

ONE_INSTANCE_SERVICE_FACTORY_IMPL( ContentProvider );

//=========================================================================
//
// XContentProvider methods.
//
//=========================================================================

// virtual
Reference< XContent > SAL_CALL ContentProvider::queryContent( const Reference< XContentIdentifier >& xCanonicId )
    throw( IllegalIdentifierException, RuntimeException )
{
    if ( ! xCanonicId->getContentProviderScheme().equalsIgnoreAsciiCase( m_aScheme ) )
    {   // Wrong URL-scheme
        throw IllegalIdentifierException();
    }

    {
        osl::MutexGuard aGuard( m_aMutex );
        if( ! isInitialized )
            init();
    }

    if( ! m_pDatabases )
        throw RuntimeException();

    rtl::OUString aOUString( m_pDatabases->getInstallPathAsURL() );
    rtl::OString aOString( aOUString.getStr(),
                           aOUString.getLength(),
                           RTL_TEXTENCODING_UTF8 );

    // Check, if a content with given id already exists...
    Reference< XContent > xContent
        = queryExistingContent( xCanonicId ).getBodyPtr();
    if ( xContent.is() )
        return xContent;

    xContent = new Content( m_xSMgr,this,xCanonicId,m_pDatabases );

    // Further checks

    if ( !xContent->getIdentifier().is() )
        throw IllegalIdentifierException();

    return xContent;
}

void SAL_CALL
ContentProvider::dispose()
{
    if(m_xContainer.is())
    {
        m_xContainer->removeContainerListener(this);
        m_xContainer = Reference<XContainer>(0);
    }
}

#include <provider/debughelper.hxx>

void SAL_CALL
ContentProvider::elementReplaced(const ContainerEvent& Event)
    throw (::com::sun::star::uno::RuntimeException)
{
    if(!m_pDatabases)
        return;

    rtl::OUString accessor;
    Event.Accessor >>= accessor;
    if(accessor.compareToAscii("HelpStyleSheet"))
        return;

    rtl::OUString replacedElement,element;
    Event.ReplacedElement >>= replacedElement;
    Event.Element >>= element;

    if(replacedElement == element)
        return;

    m_pDatabases->changeCSS(element);
}

void ContentProvider::init()
{
    osl::MutexGuard aGuard( m_aMutex );

    isInitialized = true;
    Reference< XMultiServiceFactory >  sProvider( getConfiguration() );
    Reference< XHierarchicalNameAccess > xHierAccess( getHierAccess( sProvider,
                                                                     "org.openoffice.Office.Common" ) );

    rtl::OUString instPath( getKey( xHierAccess,"Path/Current/Help" ) );
    if( ! instPath.getLength() )
        // try to determine path from default
        instPath = rtl::OUString::createFromAscii( "$(instpath)/help" );
    // replace anything like $(instpath);
    subst( instPath );

    rtl::OUString stylesheet(getKey(xHierAccess,"Help/HelpStyleSheet"));
    try {
        // now adding as configuration change listener for the stylesheet
        Reference<XNameAccess> xAccess(xHierAccess,UNO_QUERY);
        Any aAny =
            xAccess->getByName(rtl::OUString::createFromAscii("Help"));
        aAny >>= m_xContainer;
        if(m_xContainer.is())
            m_xContainer->addContainerListener(this);
    } catch(const com::sun::star::uno::Exception& e) {
    }

    /**
     *  now determing
     *  productname,
     *  productversion,
     *  vendorname,
     *  vendorversion,
     *  vendorshort
     */

    xHierAccess = getHierAccess( sProvider,
                                 "org.openoffice.Setup" );
    rtl::OUString productname( getKey(  xHierAccess,"Product/ooName" ) );

    rtl::OUString setupversion( getKey(  xHierAccess,"Product/ooSetupVersion" ) );
    rtl::OUString setupextension( getKey(  xHierAccess,"Product/ooSetupExtension") );
    rtl::OUString productversion( setupversion +
                                  rtl::OUString::createFromAscii( " " ) +
                                  setupextension );

    xHierAccess = getHierAccess( sProvider,
                                 "org.openoffice.Webtop.Common" );
    rtl::OUString vendorname( getKey(  xHierAccess,"Product/ooName" ) );

    setupversion = rtl::OUString( getKey(  xHierAccess,"Product/ooSetupVersion" ) );
    setupextension = rtl::OUString ( getKey(  xHierAccess,"Product/ooSetupExtension") );
    rtl::OUString vendorversion( setupversion +
                                 rtl::OUString::createFromAscii( " " ) +
                                 setupextension );
    rtl::OUString vendorshort = vendorname;

    m_pDatabases = new Databases( instPath,
                                  productname,
                                  productversion,
                                  vendorname,
                                  vendorversion,
                                  vendorshort,
                                  stylesheet,
                                  m_xSMgr );

//      rtl::OUString newVal = rtl::OUString::createFromAscii("high_contrast");
//      Any bla;
//      bla <<= newVal;
//      Reference<XNameReplace> rep(m_xContainer,UNO_QUERY);
//      rep->replaceByName(rtl::OUString::createFromAscii("HelpStyleSheet"),
//                         bla);
}

Reference< XMultiServiceFactory > ContentProvider::getConfiguration() const
{
    Reference< XMultiServiceFactory > sProvider;
    if( m_xSMgr.is() )
    {
        Any aAny;
        aAny <<= rtl::OUString::createFromAscii( "plugin" );
        PropertyValue aProp( rtl::OUString::createFromAscii( "servertype" ),
                             -1,
                             aAny,
                             PropertyState_DIRECT_VALUE );

        Sequence< Any > seq(1);
        seq[0] <<= aProp;

        try
        {
            rtl::OUString sProviderService =
                rtl::OUString::createFromAscii( "com.sun.star.configuration.ConfigurationProvider" );
            sProvider =
                Reference< XMultiServiceFactory >(
                    m_xSMgr->createInstanceWithArguments( sProviderService,seq ),
                    UNO_QUERY );
        }
        catch( const com::sun::star::uno::Exception& )
        {
            OSL_ENSURE( sProvider.is(),"cant instantiate configuration" );
        }
    }

    return sProvider;
}

Reference< XHierarchicalNameAccess >
ContentProvider::getHierAccess( const Reference< XMultiServiceFactory >& sProvider,
                                const char* file ) const
{
    Reference< XHierarchicalNameAccess > xHierAccess;

    if( sProvider.is() )
    {
        Sequence< Any > seq(1);
        rtl::OUString sReaderService =
            rtl::OUString::createFromAscii( "com.sun.star.configuration.ConfigurationAccess" );

        seq[0] <<= rtl::OUString::createFromAscii( file );

        try
        {
            xHierAccess =
                Reference< XHierarchicalNameAccess >
                ( sProvider->createInstanceWithArguments( sReaderService,seq ),
                  UNO_QUERY );
        }
        catch( const com::sun::star::uno::Exception& )
        {
        }
    }

    return xHierAccess;
}

rtl::OUString
ContentProvider::getKey( const Reference< XHierarchicalNameAccess >& xHierAccess,
                         const char* key ) const
{
    rtl::OUString instPath;
    if( xHierAccess.is() )
    {
        Any aAny;
        try
        {
            aAny =
                xHierAccess->getByHierarchicalName( rtl::OUString::createFromAscii( key ) );
        }
        catch( const com::sun::star::container::NoSuchElementException& )
        {
        }
        aAny >>= instPath;
    }
    return instPath;
}

void ContentProvider::subst( rtl::OUString& instpath ) const
{
    Reference< XConfigManager >  xCfgMgr;
    if( m_xSMgr.is() )
    {
        try
        {
            xCfgMgr =
                Reference< XConfigManager >(
                    m_xSMgr->createInstance( rtl::OUString::createFromAscii( "com.sun.star.config.SpecialConfigManager" ) ),
                    UNO_QUERY );
        }
        catch( const com::sun::star::uno::Exception& e )
        {
            OSL_ENSURE( xCfgMgr.is()," cant instantiate the special config manager " );
        }
    }

    OSL_ENSURE( xCfgMgr.is(), "specialconfigmanager not found\n" );

    if( xCfgMgr.is() )
        instpath = xCfgMgr->substituteVariables( instpath );
}
<commit_msg>#65293# exception specification<commit_after>/*************************************************************************
 *
 *  $RCSfile: provider.cxx,v $
 *
 *  $Revision: 1.12 $
 *
 *  last change: $Author: vg $ $Date: 2002-06-05 09:33:43 $
 *
 *  The Contents of this file are made available subject to the terms of
 *  either of the following licenses
 *
 *         - GNU Lesser General Public License Version 2.1
 *         - Sun Industry Standards Source License Version 1.1
 *
 *  Sun Microsystems Inc., October, 2000
 *
 *  GNU Lesser General Public License Version 2.1
 *  =============================================
 *  Copyright 2000 by Sun Microsystems, Inc.
 *  901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *  This library is free software; you can redistribute it and/or
 *  modify it under the terms of the GNU Lesser General Public
 *  License version 2.1, as published by the Free Software Foundation.
 *
 *  This library is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *  Lesser General Public License for more details.
 *
 *  You should have received a copy of the GNU Lesser General Public
 *  License along with this library; if not, write to the Free Software
 *  Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *  MA  02111-1307  USA
 *
 *
 *  Sun Industry Standards Source License Version 1.1
 *  =================================================
 *  The contents of this file are subject to the Sun Industry Standards
 *  Source License Version 1.1 (the "License"); You may not use this file
 *  except in compliance with the License. You may obtain a copy of the
 *  License at http://www.openoffice.org/license.html.
 *
 *  Software provided under this License is provided on an "AS IS" basis,
 *  WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
 *  WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
 *  MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
 *  See the License for the specific provisions governing your rights and
 *  obligations concerning the Software.
 *
 *  The Initial Developer of the Original Code is: Sun Microsystems, Inc.
 *
 *  Copyright: 2000 by Sun Microsystems, Inc.
 *
 *  All Rights Reserved.
 *
 *  Contributor(s): _______________________________________
 *
 *
 ************************************************************************/

/**************************************************************************
                                TODO
 **************************************************************************

 *************************************************************************/

#include <stdio.h>

#ifndef _VOS_DIAGNOSE_HXX_
#include <vos/diagnose.hxx>
#endif
#ifndef _UCBHELPER_CONTENTIDENTIFIER_HXX
#include <ucbhelper/contentidentifier.hxx>
#endif
#ifndef _DATABASES_HXX_
#include <provider/databases.hxx>
#endif
#ifndef _PROVIDER_HXX
#include <provider/provider.hxx>
#endif
#ifndef _CONTENT_HXX
#include <provider/content.hxx>
#endif
#ifndef _DATABASES_HXX_
#include <provider/databases.hxx>
#endif
#ifndef _COM_SUN_STAR_FRAME_XCONFIGMANAGER_HPP_
#include <com/sun/star/frame/XConfigManager.hpp>
#endif
#ifndef _COM_SUN_STAR_BEANS_PROPERTYATTRIBBUTE_HPP_
#include <com/sun/star/beans/PropertyAttribute.hpp>
#endif
#ifndef _COM_SUN_STAR_BEANS_PROPERTYVALUE_HPP_
#include <com/sun/star/beans/PropertyValue.hpp>
#endif
#ifndef _COM_SUN_STAR_BEANS_PROPERTYSTATE_HPP_
#include <com/sun/star/beans/PropertyState.hpp>
#endif
#ifndef _COM_SUN_STAR_CONTAINER_XCONTAINER_HPP_
#include <com/sun/star/container/XContainer.hpp>
#endif
#ifndef _COM_SUN_STAR_CONTAINER_XNAMEACCESS_HPP_
#include <com/sun/star/container/XNameAccess.hpp>
#endif
#ifndef _COM_SUN_STAR_CONTAINER_XNAMEREPLACE_HPP_
#include <com/sun/star/container/XNameReplace.hpp>
#endif

using namespace com::sun::star::frame;
using namespace com::sun::star::beans;
using namespace com::sun::star::container;
using namespace com::sun::star::lang;
using namespace com::sun::star::ucb;
using namespace com::sun::star::uno;
using namespace rtl;

using namespace chelp;

//=========================================================================
//=========================================================================
//
// ContentProvider Implementation.
//
//=========================================================================
//=========================================================================

ContentProvider::ContentProvider( const Reference< XMultiServiceFactory >& rSMgr )
    : ::ucb::ContentProviderImplHelper( rSMgr ),
        isInitialized( false ),
        m_aScheme( OUString::createFromAscii( MYUCP_URL_SCHEME ) ),
        m_pDatabases( 0 )
{
}

//=========================================================================
// virtual
ContentProvider::~ContentProvider()
{
    delete m_pDatabases;
}

//=========================================================================
//
// XInterface methods.
//
//=========================================================================

XINTERFACE_IMPL_5( ContentProvider,
                   XTypeProvider,
                   XServiceInfo,
                   XContentProvider,
                   XComponent,
                   XContainerListener);

//=========================================================================
//
// XTypeProvider methods.
//
//=========================================================================

XTYPEPROVIDER_IMPL_5( ContentProvider,
                         XTypeProvider,
                         XServiceInfo,
                         XContentProvider,
                      XComponent,
                      XContainerListener);

//=========================================================================
//
// XServiceInfo methods.
//
//=========================================================================

XSERVICEINFO_IMPL_1( ContentProvider,
                     OUString::createFromAscii(
                             "CHelpContentProvider" ),
                     OUString::createFromAscii(
                             MYUCP_CONTENT_PROVIDER_SERVICE_NAME ) );

//=========================================================================
//
// Service factory implementation.
//
//=========================================================================

ONE_INSTANCE_SERVICE_FACTORY_IMPL( ContentProvider );

//=========================================================================
//
// XContentProvider methods.
//
//=========================================================================

// virtual
Reference< XContent > SAL_CALL ContentProvider::queryContent( const Reference< XContentIdentifier >& xCanonicId )
    throw( IllegalIdentifierException, RuntimeException )
{
    if ( ! xCanonicId->getContentProviderScheme().equalsIgnoreAsciiCase( m_aScheme ) )
    {   // Wrong URL-scheme
        throw IllegalIdentifierException();
    }

    {
        osl::MutexGuard aGuard( m_aMutex );
        if( ! isInitialized )
            init();
    }

    if( ! m_pDatabases )
        throw RuntimeException();

    rtl::OUString aOUString( m_pDatabases->getInstallPathAsURL() );
    rtl::OString aOString( aOUString.getStr(),
                           aOUString.getLength(),
                           RTL_TEXTENCODING_UTF8 );

    // Check, if a content with given id already exists...
    Reference< XContent > xContent
        = queryExistingContent( xCanonicId ).getBodyPtr();
    if ( xContent.is() )
        return xContent;

    xContent = new Content( m_xSMgr,this,xCanonicId,m_pDatabases );

    // Further checks

    if ( !xContent->getIdentifier().is() )
        throw IllegalIdentifierException();

    return xContent;
}

void SAL_CALL
ContentProvider::dispose()
    throw ( com::sun::star::uno::RuntimeException)
{
    if(m_xContainer.is())
    {
        m_xContainer->removeContainerListener(this);
        m_xContainer = Reference<XContainer>(0);
    }
}

#include <provider/debughelper.hxx>

void SAL_CALL
ContentProvider::elementReplaced(const ContainerEvent& Event)
    throw (::com::sun::star::uno::RuntimeException)
{
    if(!m_pDatabases)
        return;

    rtl::OUString accessor;
    Event.Accessor >>= accessor;
    if(accessor.compareToAscii("HelpStyleSheet"))
        return;

    rtl::OUString replacedElement,element;
    Event.ReplacedElement >>= replacedElement;
    Event.Element >>= element;

    if(replacedElement == element)
        return;

    m_pDatabases->changeCSS(element);
}

void ContentProvider::init()
{
    osl::MutexGuard aGuard( m_aMutex );

    isInitialized = true;
    Reference< XMultiServiceFactory >  sProvider( getConfiguration() );
    Reference< XHierarchicalNameAccess > xHierAccess( getHierAccess( sProvider,
                                                                     "org.openoffice.Office.Common" ) );

    rtl::OUString instPath( getKey( xHierAccess,"Path/Current/Help" ) );
    if( ! instPath.getLength() )
        // try to determine path from default
        instPath = rtl::OUString::createFromAscii( "$(instpath)/help" );
    // replace anything like $(instpath);
    subst( instPath );

    rtl::OUString stylesheet(getKey(xHierAccess,"Help/HelpStyleSheet"));
    try {
        // now adding as configuration change listener for the stylesheet
        Reference<XNameAccess> xAccess(xHierAccess,UNO_QUERY);
        Any aAny =
            xAccess->getByName(rtl::OUString::createFromAscii("Help"));
        aAny >>= m_xContainer;
        if(m_xContainer.is())
            m_xContainer->addContainerListener(this);
    } catch(const com::sun::star::uno::Exception& e) {
    }

    /**
     *  now determing
     *  productname,
     *  productversion,
     *  vendorname,
     *  vendorversion,
     *  vendorshort
     */

    xHierAccess = getHierAccess( sProvider,
                                 "org.openoffice.Setup" );
    rtl::OUString productname( getKey(  xHierAccess,"Product/ooName" ) );

    rtl::OUString setupversion( getKey(  xHierAccess,"Product/ooSetupVersion" ) );
    rtl::OUString setupextension( getKey(  xHierAccess,"Product/ooSetupExtension") );
    rtl::OUString productversion( setupversion +
                                  rtl::OUString::createFromAscii( " " ) +
                                  setupextension );

    xHierAccess = getHierAccess( sProvider,
                                 "org.openoffice.Webtop.Common" );
    rtl::OUString vendorname( getKey(  xHierAccess,"Product/ooName" ) );

    setupversion = rtl::OUString( getKey(  xHierAccess,"Product/ooSetupVersion" ) );
    setupextension = rtl::OUString ( getKey(  xHierAccess,"Product/ooSetupExtension") );
    rtl::OUString vendorversion( setupversion +
                                 rtl::OUString::createFromAscii( " " ) +
                                 setupextension );
    rtl::OUString vendorshort = vendorname;

    m_pDatabases = new Databases( instPath,
                                  productname,
                                  productversion,
                                  vendorname,
                                  vendorversion,
                                  vendorshort,
                                  stylesheet,
                                  m_xSMgr );

//      rtl::OUString newVal = rtl::OUString::createFromAscii("high_contrast");
//      Any bla;
//      bla <<= newVal;
//      Reference<XNameReplace> rep(m_xContainer,UNO_QUERY);
//      rep->replaceByName(rtl::OUString::createFromAscii("HelpStyleSheet"),
//                         bla);
}

Reference< XMultiServiceFactory > ContentProvider::getConfiguration() const
{
    Reference< XMultiServiceFactory > sProvider;
    if( m_xSMgr.is() )
    {
        Any aAny;
        aAny <<= rtl::OUString::createFromAscii( "plugin" );
        PropertyValue aProp( rtl::OUString::createFromAscii( "servertype" ),
                             -1,
                             aAny,
                             PropertyState_DIRECT_VALUE );

        Sequence< Any > seq(1);
        seq[0] <<= aProp;

        try
        {
            rtl::OUString sProviderService =
                rtl::OUString::createFromAscii( "com.sun.star.configuration.ConfigurationProvider" );
            sProvider =
                Reference< XMultiServiceFactory >(
                    m_xSMgr->createInstanceWithArguments( sProviderService,seq ),
                    UNO_QUERY );
        }
        catch( const com::sun::star::uno::Exception& )
        {
            OSL_ENSURE( sProvider.is(),"cant instantiate configuration" );
        }
    }

    return sProvider;
}

Reference< XHierarchicalNameAccess >
ContentProvider::getHierAccess( const Reference< XMultiServiceFactory >& sProvider,
                                const char* file ) const
{
    Reference< XHierarchicalNameAccess > xHierAccess;

    if( sProvider.is() )
    {
        Sequence< Any > seq(1);
        rtl::OUString sReaderService =
            rtl::OUString::createFromAscii( "com.sun.star.configuration.ConfigurationAccess" );

        seq[0] <<= rtl::OUString::createFromAscii( file );

        try
        {
            xHierAccess =
                Reference< XHierarchicalNameAccess >
                ( sProvider->createInstanceWithArguments( sReaderService,seq ),
                  UNO_QUERY );
        }
        catch( const com::sun::star::uno::Exception& )
        {
        }
    }

    return xHierAccess;
}

rtl::OUString
ContentProvider::getKey( const Reference< XHierarchicalNameAccess >& xHierAccess,
                         const char* key ) const
{
    rtl::OUString instPath;
    if( xHierAccess.is() )
    {
        Any aAny;
        try
        {
            aAny =
                xHierAccess->getByHierarchicalName( rtl::OUString::createFromAscii( key ) );
        }
        catch( const com::sun::star::container::NoSuchElementException& )
        {
        }
        aAny >>= instPath;
    }
    return instPath;
}

void ContentProvider::subst( rtl::OUString& instpath ) const
{
    Reference< XConfigManager >  xCfgMgr;
    if( m_xSMgr.is() )
    {
        try
        {
            xCfgMgr =
                Reference< XConfigManager >(
                    m_xSMgr->createInstance( rtl::OUString::createFromAscii( "com.sun.star.config.SpecialConfigManager" ) ),
                    UNO_QUERY );
        }
        catch( const com::sun::star::uno::Exception& e )
        {
            OSL_ENSURE( xCfgMgr.is()," cant instantiate the special config manager " );
        }
    }

    OSL_ENSURE( xCfgMgr.is(), "specialconfigmanager not found\n" );

    if( xCfgMgr.is() )
        instpath = xCfgMgr->substituteVariables( instpath );
}
<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: SchXMLSeries2Context.hxx,v $
 *
 *  $Revision: 1.6 $
 *
 *  last change: $Author: kz $ $Date: 2008-03-06 15:56:07 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 by Sun Microsystems, Inc.
 *    901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License version 2.1, as published by the Free Software Foundation.
 *
 *    This library is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *    Lesser General Public License for more details.
 *
 *    You should have received a copy of the GNU Lesser General Public
 *    License along with this library; if not, write to the Free Software
 *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *    MA  02111-1307  USA
 *
 ************************************************************************/
#ifndef XMLOFF_SCHXMLSERIES2CONTEXT_HXX
#define XMLOFF_SCHXMLSERIES2CONTEXT_HXX

#include "transporttypes.hxx"
#include "SchXMLChartContext.hxx"

#ifndef _XMLOFF_XMLICTXT_HXX
#include <xmloff/xmlictxt.hxx>
#endif
#ifndef _XMLOFF_SCH_XMLIMPORTHELPER_HXX_
#include <xmloff/SchXMLImportHelper.hxx>
#endif
// header for class SvXMLStyleContext
#ifndef _XMLOFF_XMLSTYLE_HXX
#include <xmloff/xmlstyle.hxx>
#endif

#include <vector>
#include <list>

namespace com { namespace sun { namespace star {
    namespace chart2 {
        class XChartDocument;
        class XDataSeries;
    }
    namespace awt {
        struct Size;
    }
}}}

// class for child contexts: series, data point and statistics objects
class SchXMLSeries2Context : public SvXMLImportContext
{
private:
    SchXMLImportHelper& mrImportHelper;
    ::com::sun::star::uno::Reference<
            ::com::sun::star::chart2::XChartDocument > mxNewDoc;
    ::std::vector< SchXMLAxis >& mrAxes;
    ::std::list< DataRowPointStyle >& mrStyleList;
    ::com::sun::star::uno::Reference< ::com::sun::star::chart2::XDataSeries > m_xSeries;
    sal_Int32 mnSeriesIndex;
    sal_Int32 mnDataPointIndex;
    sal_Int32& mrMaxSeriesLength;
    sal_Int32& mrNumOfLines;
    sal_Bool& mrStockHasVolume;
    ::rtl::OUString& mrFirstFirstDomainAddress;
    sal_Int32& mrFirstFirstDomainIndex;
    sal_Bool& mrAllRangeAddressesAvailable;
    SchXMLAxis* mpAttachedAxis;
    sal_Int32 mnAttachedAxis;
    ::rtl::OUString msAutoStyleName;
    ::std::vector< ::rtl::OUString > maDomainAddresses;
    ::rtl::OUString maGlobalChartTypeName;
    ::rtl::OUString maSeriesChartTypeName;
    ::rtl::OUString m_aSeriesRange;
    ::rtl::OUString m_aSeriesLabelRange;
    bool            m_bHasDomainContext;
    tSchXMLLSequencesPerIndex & mrLSequencesPerIndex;
    sal_Int32& mrCurrentDataIndex;
    tSchXMLLSequencesPerIndex maPostponedSequences;
    bool& mrGlobalChartTypeUsedBySeries;
    bool mbSymbolSizeIsMissingInFile;
    ::com::sun::star::awt::Size maChartSize;

public:
    SchXMLSeries2Context( SchXMLImportHelper& rImpHelper,
                          SvXMLImport& rImport, const rtl::OUString& rLocalName,
                          const ::com::sun::star::uno::Reference<
                              ::com::sun::star::chart2::XChartDocument > & xNewDoc,
                          std::vector< SchXMLAxis >& rAxes,
                          ::std::list< DataRowPointStyle >& rStyleList,
                          sal_Int32 nSeriesIndex,
                          sal_Int32& rMaxSeriesLength,
                          sal_Int32& rNumOfLines,
                          sal_Bool&  rStockHasVolume,
                          ::rtl::OUString& rFirstFirstDomainAddress,
                          sal_Int32& rFirstFirstDomainIndex,
                          sal_Bool&  rAllRangeAddressesAvailable,
                          const ::rtl::OUString & aGlobalChartTypeName,
                          tSchXMLLSequencesPerIndex & rLSequencesPerIndex,
                          sal_Int32& rCurrentDataIndex,
                          bool& rGlobalChartTypeUsedBySeries,
                          const ::com::sun::star::awt::Size & rChartSize );
    virtual ~SchXMLSeries2Context();

    virtual void StartElement( const ::com::sun::star::uno::Reference< ::com::sun::star::xml::sax::XAttributeList >& xAttrList );
    virtual SvXMLImportContext* CreateChildContext(
        USHORT nPrefix,
        const rtl::OUString& rLocalName,
        const ::com::sun::star::uno::Reference< ::com::sun::star::xml::sax::XAttributeList >& xAttrList );
    virtual void EndElement();

    static void initSeriesPropertySets( SeriesDefaultsAndStyles& rSeriesDefaultsAndStyles
        , const ::com::sun::star::uno::Reference< ::com::sun::star::frame::XModel >& xChartModel );

    static void setDefaultsToSeries( SeriesDefaultsAndStyles& rSeriesDefaultsAndStyles );

    static void setStylesToSeries( SeriesDefaultsAndStyles& rSeriesDefaultsAndStyles
        , const SvXMLStylesContext* pStylesCtxt
        , const SvXMLStyleContext*& rpStyle
        , ::rtl::OUString& rCurrStyleName
        , SchXMLImportHelper& rImportHelper
        , const SvXMLImport& rImport
        , bool bIsStockChart
        , tSchXMLLSequencesPerIndex & rInOutLSequencesPerIndex );

    static void setStylesToStatisticsObjects( SeriesDefaultsAndStyles& rSeriesDefaultsAndStyles
        , const SvXMLStylesContext* pStylesCtxt
        , const SvXMLStyleContext*& rpStyle
        , ::rtl::OUString& rCurrStyleName );

    static void setStylesToDataPoints( SeriesDefaultsAndStyles& rSeriesDefaultsAndStyles
        , const SvXMLStylesContext* pStylesCtxt
        , const SvXMLStyleContext*& rpStyle
        , ::rtl::OUString& rCurrStyleName
        , SchXMLImportHelper& rImportHelper
        , const SvXMLImport& rImport
        , bool bIsStockChart, bool bIsDonutChart, bool bSwitchOffLinesForScatter );

    static void switchSeriesLinesOff( ::std::list< DataRowPointStyle >& rSeriesStyleList );
};

// XMLOFF_SCHXMLSERIES2CONTEXT_HXX
#endif
<commit_msg>INTEGRATION: CWS changefileheader (1.6.20); FILE MERGED 2008/04/01 13:04:32 thb 1.6.20.2: #i85898# Stripping all external header guards 2008/03/31 16:28:00 rt 1.6.20.1: #i87441# Change license header to LPGL v3.<commit_after>/*************************************************************************
 *
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 *
 * Copyright 2008 by Sun Microsystems, Inc.
 *
 * OpenOffice.org - a multi-platform office productivity suite
 *
 * $RCSfile: SchXMLSeries2Context.hxx,v $
 * $Revision: 1.7 $
 *
 * This file is part of OpenOffice.org.
 *
 * OpenOffice.org is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License version 3
 * only, as published by the Free Software Foundation.
 *
 * OpenOffice.org 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 version 3 for more details
 * (a copy is included in the LICENSE file that accompanied this code).
 *
 * You should have received a copy of the GNU Lesser General Public License
 * version 3 along with OpenOffice.org.  If not, see
 * <http://www.openoffice.org/license.html>
 * for a copy of the LGPLv3 License.
 *
 ************************************************************************/
#ifndef XMLOFF_SCHXMLSERIES2CONTEXT_HXX
#define XMLOFF_SCHXMLSERIES2CONTEXT_HXX

#include "transporttypes.hxx"
#include "SchXMLChartContext.hxx"
#include <xmloff/xmlictxt.hxx>
#include <xmloff/SchXMLImportHelper.hxx>
// header for class SvXMLStyleContext
#include <xmloff/xmlstyle.hxx>

#include <vector>
#include <list>

namespace com { namespace sun { namespace star {
    namespace chart2 {
        class XChartDocument;
        class XDataSeries;
    }
    namespace awt {
        struct Size;
    }
}}}

// class for child contexts: series, data point and statistics objects
class SchXMLSeries2Context : public SvXMLImportContext
{
private:
    SchXMLImportHelper& mrImportHelper;
    ::com::sun::star::uno::Reference<
            ::com::sun::star::chart2::XChartDocument > mxNewDoc;
    ::std::vector< SchXMLAxis >& mrAxes;
    ::std::list< DataRowPointStyle >& mrStyleList;
    ::com::sun::star::uno::Reference< ::com::sun::star::chart2::XDataSeries > m_xSeries;
    sal_Int32 mnSeriesIndex;
    sal_Int32 mnDataPointIndex;
    sal_Int32& mrMaxSeriesLength;
    sal_Int32& mrNumOfLines;
    sal_Bool& mrStockHasVolume;
    ::rtl::OUString& mrFirstFirstDomainAddress;
    sal_Int32& mrFirstFirstDomainIndex;
    sal_Bool& mrAllRangeAddressesAvailable;
    SchXMLAxis* mpAttachedAxis;
    sal_Int32 mnAttachedAxis;
    ::rtl::OUString msAutoStyleName;
    ::std::vector< ::rtl::OUString > maDomainAddresses;
    ::rtl::OUString maGlobalChartTypeName;
    ::rtl::OUString maSeriesChartTypeName;
    ::rtl::OUString m_aSeriesRange;
    ::rtl::OUString m_aSeriesLabelRange;
    bool            m_bHasDomainContext;
    tSchXMLLSequencesPerIndex & mrLSequencesPerIndex;
    sal_Int32& mrCurrentDataIndex;
    tSchXMLLSequencesPerIndex maPostponedSequences;
    bool& mrGlobalChartTypeUsedBySeries;
    bool mbSymbolSizeIsMissingInFile;
    ::com::sun::star::awt::Size maChartSize;

public:
    SchXMLSeries2Context( SchXMLImportHelper& rImpHelper,
                          SvXMLImport& rImport, const rtl::OUString& rLocalName,
                          const ::com::sun::star::uno::Reference<
                              ::com::sun::star::chart2::XChartDocument > & xNewDoc,
                          std::vector< SchXMLAxis >& rAxes,
                          ::std::list< DataRowPointStyle >& rStyleList,
                          sal_Int32 nSeriesIndex,
                          sal_Int32& rMaxSeriesLength,
                          sal_Int32& rNumOfLines,
                          sal_Bool&  rStockHasVolume,
                          ::rtl::OUString& rFirstFirstDomainAddress,
                          sal_Int32& rFirstFirstDomainIndex,
                          sal_Bool&  rAllRangeAddressesAvailable,
                          const ::rtl::OUString & aGlobalChartTypeName,
                          tSchXMLLSequencesPerIndex & rLSequencesPerIndex,
                          sal_Int32& rCurrentDataIndex,
                          bool& rGlobalChartTypeUsedBySeries,
                          const ::com::sun::star::awt::Size & rChartSize );
    virtual ~SchXMLSeries2Context();

    virtual void StartElement( const ::com::sun::star::uno::Reference< ::com::sun::star::xml::sax::XAttributeList >& xAttrList );
    virtual SvXMLImportContext* CreateChildContext(
        USHORT nPrefix,
        const rtl::OUString& rLocalName,
        const ::com::sun::star::uno::Reference< ::com::sun::star::xml::sax::XAttributeList >& xAttrList );
    virtual void EndElement();

    static void initSeriesPropertySets( SeriesDefaultsAndStyles& rSeriesDefaultsAndStyles
        , const ::com::sun::star::uno::Reference< ::com::sun::star::frame::XModel >& xChartModel );

    static void setDefaultsToSeries( SeriesDefaultsAndStyles& rSeriesDefaultsAndStyles );

    static void setStylesToSeries( SeriesDefaultsAndStyles& rSeriesDefaultsAndStyles
        , const SvXMLStylesContext* pStylesCtxt
        , const SvXMLStyleContext*& rpStyle
        , ::rtl::OUString& rCurrStyleName
        , SchXMLImportHelper& rImportHelper
        , const SvXMLImport& rImport
        , bool bIsStockChart
        , tSchXMLLSequencesPerIndex & rInOutLSequencesPerIndex );

    static void setStylesToStatisticsObjects( SeriesDefaultsAndStyles& rSeriesDefaultsAndStyles
        , const SvXMLStylesContext* pStylesCtxt
        , const SvXMLStyleContext*& rpStyle
        , ::rtl::OUString& rCurrStyleName );

    static void setStylesToDataPoints( SeriesDefaultsAndStyles& rSeriesDefaultsAndStyles
        , const SvXMLStylesContext* pStylesCtxt
        , const SvXMLStyleContext*& rpStyle
        , ::rtl::OUString& rCurrStyleName
        , SchXMLImportHelper& rImportHelper
        , const SvXMLImport& rImport
        , bool bIsStockChart, bool bIsDonutChart, bool bSwitchOffLinesForScatter );

    static void switchSeriesLinesOff( ::std::list< DataRowPointStyle >& rSeriesStyleList );
};

// XMLOFF_SCHXMLSERIES2CONTEXT_HXX
#endif
<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: StyleOOoTContext.hxx,v $
 *
 *  $Revision: 1.3 $
 *
 *  last change: $Author: rt $ $Date: 2005-09-09 15:56:06 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 by Sun Microsystems, Inc.
 *    901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License version 2.1, as published by the Free Software Foundation.
 *
 *    This library is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *    Lesser General Public License for more details.
 *
 *    You should have received a copy of the GNU Lesser General Public
 *    License along with this library; if not, write to the Free Software
 *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *    MA  02111-1307  USA
 *
 ************************************************************************/

#ifndef _XMLOFF_STYLEOOOTCONTEXT_HXX
#define _XMLOFF_STYLEOOOTCONTEXT_HXX

#ifndef _RTL_REF_HXX_
#include <rtl/ref.hxx>
#endif

#ifndef _XMLOFF_FAMILYTYPE_HXX
#include "FamilyType.hxx"
#endif
#ifndef _XMLOFF_DEEPTCONTEXT_HXX
#include "DeepTContext.hxx"
#endif

class XMLTransformerActions;

class XMLStyleOOoTContext : public XMLPersElemContentTContext
{
       XMLFamilyType m_eFamily;

    sal_Bool m_bPersistent;

public:
    TYPEINFO();

    XMLStyleOOoTContext( XMLTransformerBase& rTransformer,
                        const ::rtl::OUString& rQName,
                           XMLFamilyType eType,
                           sal_Bool bPersistent );
    XMLStyleOOoTContext( XMLTransformerBase& rTransformer,
                        const ::rtl::OUString& rQName,
                           XMLFamilyType eType,
                           sal_uInt16 nPrefix,
                           ::xmloff::token::XMLTokenEnum eToken,
                           sal_Bool bPersistent );

    virtual ~XMLStyleOOoTContext();

    virtual XMLTransformerContext *CreateChildContext( sal_uInt16 nPrefix,
                                   const ::rtl::OUString& rLocalName,
                                   const ::rtl::OUString& rQName,
                                   const ::com::sun::star::uno::Reference< ::com::sun::star::xml::sax::XAttributeList >& xAttrList );

    virtual void StartElement( const ::com::sun::star::uno::Reference< ::com::sun::star::xml::sax::XAttributeList >& xAttrList );
    virtual void EndElement();
    virtual void Characters( const ::rtl::OUString& rChars );
    virtual sal_Bool IsPersistent() const;

    static XMLTransformerActions *CreateTransformerActions( sal_uInt16 nType );

};

#endif  //  _XMLOFF_STYLEOOOTCONTEXT_HXX

<commit_msg>INTEGRATION: CWS changefileheader (1.3.448); FILE MERGED 2008/04/01 16:10:17 thb 1.3.448.3: #i85898# Stripping all external header guards 2008/04/01 13:05:51 thb 1.3.448.2: #i85898# Stripping all external header guards 2008/03/31 16:28:53 rt 1.3.448.1: #i87441# Change license header to LPGL v3.<commit_after>/*************************************************************************
 *
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 *
 * Copyright 2008 by Sun Microsystems, Inc.
 *
 * OpenOffice.org - a multi-platform office productivity suite
 *
 * $RCSfile: StyleOOoTContext.hxx,v $
 * $Revision: 1.4 $
 *
 * This file is part of OpenOffice.org.
 *
 * OpenOffice.org is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License version 3
 * only, as published by the Free Software Foundation.
 *
 * OpenOffice.org 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 version 3 for more details
 * (a copy is included in the LICENSE file that accompanied this code).
 *
 * You should have received a copy of the GNU Lesser General Public License
 * version 3 along with OpenOffice.org.  If not, see
 * <http://www.openoffice.org/license.html>
 * for a copy of the LGPLv3 License.
 *
 ************************************************************************/

#ifndef _XMLOFF_STYLEOOOTCONTEXT_HXX
#define _XMLOFF_STYLEOOOTCONTEXT_HXX

#include <rtl/ref.hxx>
#include "FamilyType.hxx"
#include "DeepTContext.hxx"

class XMLTransformerActions;

class XMLStyleOOoTContext : public XMLPersElemContentTContext
{
       XMLFamilyType m_eFamily;

    sal_Bool m_bPersistent;

public:
    TYPEINFO();

    XMLStyleOOoTContext( XMLTransformerBase& rTransformer,
                        const ::rtl::OUString& rQName,
                           XMLFamilyType eType,
                           sal_Bool bPersistent );
    XMLStyleOOoTContext( XMLTransformerBase& rTransformer,
                        const ::rtl::OUString& rQName,
                           XMLFamilyType eType,
                           sal_uInt16 nPrefix,
                           ::xmloff::token::XMLTokenEnum eToken,
                           sal_Bool bPersistent );

    virtual ~XMLStyleOOoTContext();

    virtual XMLTransformerContext *CreateChildContext( sal_uInt16 nPrefix,
                                   const ::rtl::OUString& rLocalName,
                                   const ::rtl::OUString& rQName,
                                   const ::com::sun::star::uno::Reference< ::com::sun::star::xml::sax::XAttributeList >& xAttrList );

    virtual void StartElement( const ::com::sun::star::uno::Reference< ::com::sun::star::xml::sax::XAttributeList >& xAttrList );
    virtual void EndElement();
    virtual void Characters( const ::rtl::OUString& rChars );
    virtual sal_Bool IsPersistent() const;

    static XMLTransformerActions *CreateTransformerActions( sal_uInt16 nType );

};

#endif  //  _XMLOFF_STYLEOOOTCONTEXT_HXX

<|endoftext|>


<commit_before>/*
 * Copyright 2015 - 2021 gary@drinkingtea.net
 *
 * This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/.
 */

#pragma once

#include "bit.hpp"
#include "new.hpp"
#include "types.hpp"
#include "utility.hpp"

namespace ox {

template<typename T>
class Vector {

	private:
		std::size_t m_size = 0;
		std::size_t m_cap = 0;
		T *m_items = nullptr;

	public:
		Vector() noexcept = default;

		explicit Vector(std::size_t size) noexcept;

		Vector(const Vector &other);

		Vector(Vector &&other) noexcept;

		~Vector();

		bool operator==(const Vector &other) const;

		Vector &operator=(const Vector &other);

		Vector &operator=(Vector &&other);

		[[nodiscard]] T &operator[](std::size_t i) noexcept;

		[[nodiscard]] const T &operator[](std::size_t i) const noexcept;

		[[nodiscard]] Result<T&> front() noexcept;

		[[nodiscard]] Result<const T&> front() const noexcept;

		[[nodiscard]] Result<T&> back() noexcept;

		[[nodiscard]] Result<const T&> back() const noexcept;

		[[nodiscard]] std::size_t size() const noexcept;

		[[nodiscard]] bool empty() const noexcept;

		void clear();

		void resize(std::size_t size);

		[[nodiscard]]
		constexpr T *data() noexcept {
			return m_items;
		}

		[[nodiscard]]
		constexpr const T *data() const noexcept {
			return m_items;
		}

		[[nodiscard]] bool contains(const T&) const;

		void insert(std::size_t pos, const T &val);

		template<typename... Args>
		void emplace_back(Args&&... args);

		void push_back(const T &item);

		void pop_back();

		/**
		 * Removes an item from the Vector.
		 * @param pos position of item to remove
		 * @return Error if index is out of bounds
		 */
		Error erase(std::size_t pos);

		/**
		 * Moves the last item in the Vector to position pos and decrements the
		 * size by 1.
		 * @param pos position of item to remove
		 * @return Error if index is out of bounds
		 */
		Error unordered_erase(std::size_t pos);

	private:
		void expandCap(std::size_t cap);

};

template<typename T>
Vector<T>::Vector(std::size_t size) noexcept {
	m_size = size;
	m_cap = m_size;
	m_items = bit_cast<T*>(new AllocAlias<T>[m_cap]);
	for (std::size_t i = 0; i < size; i++) {
		m_items[i] = {};
	}
}

template<typename T>
Vector<T>::Vector(const Vector<T> &other) {
	m_size = other.m_size;
	m_cap = other.m_cap;
	m_items = bit_cast<T*>(new AllocAlias<T>[m_cap]);
	for (std::size_t i = 0; i < m_size; i++) {
		m_items[i] = ox::move(other.m_items[i]);
	}
}

template<typename T>
Vector<T>::Vector(Vector<T> &&other) noexcept {
	m_size = other.m_size;
	m_cap = other.m_cap;
	m_items = other.m_items;
	other.m_size = 0;
	other.m_cap = 0;
	other.m_items = nullptr;
}

template<typename T>
Vector<T>::~Vector() {
	if constexpr(ox::is_class<T>()) {
		for (std::size_t i = 0; i < m_size; i++) {
			m_items[i].~T();
		}
	}
	delete[] bit_cast<AllocAlias<T>*>(m_items);
	m_items = nullptr;
}

template<typename T>
bool Vector<T>::operator==(const Vector<T> &other) const {
	for (std::size_t i = 0; i < m_size; i++) {
		if (!(m_items[i] == other.m_items[i])) {
			return false;
		}
	}
	return true;
}

template<typename T>
Vector<T> &Vector<T>::operator=(const Vector<T> &other) {
	this->~Vector<T>();
	m_size = other.m_size;
	m_cap = other.m_cap;
	m_items = bit_cast<T*>(new AllocAlias<T>[m_cap]);
	for (std::size_t i = 0; i < m_size; i++) {
		m_items[i] = other.m_items[i];
	}
	return *this;
}

template<typename T>
Vector<T> &Vector<T>::operator=(Vector<T> &&other) {
	this->~Vector<T>();
	m_size = other.m_size;
	m_cap = other.m_cap;
	m_items = other.m_items;
	other.m_size = 0;
	other.m_cap = 0;
	other.m_items = nullptr;
	return *this;
}

template<typename T>
T &Vector<T>::operator[](std::size_t i) noexcept {
	return m_items[i];
}

template<typename T>
const T &Vector<T>::operator[](std::size_t i) const noexcept {
	return m_items[i];
}

template<typename T>
Result<T&> Vector<T>::front() noexcept {
	if (!m_size) {
		AllocAlias<T> v;
		return {*bit_cast<T*>(&v), OxError(1)};
	}
	return m_items[0];
}

template<typename T>
Result<const T&> Vector<T>::front() const noexcept {
	if (!m_size) {
		AllocAlias<T> v;
		return {*bit_cast<T*>(&v), OxError(1)};
	}
	return m_items[0];
}

template<typename T>
Result<T&> Vector<T>::back() noexcept {
	if (!m_size) {
		AllocAlias<T> v;
		return {*bit_cast<T*>(&v), OxError(1)};
	}
	return m_items[m_size - 1];
}

template<typename T>
Result<const T&> Vector<T>::back() const noexcept {
	if (!m_size) {
		AllocAlias<T> v;
		return {*bit_cast<T*>(&v), OxError(1)};
	}
	return m_items[m_size - 1];
}

template<typename T>
std::size_t Vector<T>::size() const noexcept {
	return m_size;
}

template<typename T>
bool Vector<T>::empty() const noexcept {
	return !m_size;
}

template<typename T>
void Vector<T>::clear() {
	resize(0);
}

template<typename T>
void Vector<T>::resize(std::size_t size) {
	if (m_cap < size) {
		expandCap(size);
	}
	if (m_size < size) {
		for (std::size_t i = m_size; i < size; i++) {
			m_items[i] = {};
		}
	} else {
		for (std::size_t i = size; i < m_size; i++) {
			m_items[i].~T();
		}
	}
	m_size = size;
}

template<typename T>
bool Vector<T>::contains(const T &v) const {
	for (std::size_t i = 0; i < m_size; i++) {
		if (m_items[i] == v) {
			return true;
		}
	}
	return false;
}

template<typename T>
void Vector<T>::insert(std::size_t pos, const T &val) {
	// TODO: insert should ideally have its own expandCap
	if (m_size == m_cap) {
		expandCap(m_cap ? m_cap * 2 : 100);
	}
	for (auto i = m_size; i > pos; --i) {
		m_items[i] = ox::move(m_items[i - 1]);
	}
	m_items[pos] = val;
	++m_size;
}

template<typename T>
template<typename... Args>
void Vector<T>::emplace_back(Args&&... args) {
	if (m_size == m_cap) {
		expandCap(m_cap ? m_cap * 2 : 100);
	}
	new (&m_items[m_size]) T{args...};
	++m_size;
}

template<typename T>
void Vector<T>::push_back(const T &item) {
	if (m_size == m_cap) {
		expandCap(m_cap ? m_cap * 2 : 100);
	}
	new (&m_items[m_size]) T(item);
	++m_size;
}

template<typename T>
void Vector<T>::pop_back() {
	--m_size;
	m_items[m_size].~T();
}

template<typename T>
Error Vector<T>::erase(std::size_t pos) {
	if (pos >= m_size) {
		return OxError(1);
	}
	--m_size;
	for (auto i = pos; i < m_size; ++i) {
		m_items[i] = ox::move(m_items[i + 1]);
	}
	return OxError(0);
}

template<typename T>
Error Vector<T>::unordered_erase(std::size_t pos) {
	if (pos >= m_size) {
		return OxError(1);
	}
	m_size--;
	m_items[pos] = ox::move(m_items[m_size]);
	return OxError(0);
}

template<typename T>
void Vector<T>::expandCap(std::size_t cap) {
	auto oldItems = m_items;
	m_cap = cap;
	m_items = bit_cast<T*>(new AllocAlias<T>[m_cap]);
	if (oldItems) { // move over old items
		const auto itRange = cap > m_size ? m_size : cap;
		for (std::size_t i = 0; i < itRange; i++) {
			m_items[i] = ox::move(oldItems[i]);
		}
		for (std::size_t i = itRange; i < m_cap; i++) {
			new (&m_items[i]) T;
		}
		delete[] bit_cast<AllocAlias<T>*>(oldItems);
	}
}

}
<commit_msg>[ox/std] Cleanup<commit_after>/*
 * Copyright 2015 - 2021 gary@drinkingtea.net
 *
 * This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/.
 */

#pragma once

#include "bit.hpp"
#include "new.hpp"
#include "types.hpp"
#include "utility.hpp"

namespace ox {

template<typename T>
class Vector {

	private:
		std::size_t m_size = 0;
		std::size_t m_cap = 0;
		T *m_items = nullptr;

	public:
		Vector() noexcept = default;

		explicit Vector(std::size_t size) noexcept;

		Vector(const Vector &other);

		Vector(Vector &&other) noexcept;

		~Vector();

		bool operator==(const Vector &other) const;

		Vector &operator=(const Vector &other);

		Vector &operator=(Vector &&other);

		[[nodiscard]]
		T &operator[](std::size_t i) noexcept;

		[[nodiscard]]
		const T &operator[](std::size_t i) const noexcept;

		[[nodiscard]]
		Result<T&> front() noexcept;

		[[nodiscard]]
		Result<const T&> front() const noexcept;

		[[nodiscard]]
		Result<T&> back() noexcept;

		[[nodiscard]]
		Result<const T&> back() const noexcept;

		[[nodiscard]]
		std::size_t size() const noexcept;

		[[nodiscard]]
		bool empty() const noexcept;

		void clear();

		void resize(std::size_t size);

		[[nodiscard]]
		constexpr T *data() noexcept {
			return m_items;
		}

		[[nodiscard]]
		constexpr const T *data() const noexcept {
			return m_items;
		}

		[[nodiscard]] bool contains(const T&) const;

		void insert(std::size_t pos, const T &val);

		template<typename... Args>
		void emplace_back(Args&&... args);

		void push_back(const T &item);

		void pop_back();

		/**
		 * Removes an item from the Vector.
		 * @param pos position of item to remove
		 * @return Error if index is out of bounds
		 */
		Error erase(std::size_t pos);

		/**
		 * Moves the last item in the Vector to position pos and decrements the
		 * size by 1.
		 * @param pos position of item to remove
		 * @return Error if index is out of bounds
		 */
		Error unordered_erase(std::size_t pos);

	private:
		void expandCap(std::size_t cap);

};

template<typename T>
Vector<T>::Vector(std::size_t size) noexcept {
	m_size = size;
	m_cap = m_size;
	m_items = bit_cast<T*>(new AllocAlias<T>[m_cap]);
	for (std::size_t i = 0; i < size; i++) {
		m_items[i] = {};
	}
}

template<typename T>
Vector<T>::Vector(const Vector<T> &other) {
	m_size = other.m_size;
	m_cap = other.m_cap;
	m_items = bit_cast<T*>(new AllocAlias<T>[m_cap]);
	for (std::size_t i = 0; i < m_size; i++) {
		m_items[i] = ox::move(other.m_items[i]);
	}
}

template<typename T>
Vector<T>::Vector(Vector<T> &&other) noexcept {
	m_size = other.m_size;
	m_cap = other.m_cap;
	m_items = other.m_items;
	other.m_size = 0;
	other.m_cap = 0;
	other.m_items = nullptr;
}

template<typename T>
Vector<T>::~Vector() {
	if constexpr(ox::is_class<T>()) {
		for (std::size_t i = 0; i < m_size; i++) {
			m_items[i].~T();
		}
	}
	delete[] bit_cast<AllocAlias<T>*>(m_items);
	m_items = nullptr;
}

template<typename T>
bool Vector<T>::operator==(const Vector<T> &other) const {
	for (std::size_t i = 0; i < m_size; i++) {
		if (!(m_items[i] == other.m_items[i])) {
			return false;
		}
	}
	return true;
}

template<typename T>
Vector<T> &Vector<T>::operator=(const Vector<T> &other) {
	this->~Vector<T>();
	m_size = other.m_size;
	m_cap = other.m_cap;
	m_items = bit_cast<T*>(new AllocAlias<T>[m_cap]);
	for (std::size_t i = 0; i < m_size; i++) {
		m_items[i] = other.m_items[i];
	}
	return *this;
}

template<typename T>
Vector<T> &Vector<T>::operator=(Vector<T> &&other) {
	this->~Vector<T>();
	m_size = other.m_size;
	m_cap = other.m_cap;
	m_items = other.m_items;
	other.m_size = 0;
	other.m_cap = 0;
	other.m_items = nullptr;
	return *this;
}

template<typename T>
T &Vector<T>::operator[](std::size_t i) noexcept {
	return m_items[i];
}

template<typename T>
const T &Vector<T>::operator[](std::size_t i) const noexcept {
	return m_items[i];
}

template<typename T>
Result<T&> Vector<T>::front() noexcept {
	if (!m_size) {
		AllocAlias<T> v;
		return {*bit_cast<T*>(&v), OxError(1)};
	}
	return m_items[0];
}

template<typename T>
Result<const T&> Vector<T>::front() const noexcept {
	if (!m_size) {
		AllocAlias<T> v;
		return {*bit_cast<T*>(&v), OxError(1)};
	}
	return m_items[0];
}

template<typename T>
Result<T&> Vector<T>::back() noexcept {
	if (!m_size) {
		AllocAlias<T> v;
		return {*bit_cast<T*>(&v), OxError(1)};
	}
	return m_items[m_size - 1];
}

template<typename T>
Result<const T&> Vector<T>::back() const noexcept {
	if (!m_size) {
		AllocAlias<T> v;
		return {*bit_cast<T*>(&v), OxError(1)};
	}
	return m_items[m_size - 1];
}

template<typename T>
std::size_t Vector<T>::size() const noexcept {
	return m_size;
}

template<typename T>
bool Vector<T>::empty() const noexcept {
	return !m_size;
}

template<typename T>
void Vector<T>::clear() {
	resize(0);
}

template<typename T>
void Vector<T>::resize(std::size_t size) {
	if (m_cap < size) {
		expandCap(size);
	}
	if (m_size < size) {
		for (std::size_t i = m_size; i < size; i++) {
			m_items[i] = {};
		}
	} else {
		for (std::size_t i = size; i < m_size; i++) {
			m_items[i].~T();
		}
	}
	m_size = size;
}

template<typename T>
bool Vector<T>::contains(const T &v) const {
	for (std::size_t i = 0; i < m_size; i++) {
		if (m_items[i] == v) {
			return true;
		}
	}
	return false;
}

template<typename T>
void Vector<T>::insert(std::size_t pos, const T &val) {
	// TODO: insert should ideally have its own expandCap
	if (m_size == m_cap) {
		expandCap(m_cap ? m_cap * 2 : 100);
	}
	for (auto i = m_size; i > pos; --i) {
		m_items[i] = ox::move(m_items[i - 1]);
	}
	m_items[pos] = val;
	++m_size;
}

template<typename T>
template<typename... Args>
void Vector<T>::emplace_back(Args&&... args) {
	if (m_size == m_cap) {
		expandCap(m_cap ? m_cap * 2 : 100);
	}
	new (&m_items[m_size]) T{args...};
	++m_size;
}

template<typename T>
void Vector<T>::push_back(const T &item) {
	if (m_size == m_cap) {
		expandCap(m_cap ? m_cap * 2 : 100);
	}
	new (&m_items[m_size]) T(item);
	++m_size;
}

template<typename T>
void Vector<T>::pop_back() {
	--m_size;
	m_items[m_size].~T();
}

template<typename T>
Error Vector<T>::erase(std::size_t pos) {
	if (pos >= m_size) {
		return OxError(1);
	}
	--m_size;
	for (auto i = pos; i < m_size; ++i) {
		m_items[i] = ox::move(m_items[i + 1]);
	}
	return OxError(0);
}

template<typename T>
Error Vector<T>::unordered_erase(std::size_t pos) {
	if (pos >= m_size) {
		return OxError(1);
	}
	m_size--;
	m_items[pos] = ox::move(m_items[m_size]);
	return OxError(0);
}

template<typename T>
void Vector<T>::expandCap(std::size_t cap) {
	auto oldItems = m_items;
	m_cap = cap;
	m_items = bit_cast<T*>(new AllocAlias<T>[m_cap]);
	if (oldItems) { // move over old items
		const auto itRange = cap > m_size ? m_size : cap;
		for (std::size_t i = 0; i < itRange; i++) {
			m_items[i] = ox::move(oldItems[i]);
		}
		for (std::size_t i = itRange; i < m_cap; i++) {
			new (&m_items[i]) T;
		}
		delete[] bit_cast<AllocAlias<T>*>(oldItems);
	}
}

}
<|endoftext|>


<commit_before>/* Copyright 2020 The TensorFlow Quantum Authors. All Rights Reserved.

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 "tensorflow_quantum/core/qsim/util.h"

#include <vector>

#include "gtest/gtest.h"

namespace tfq {
namespace qsim {
namespace {

TEST(Util, ComputeBitmask) {
  const std::vector<unsigned int> parity_;
  const std::vector<unsigned int> parity_0({0});
  const std::vector<unsigned int> parity_1({1});
  const std::vector<unsigned int> parity_01({0, 1});
  ASSERT_EQ(ComputeBitmask(parity_), 0);
  ASSERT_EQ(ComputeBitmask(parity_0), 1);
  ASSERT_EQ(ComputeBitmask(parity_1), 2);
  ASSERT_EQ(ComputeBitmask(parity_01), 3);
}

// TEST(Util, ComputeParity) {
//   // Check all parities for all two qubit states
//   uint64_t sample_01;
//   const std::vector<unsigned int> parity_;
//   const std::vector<unsigned int> parity_0({0});
//   const std::vector<unsigned int> parity_1({1});
//   const std::vector<unsigned int> parity_01({0, 1});
//   // |00> <--> 0
//   sample_01 = 0;
//   ASSERT_EQ(ComputeParity(parity_, sample_01), 1);
//   ASSERT_EQ(ComputeParity(parity_0, sample_01), 1);
//   ASSERT_EQ(ComputeParity(parity_1, sample_01), 1);
//   ASSERT_EQ(ComputeParity(parity_01, sample_01), 1);
//   // |01> <--> 1
//   sample_01 = 1;
//   ASSERT_EQ(ComputeParity(parity_, sample_01), 1);
//   ASSERT_EQ(ComputeParity(parity_0, sample_01), -1);
//   ASSERT_EQ(ComputeParity(parity_1, sample_01), 1);
//   ASSERT_EQ(ComputeParity(parity_01, sample_01), -1);
//   // |10> <--> 2
//   sample_01 = 2;
//   ASSERT_EQ(ComputeParity(parity_, sample_01), 1);
//   ASSERT_EQ(ComputeParity(parity_0, sample_01), 1);
//   ASSERT_EQ(ComputeParity(parity_1, sample_01), -1);
//   ASSERT_EQ(ComputeParity(parity_01, sample_01), -1);
//   // |11> <--> 3
//   sample_01 = 3;
//   ASSERT_EQ(ComputeParity(parity_, sample_01), 1);
//   ASSERT_EQ(ComputeParity(parity_0, sample_01), -1);
//   ASSERT_EQ(ComputeParity(parity_1, sample_01), -1);
//   ASSERT_EQ(ComputeParity(parity_01, sample_01), 1);

//   // Check all parities for a three qubit state
//   // |101> <--> 5
//   uint64_t sample_012(5);
//   const std::vector<unsigned int> parity_2({2});
//   const std::vector<unsigned int> parity_02({0, 2});
//   const std::vector<unsigned int> parity_12({1, 2});
//   const std::vector<unsigned int> parity_012({0, 1, 2});
//   ASSERT_EQ(ComputeParity(parity_, sample_012), 1);
//   ASSERT_EQ(ComputeParity(parity_0, sample_012), -1);
//   ASSERT_EQ(ComputeParity(parity_1, sample_012), 1);
//   ASSERT_EQ(ComputeParity(parity_01, sample_012), -1);
//   ASSERT_EQ(ComputeParity(parity_2, sample_012), -1);
//   ASSERT_EQ(ComputeParity(parity_02, sample_012), 1);
//   ASSERT_EQ(ComputeParity(parity_12, sample_012), -1);
//   ASSERT_EQ(ComputeParity(parity_012, sample_012), 1);
//   // |100> <--> 4
//   sample_012 = 4;
//   ASSERT_EQ(ComputeParity(parity_, sample_012), 1);
//   ASSERT_EQ(ComputeParity(parity_0, sample_012), 1);
//   ASSERT_EQ(ComputeParity(parity_1, sample_012), 1);
//   ASSERT_EQ(ComputeParity(parity_01, sample_012), 1);
//   ASSERT_EQ(ComputeParity(parity_2, sample_012), -1);
//   ASSERT_EQ(ComputeParity(parity_02, sample_012), -1);
//   ASSERT_EQ(ComputeParity(parity_12, sample_012), -1);
//   ASSERT_EQ(ComputeParity(parity_012, sample_012), -1);

//   // Check some parities for a six qubit state
//   // |011000> <--> 24
//   uint64_t sample_six(24);
//   const std::vector<unsigned int> parity_012345({0, 1, 2, 3, 4, 5});
//   const std::vector<unsigned int> parity_134({1, 3, 4});
//   const std::vector<unsigned int> parity_025({0, 2, 5});
//   const std::vector<unsigned int> parity_4({4});
//   ASSERT_EQ(ComputeParity(parity_, sample_six), 1);
//   ASSERT_EQ(ComputeParity(parity_0, sample_six), 1);
//   ASSERT_EQ(ComputeParity(parity_1, sample_six), 1);
//   ASSERT_EQ(ComputeParity(parity_01, sample_six), 1);
//   ASSERT_EQ(ComputeParity(parity_2, sample_six), 1);
//   ASSERT_EQ(ComputeParity(parity_02, sample_six), 1);
//   ASSERT_EQ(ComputeParity(parity_12, sample_six), 1);
//   ASSERT_EQ(ComputeParity(parity_012, sample_six), 1);
//   ASSERT_EQ(ComputeParity(parity_012345, sample_six), 1);
//   ASSERT_EQ(ComputeParity(parity_134, sample_six), 1);
//   ASSERT_EQ(ComputeParity(parity_025, sample_six), 1);
//   ASSERT_EQ(ComputeParity(parity_4, sample_six), -1);
// }

}  // namespace
}  // namespace qsim
}  // namespace tfq
<commit_msg>Fixed tests<commit_after>/* Copyright 2020 The TensorFlow Quantum Authors. All Rights Reserved.

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 "tensorflow_quantum/core/qsim/util.h"

#include <vector>

#include "gtest/gtest.h"

namespace tfq {
namespace qsim {
namespace {

TEST(Util, ComputeBitmask) {
  const std::vector<unsigned int> parity_;
  const std::vector<unsigned int> parity_0({0});
  const std::vector<unsigned int> parity_1({1});
  const std::vector<unsigned int> parity_01({0, 1});
  const std::vector<unsigned int> parity_2({2});
  const std::vector<unsigned int> parity_02({0, 2});
  const std::vector<unsigned int> parity_12({1, 2});
  const std::vector<unsigned int> parity_012({0, 1, 2});
  ASSERT_EQ(ComputeBitmask(parity_), 0);
  ASSERT_EQ(ComputeBitmask(parity_0), 1);
  ASSERT_EQ(ComputeBitmask(parity_1), 2);
  ASSERT_EQ(ComputeBitmask(parity_01), 3);
  ASSERT_EQ(ComputeBitmask(parity_2), 4);
  ASSERT_EQ(ComputeBitmask(parity_02), 5);
  ASSERT_EQ(ComputeBitmask(parity_12), 6);
  ASSERT_EQ(ComputeBitmask(parity_012), 7);
}

TEST(Util, ComputeParity) {
  // Check all parities for all two qubit states
  uint64_t sample_01;
  // |00> <--> 0
  sample_01 = 0;
  ASSERT_EQ(ComputeParity(0, sample_01), 1);
  ASSERT_EQ(ComputeParity(1, sample_01), 1);
  ASSERT_EQ(ComputeParity(2, sample_01), 1);
  ASSERT_EQ(ComputeParity(3, sample_01), 1);
  // |01> <--> 1
  sample_01 = 1;
  ASSERT_EQ(ComputeParity(0, sample_01), 1);
  ASSERT_EQ(ComputeParity(1, sample_01), -1);
  ASSERT_EQ(ComputeParity(2, sample_01), 1);
  ASSERT_EQ(ComputeParity(3, sample_01), -1);
  // |10> <--> 2
  sample_01 = 2;
  ASSERT_EQ(ComputeParity(0, sample_01), 1);
  ASSERT_EQ(ComputeParity(1, sample_01), 1);
  ASSERT_EQ(ComputeParity(2, sample_01), -1);
  ASSERT_EQ(ComputeParity(3, sample_01), -1);
  // |11> <--> 3
  sample_01 = 3;
  ASSERT_EQ(ComputeParity(0, sample_01), 1);
  ASSERT_EQ(ComputeParity(1, sample_01), -1);
  ASSERT_EQ(ComputeParity(2, sample_01), -1);
  ASSERT_EQ(ComputeParity(3, sample_01), 1);

  // Check all parities for a three qubit state
  // |101> <--> 5
  uint64_t sample_012(5);
  ASSERT_EQ(ComputeParity(0, sample_012), 1);
  ASSERT_EQ(ComputeParity(1, sample_012), -1);
  ASSERT_EQ(ComputeParity(2, sample_012), 1);
  ASSERT_EQ(ComputeParity(3, sample_012), -1);
  ASSERT_EQ(ComputeParity(4, sample_012), -1);
  ASSERT_EQ(ComputeParity(5, sample_012), 1);
  ASSERT_EQ(ComputeParity(6, sample_012), -1);
  ASSERT_EQ(ComputeParity(7, sample_012), 1);
  // |100> <--> 4
  sample_012 = 4;
  ASSERT_EQ(ComputeParity(0, sample_012), 1);
  ASSERT_EQ(ComputeParity(1, sample_012), 1);
  ASSERT_EQ(ComputeParity(2, sample_012), 1);
  ASSERT_EQ(ComputeParity(3, sample_012), 1);
  ASSERT_EQ(ComputeParity(4, sample_012), -1);
  ASSERT_EQ(ComputeParity(5, sample_012), -1);
  ASSERT_EQ(ComputeParity(6, sample_012), -1);
  ASSERT_EQ(ComputeParity(7, sample_012), -1);

  // Check some parities for a six qubit state
  // |011000> <--> 24
  uint64_t sample_six(24);
  ASSERT_EQ(ComputeParity(0, sample_six), 1);
  ASSERT_EQ(ComputeParity(1, sample_six), 1);
  ASSERT_EQ(ComputeParity(2, sample_six), 1);
  ASSERT_EQ(ComputeParity(3, sample_six), 1);
  ASSERT_EQ(ComputeParity(4, sample_six), 1);
  ASSERT_EQ(ComputeParity(5, sample_six), 1);
  ASSERT_EQ(ComputeParity(6, sample_six), 1);
  ASSERT_EQ(ComputeParity(7, sample_six), 1);
  ASSERT_EQ(ComputeParity(63, sample_six), 1);
  ASSERT_EQ(ComputeParity(25, sample_six), 1);
  ASSERT_EQ(ComputeParity(37, sample_six), 1);
  ASSERT_EQ(ComputeParity(16, sample_six), -1);
}

}  // namespace
}  // namespace qsim
}  // namespace tfq
<|endoftext|>