<commit_before>/*****************************************************************************
 *
 * This file is part of Mapnik (c++ mapping toolkit)
 *
 * Copyright (C) 2007 Artem Pavlenko
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
 *
 *****************************************************************************/
//$Id$

#include <mapnik/global.hpp>
#include <mapnik/datasource.hpp>
#include <mapnik/envelope.hpp>
#include <mapnik/geometry.hpp>
#include <mapnik/feature.hpp>
#include <mapnik/feature_layer_desc.hpp>
#include <mapnik/wkb.hpp>
#include <mapnik/unicode.hpp>

// ogr
#include "sqlite_featureset.hpp"

using std::clog;
using std::endl;

using mapnik::query;
using mapnik::Envelope;
using mapnik::CoordTransform;
using mapnik::Feature;
using mapnik::feature_ptr;
using mapnik::point_impl;
using mapnik::line_string_impl;
using mapnik::polygon_impl;
using mapnik::geometry2d;
using mapnik::geometry_utils;
using mapnik::transcoder;

sqlite_featureset::sqlite_featureset(boost::shared_ptr<sqlite_resultset> rs,
                                     std::string const& encoding,
                                     bool multiple_geometries)
   : rs_(rs),
     tr_(new transcoder(encoding)),
     multiple_geometries_(multiple_geometries)
{
}

sqlite_featureset::~sqlite_featureset() {}

feature_ptr sqlite_featureset::next()
{
    if (rs_->is_valid () && rs_->step_next ())
    {
        int size;
        const char* data = (const char *) rs_->column_blob (0, size);
        int feature_id = rs_->column_integer (1);

#ifdef MAPNIK_DEBUG
        // clog << "feature_oid=" << feature_id << endl;
#endif

        feature_ptr feature(new Feature(feature_id));
        geometry_utils::from_wkb(*feature,data,size,multiple_geometries_,mapnik::wkbSQLite);

        for (int i = 2; i < rs_->column_count (); ++i)
        {
           const int type_oid = rs_->column_type (i);
           const char* fld_name = rs_->column_name (i);

           switch (type_oid)
           {
              case SQLITE_INTEGER:
              {
                 boost::put(*feature,fld_name,rs_->column_integer (i));
                 break;
              }

              case SQLITE_FLOAT:
              {
                 boost::put(*feature,fld_name,rs_->column_double (i));
                 break;
              }

              case SQLITE_TEXT:
              {
                 UnicodeString ustr = tr_->transcode (rs_->column_text (i));
                 boost::put(*feature,fld_name,ustr);
                 break;
              }

              case SQLITE_BLOB:
              case SQLITE_NULL:
                 break;

              default:
#ifdef MAPNIK_DEBUG
                 clog << "unhandled type_oid=" << type_oid << endl;
#endif
                 break;
           }
        }

        return feature;
    }

    return feature_ptr();
}

<commit_msg>+ use standard WKB by default<commit_after>/*****************************************************************************
 *
 * This file is part of Mapnik (c++ mapping toolkit)
 *
 * Copyright (C) 2007 Artem Pavlenko
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
 *
 *****************************************************************************/
//$Id$

#include <mapnik/global.hpp>
#include <mapnik/datasource.hpp>
#include <mapnik/envelope.hpp>
#include <mapnik/geometry.hpp>
#include <mapnik/feature.hpp>
#include <mapnik/feature_layer_desc.hpp>
#include <mapnik/wkb.hpp>
#include <mapnik/unicode.hpp>

// ogr
#include "sqlite_featureset.hpp"

using std::clog;
using std::endl;

using mapnik::query;
using mapnik::Envelope;
using mapnik::CoordTransform;
using mapnik::Feature;
using mapnik::feature_ptr;
using mapnik::point_impl;
using mapnik::line_string_impl;
using mapnik::polygon_impl;
using mapnik::geometry2d;
using mapnik::geometry_utils;
using mapnik::transcoder;

sqlite_featureset::sqlite_featureset(boost::shared_ptr<sqlite_resultset> rs,
                                     std::string const& encoding,
                                     bool multiple_geometries)
   : rs_(rs),
     tr_(new transcoder(encoding)),
     multiple_geometries_(multiple_geometries)
{
}

sqlite_featureset::~sqlite_featureset() {}

feature_ptr sqlite_featureset::next()
{
    if (rs_->is_valid () && rs_->step_next ())
    {
        int size;
        const char* data = (const char *) rs_->column_blob (0, size);
        int feature_id = rs_->column_integer (1);

#ifdef MAPNIK_DEBUG
        // clog << "feature_oid=" << feature_id << endl;
#endif

        feature_ptr feature(new Feature(feature_id));
        geometry_utils::from_wkb(*feature,data,size,multiple_geometries_,mapnik::wkbGeneric);

        for (int i = 2; i < rs_->column_count (); ++i)
        {
           const int type_oid = rs_->column_type (i);
           const char* fld_name = rs_->column_name (i);

           switch (type_oid)
           {
              case SQLITE_INTEGER:
              {
                 boost::put(*feature,fld_name,rs_->column_integer (i));
                 break;
              }

              case SQLITE_FLOAT:
              {
                 boost::put(*feature,fld_name,rs_->column_double (i));
                 break;
              }

              case SQLITE_TEXT:
              {
                 UnicodeString ustr = tr_->transcode (rs_->column_text (i));
                 boost::put(*feature,fld_name,ustr);
                 break;
              }

              case SQLITE_BLOB:
              case SQLITE_NULL:
                 break;

              default:
#ifdef MAPNIK_DEBUG
                 clog << "unhandled type_oid=" << type_oid << endl;
#endif
                 break;
           }
        }

        return feature;
    }

    return feature_ptr();
}

<|endoftext|>


<commit_before>
#include <deal.II/base/function.h>
#include <deal.II/base/function_parser.h>
#include <deal.II/base/logstream.h>
#include <deal.II/base/parameter_handler.h>
#include <deal.II/base/quadrature_lib.h>
#include <deal.II/base/timer.h>
#include <deal.II/base/table_handler.h>

#include <deal.II/lac/constraint_matrix.h>
#include <deal.II/lac/dynamic_sparsity_pattern.h>
#include <deal.II/lac/full_matrix.h>
#include <deal.II/lac/petsc_parallel_sparse_matrix.h>
#include <deal.II/lac/petsc_parallel_vector.h>
#include <deal.II/lac/petsc_solver.h>
#include <deal.II/lac/petsc_precondition.h>
#include <deal.II/lac/sparsity_tools.h>
#include <deal.II/lac/vector.h>

#include <deal.II/grid/grid_generator.h>
#include <deal.II/grid/grid_out.h>
#include <deal.II/grid/grid_refinement.h>
#include <deal.II/grid/tria.h>
#include <deal.II/grid/tria_accessor.h>
#include <deal.II/grid/tria_iterator.h>

#include <deal.II/distributed/grid_refinement.h>
#include <deal.II/distributed/tria.h>

#include <deal.II/dofs/dof_handler.h>
#include <deal.II/dofs/dof_accessor.h>
#include <deal.II/dofs/dof_tools.h>

#include <deal.II/fe/fe_values.h>
#include <deal.II/fe/fe_system.h>
#include <deal.II/fe/fe_q.h>

#include <deal.II/numerics/data_out.h>
#include <deal.II/numerics/error_estimator.h>
#include <deal.II/numerics/matrix_tools.h>
#include <deal.II/numerics/vector_tools.h>

// #include <boost/program_options.hpp>

#include <mandy/function_tools.h>

#include <mandy/elastic_problem.h>
#include <mandy/piezoelectric_problem.h>

#include <fstream>
#include <iostream>

#include <algorithm>    // std::transform
#include <functional>   // std::plus

namespace aphex
{

  template <int dim>
  class Aphex
  {
  public:

    /**
     * Class constructor.
     */
    Aphex (const std::string &prm);

    /**
     * Class destructor.
     */
    ~Aphex ();

    /**
     * Run.
     */
    void run ();

  private:

    /**
     * MPI communicator.
     */
    MPI_Comm mpi_communicator;

    /**
     * A distributed grid on which all computations are done.
     */
    dealii::parallel::distributed::Triangulation<dim> triangulation;

    /**
     * Solution of the elastic problem.
     */
    dealii::PETScWrappers::MPI::Vector displacement;

    /**
     * Solution of the piezoelectric.
     */
    dealii::PETScWrappers::MPI::Vector piezoelectric_potential;

    /**
     * Parallel iostream.
     */
    dealii::ConditionalOStream pcout;

    /**
     * Stop clock.
     */
    dealii::TimerOutput timer;

  };

  template <int dim>
  Aphex<dim>::Aphex (const std::string &prm)
    :
    mpi_communicator (MPI_COMM_WORLD),
    triangulation (mpi_communicator,
		   typename dealii::Triangulation<dim>::MeshSmoothing
		   (dealii::Triangulation<dim>::smoothing_on_refinement |
		    dealii::Triangulation<dim>::smoothing_on_coarsening)),
    pcout (std::cout, (dealii::Utilities::MPI::this_mpi_process (mpi_communicator) == 0)),
    timer (mpi_communicator, pcout,
     	   dealii::TimerOutput::summary,
     	   dealii::TimerOutput::wall_times)
  {}

  template <int dim>
  Aphex<dim>::~Aphex ()
  {}

  template <int dim>
  void
  Aphex<dim>::run ()
  {

    try
      {
	dealii::TimerOutput::Scope time (timer, "aphex");

	dealii::GridGenerator::hyper_cube (triangulation, -10, 10);
	// triangulation.refine_global (parameters.get_integer ("Global mesh refinement steps"));
	triangulation.refine_global (2);

	{
	  mandy::FunctionTools<3> material (triangulation, "material.prm");
	  material.run ();
	}

	{
	  dealii::TimerOutput::Scope time (timer, "elastic problem");
	  mandy::ElasticProblem<3> elastic_problem (triangulation, displacement,
						    mpi_communicator, "elastic.prm");
	  elastic_problem.run ();
	}

	{
	  dealii::TimerOutput::Scope time (timer, "piezoelectric problem");
	  mandy::PiezoelectricProblem<3> piezoelectric_problem (triangulation, displacement,
								mpi_communicator, "piezoelectric.prm");
	  piezoelectric_problem.run ();
	}

      }

    catch (std::exception &exc)
      {
	std::cerr << std::endl << std::endl
		  << "----------------------------------------------------"
		  << std::endl;
	std::cerr << "Exception on processing: " << std::endl
		  << exc.what() << std::endl
		  << "Aborting!" << std::endl
		  << "----------------------------------------------------"
		  << std::endl;
      }

    catch (...)
      {
	std::cerr << std::endl << std::endl
		  << "----------------------------------------------------"
		  << std::endl;
	std::cerr << "Unknown exception!" << std::endl
		  << "Aborting!" << std::endl
		  << "----------------------------------------------------"
		  << std::endl;
      }

  } // run ()

} // namespace aphex

/**
 * Main function: Initialise problem and run it.
 */
int main (int argc, char *argv[])
{

  // Initialise MPI
  dealii::Utilities::MPI::MPI_InitFinalize mpi_initialization (argc, argv, 1);

  try
    {
#ifdef INCLUDED_EXTERNAL_BOOST
      // Parse the commandline.
      boost::program_options::options_description description {"Options"};
      description.add_options ()
	("help", "Help screen")
	("prm", value<string> ()->default_value ("aphex.prm"), "Parameter file");

      boost::program_options::variables_map vmap;
      boost::program_options::store
	(boost::program_options::parse_command_line (argc, argv, description), vmap);

      if (vmap.count ("help"))
	std::cout << description
		  << std::endl;

      else if (vmap.count ("prm"))
	std::cout << "Parameter file: " << vmap["prm"].as<string>
		  << std::endl;

      // else if (...)
#endif

      aphex::Aphex<3> aphex ("material.prm");
      aphex.run ();
    }

  catch (std::exception &exc)
    {
      std::cerr << std::endl << std::endl
                << "----------------------------------------------------"
                << std::endl;
      std::cerr << "Exception on processing: " << std::endl
                << exc.what() << std::endl
                << "Aborting!" << std::endl
                << "----------------------------------------------------"
                << std::endl;

      return 1;
    }

  catch (...)
    {
      std::cerr << std::endl << std::endl
                << "----------------------------------------------------"
                << std::endl;
      std::cerr << "Unknown exception!" << std::endl
                << "Aborting!" << std::endl
                << "----------------------------------------------------"
                << std::endl;
      return 1;
    }

  return 0;
}
<commit_msg>Fix timer.<commit_after>
#include <deal.II/base/function.h>
#include <deal.II/base/function_parser.h>
#include <deal.II/base/logstream.h>
#include <deal.II/base/parameter_handler.h>
#include <deal.II/base/quadrature_lib.h>
#include <deal.II/base/timer.h>
#include <deal.II/base/table_handler.h>

#include <deal.II/lac/constraint_matrix.h>
#include <deal.II/lac/dynamic_sparsity_pattern.h>
#include <deal.II/lac/full_matrix.h>
#include <deal.II/lac/petsc_parallel_sparse_matrix.h>
#include <deal.II/lac/petsc_parallel_vector.h>
#include <deal.II/lac/petsc_solver.h>
#include <deal.II/lac/petsc_precondition.h>
#include <deal.II/lac/sparsity_tools.h>
#include <deal.II/lac/vector.h>

#include <deal.II/grid/grid_generator.h>
#include <deal.II/grid/grid_out.h>
#include <deal.II/grid/grid_refinement.h>
#include <deal.II/grid/tria.h>
#include <deal.II/grid/tria_accessor.h>
#include <deal.II/grid/tria_iterator.h>

#include <deal.II/distributed/grid_refinement.h>
#include <deal.II/distributed/tria.h>

#include <deal.II/dofs/dof_handler.h>
#include <deal.II/dofs/dof_accessor.h>
#include <deal.II/dofs/dof_tools.h>

#include <deal.II/fe/fe_values.h>
#include <deal.II/fe/fe_system.h>
#include <deal.II/fe/fe_q.h>

#include <deal.II/numerics/data_out.h>
#include <deal.II/numerics/error_estimator.h>
#include <deal.II/numerics/matrix_tools.h>
#include <deal.II/numerics/vector_tools.h>

// #include <boost/program_options.hpp>

#include <mandy/function_tools.h>

#include <mandy/elastic_problem.h>
#include <mandy/piezoelectric_problem.h>

#include <fstream>
#include <iostream>

#include <algorithm>    // std::transform
#include <functional>   // std::plus

namespace aphex
{

  template <int dim>
  class Aphex
  {
  public:

    /**
     * Class constructor.
     */
    Aphex (const std::string &prm);

    /**
     * Class destructor.
     */
    ~Aphex ();

    /**
     * Run.
     */
    void run ();

  private:

    /**
     * MPI communicator.
     */
    MPI_Comm mpi_communicator;

    /**
     * A distributed grid on which all computations are done.
     */
    dealii::parallel::distributed::Triangulation<dim> triangulation;

    /**
     * Solution of the elastic problem.
     */
    dealii::PETScWrappers::MPI::Vector displacement;

    /**
     * Solution of the piezoelectric.
     */
    dealii::PETScWrappers::MPI::Vector piezoelectric_potential;

    /**
     * Parallel iostream.
     */
    dealii::ConditionalOStream pcout;

    /**
     * Stop clock.
     */
    dealii::TimerOutput timer;

  };

  template <int dim>
  Aphex<dim>::Aphex (const std::string &prm)
    :
    mpi_communicator (MPI_COMM_WORLD),
    triangulation (mpi_communicator,
		   typename dealii::Triangulation<dim>::MeshSmoothing
		   (dealii::Triangulation<dim>::smoothing_on_refinement |
		    dealii::Triangulation<dim>::smoothing_on_coarsening)),
    pcout (std::cout, (dealii::Utilities::MPI::this_mpi_process (mpi_communicator) == 0)),
    timer (mpi_communicator, pcout,
     	   dealii::TimerOutput::summary,
     	   dealii::TimerOutput::wall_times)
  {}

  template <int dim>
  Aphex<dim>::~Aphex ()
  {}

  template <int dim>
  void
  Aphex<dim>::run ()
  {

    try
      {

	dealii::GridGenerator::hyper_cube (triangulation, -10, 10);
	// triangulation.refine_global (parameters.get_integer ("Global mesh refinement steps"));
	triangulation.refine_global (2);

	{
	  dealii::TimerOutput::Scope time (timer, "material");
	  mandy::FunctionTools<3> material (triangulation, "material.prm");
	  material.run ();
	}

	{
	  dealii::TimerOutput::Scope time (timer, "elastic problem");
	  mandy::ElasticProblem<3> elastic_problem (triangulation, displacement,
						    mpi_communicator, "elastic.prm");
	  elastic_problem.run ();
	}

	{
	  dealii::TimerOutput::Scope time (timer, "piezoelectric problem");
	  mandy::PiezoelectricProblem<3> piezoelectric_problem (triangulation, displacement,
								mpi_communicator, "piezoelectric.prm");
	  piezoelectric_problem.run ();
	}

      }

    catch (std::exception &exc)
      {
	std::cerr << std::endl << std::endl
		  << "----------------------------------------------------"
		  << std::endl;
	std::cerr << "Exception on processing: " << std::endl
		  << exc.what() << std::endl
		  << "Aborting!" << std::endl
		  << "----------------------------------------------------"
		  << std::endl;
      }

    catch (...)
      {
	std::cerr << std::endl << std::endl
		  << "----------------------------------------------------"
		  << std::endl;
	std::cerr << "Unknown exception!" << std::endl
		  << "Aborting!" << std::endl
		  << "----------------------------------------------------"
		  << std::endl;
      }

  } // run ()

} // namespace aphex

/**
 * Main function: Initialise problem and run it.
 */
int main (int argc, char *argv[])
{

  // Initialise MPI
  dealii::Utilities::MPI::MPI_InitFinalize mpi_initialization (argc, argv, 1);

  try
    {
#ifdef INCLUDED_EXTERNAL_BOOST
      // Parse the commandline.
      boost::program_options::options_description description {"Options"};
      description.add_options ()
	("help", "Help screen")
	("prm", value<string> ()->default_value ("aphex.prm"), "Parameter file");

      boost::program_options::variables_map vmap;
      boost::program_options::store
	(boost::program_options::parse_command_line (argc, argv, description), vmap);

      if (vmap.count ("help"))
	std::cout << description
		  << std::endl;

      else if (vmap.count ("prm"))
	std::cout << "Parameter file: " << vmap["prm"].as<string>
		  << std::endl;

      // else if (...)
#endif

      aphex::Aphex<3> aphex ("material.prm");
      aphex.run ();
    }

  catch (std::exception &exc)
    {
      std::cerr << std::endl << std::endl
                << "----------------------------------------------------"
                << std::endl;
      std::cerr << "Exception on processing: " << std::endl
                << exc.what() << std::endl
                << "Aborting!" << std::endl
                << "----------------------------------------------------"
                << std::endl;

      return 1;
    }

  catch (...)
    {
      std::cerr << std::endl << std::endl
                << "----------------------------------------------------"
                << std::endl;
      std::cerr << "Unknown exception!" << std::endl
                << "Aborting!" << std::endl
                << "----------------------------------------------------"
                << std::endl;
      return 1;
    }

  return 0;
}
<|endoftext|>


<commit_before>//
// Created by r_milk01 on 29.03.17.
//

#ifndef DUNE_GDT_LOCALVIEW_HH
#define DUNE_GDT_LOCALVIEW_HH

#include <dune/xt/common/ranges.hh>
#include <dune/xt/grid/entity.hh>
#include <dune/xt/la/container/vector-interface.hh>
#include <dune/gdt/spaces/mapper/interfaces.hh>

#include <boost/container/vector.hpp>

namespace Dune {
namespace GDT {

template <class VectorTraits, class ScalarType, class SpaceType, class Descriptor>
class LocalView
{
  using VectorInterface = XT::LA::VectorInterface<VectorTraits, ScalarType>;
  using EntityType = XT::Grid::extract_entity_t<typename SpaceType::GridViewType>;

private:
  void resize(size_t size)
  {
    global_indices_.resize(size);
    value_cache_.resize(size);
  }

public:
  using value_type = ScalarType;

  LocalView(VectorInterface& vector, const SpaceType& space, const Descriptor& descriptor)
    : vector_(vector)
    , space_(space)
    , global_indices_(0)
    , value_cache_(0)
    , descriptor_(descriptor)
  {
  }

  void bind(const EntityType& entity)
  {
    const size_t size{descriptor_.size(space_, entity)};
    resize(size);
    if (size == 1) {
      global_indices_[0] = space_.grid_layer().indexSet().index(entity);
    } else {
      space_.mapper().globalIndices(entity, global_indices_);
    }
    for (auto i : XT::Common::value_range(size)) {
      assert(size == global_indices_.size());
      const auto global = global_indices_[i];
      const auto vector_size = vector_.size();
      assert(global < vector_size);
      value_cache_[i] = vector_[global];
    }
  }

  //! this needs to exist for communication to allow gather/scatter to define for codim non-zero. even if never called
  template <class OtherEntities>
  void bind(const OtherEntities&)
  {
    DUNE_THROW(NotImplemented, "");
    resize(0);
  }

  void commit()
  {
    assert(value_cache_.size() == global_indices_.size());
    for (auto i : XT::Common::value_range(value_cache_.size())) {
      const auto global = global_indices_[i];
      vector_[global] = value_cache_[i];
    }
  }

  ScalarType& operator[](const size_t ii)
  {
    return value_cache_[ii];
  }

  const ScalarType& operator[](const size_t ii) const
  {
    return value_cache_[ii];
  }

  size_t size() const
  {
    assert(value_cache_.size() == global_indices_.size());
    return value_cache_.size();
  }

private:
  VectorInterface& vector_;
  const SpaceType& space_;
  Dune::DynamicVector<size_t> global_indices_;
  //! must use something that doesn't have specialized data storage for bool
  boost::container::vector<ScalarType> value_cache_;
  const Descriptor& descriptor_;
};

} // namespace GDT
} // namespace Dune

#endif // DUNE_GDT_LOCALVIEW_HH
<commit_msg>[spaces.parallel] fixes localview dof index caching<commit_after>//
// Created by r_milk01 on 29.03.17.
//

#ifndef DUNE_GDT_LOCALVIEW_HH
#define DUNE_GDT_LOCALVIEW_HH

#include <dune/xt/common/ranges.hh>
#include <dune/xt/grid/entity.hh>
#include <dune/xt/la/container/vector-interface.hh>
#include <dune/gdt/spaces/mapper/interfaces.hh>

#include <boost/container/vector.hpp>

namespace Dune {
namespace GDT {

template <class VectorTraits, class ScalarType, class SpaceType, class Descriptor>
class LocalView
{
  using VectorInterface = XT::LA::VectorInterface<VectorTraits, ScalarType>;
  using EntityType = XT::Grid::extract_entity_t<typename SpaceType::GridViewType>;

private:
  void resize(size_t size)
  {
    global_indices_.resize(size);
    value_cache_.resize(size);
  }

public:
  using value_type = ScalarType;

  LocalView(VectorInterface& vector, const SpaceType& space, const Descriptor& descriptor)
    : vector_(vector)
    , space_(space)
    , global_indices_(0)
    , value_cache_(0)
    , descriptor_(descriptor)
  {
  }

  void bind(const EntityType& entity)
  {
    const size_t size{descriptor_.size(space_, entity)};
    resize(size);
    space_.mapper().globalIndices(entity, global_indices_);
    for (auto i : XT::Common::value_range(size)) {
      assert(size == global_indices_.size());
      const auto global = global_indices_[i];
      const auto vector_size = vector_.size();
      assert(global < vector_size);
      value_cache_[i] = vector_[global];
    }
  }

  //! this needs to exist for communication to allow gather/scatter to define for codim non-zero. even if never called
  template <class OtherEntities>
  void bind(const OtherEntities&)
  {
    DUNE_THROW(NotImplemented, "");
    resize(0);
  }

  void commit()
  {
    assert(value_cache_.size() == global_indices_.size());
    for (auto i : XT::Common::value_range(value_cache_.size())) {
      const auto global = global_indices_[i];
      vector_[global] = value_cache_[i];
    }
  }

  ScalarType& operator[](const size_t ii)
  {
    return value_cache_[ii];
  }

  const ScalarType& operator[](const size_t ii) const
  {
    return value_cache_[ii];
  }

  size_t size() const
  {
    assert(value_cache_.size() == global_indices_.size());
    return value_cache_.size();
  }

private:
  VectorInterface& vector_;
  const SpaceType& space_;
  Dune::DynamicVector<size_t> global_indices_;
  //! must use something that doesn't have specialized data storage for bool
  boost::container::vector<ScalarType> value_cache_;
  const Descriptor& descriptor_;
};

} // namespace GDT
} // namespace Dune

#endif // DUNE_GDT_LOCALVIEW_HH
<|endoftext|>


<commit_before>#include "stdafx.h"
#include <dukat/json.h>
#include <dukat/log.h>
#include <json/json.h>
#include <dukat/settings.h>

namespace dukat
{
	Json::Value load_json(const std::string& filename)
	{
		Json::Value root;
		load_json(filename, root);
		return root;
	}

	void load_json(const std::string& filename, Json::Value& root)
	{
		Json::Reader reader;
		log->debug("Loading: {}", filename);
		std::fstream fs(filename, std::fstream::in);
		if (!reader.parse(fs, root))
		{
			log->warn("Failed to parse JSON: {}", reader.getFormattedErrorMessages());
			throw std::runtime_error("Failed to parse JSON.");
		}
	}

	void merge_json_subtree(Json::Value& base, const Json::Value& patch)
	{
		for (auto p : patch.getMemberNames())
		{
			auto& dest = base[p];
			const auto& src = patch[p];
			if (src.isObject() && dest.isObject())
			{
				merge_json_subtree(dest, src);
			}
			else if (src.isArray() && dest.isArray())
			{
				assert(src.size() == dest.size());
				for (auto i = 0u; i < src.size(); i++)
				{
					if (src[i].isObject())
						merge_json_subtree(dest[i], src[i]);
					else
						dest[i] = src[i];
				}
			}
			else // primitive
			{
				dest = src;
			}
		}
	}

	Json::Value merge_json(Json::Value base, const Json::Value& patch)
	{
		merge_json_subtree(base, patch);
		return base;
	}

	void save_json(const std::string& filename, const Json::Value& root)
	{
		log->debug("Saving: {}", filename);
		std::fstream fs(filename, std::fstream::out);
		if (!fs)
			throw std::runtime_error("Failed to write JSON.");

		Json::StyledStreamWriter writer;
		writer.write(fs, root);
		fs.close();
	}

	void save_settings(const Settings& settings, const std::string& filename)
	{
		log->info("Saving settings to: {}", filename);
		Json::Value root;
		for (const auto& it : settings.map)
		{
			Json::Value* cur = &root;
			auto from = 0u;
			auto to = it.first.find('.');
			while (to != std::string::npos)
			{
				cur = &(*cur)[it.first.substr(from, to - from)];
				from = to + 1;
				to = it.first.find('.', from);
			}
			(*cur)[it.first.substr(from)] = it.second;
		}
		save_json(filename, root);
	}

	void load_settings_from_json(const Json::Value& node, const std::string prefix, std::map<std::string, std::string>& map)
	{
		if (node.isObject())
		{
			for (const auto& key : node.getMemberNames())
				load_settings_from_json(node[key], (prefix.length() ? prefix + "." : "") + key, map);
		}
		else if (node.isArray())
		{
			auto i = 0;
			for (const auto& val : node)
				load_settings_from_json(val, (prefix.length() ? prefix + "." : "") + std::to_string(i++), map);
		}
		else
		{
			map[prefix] = node.asString();
		}
	}

	void load_settings(const std::string& filename, Settings& settings)
	{
		log->info("Loading settings from: {}", filename);
		const auto root = load_json(filename);
		load_settings_from_json(root, "", settings.map);
	}
}<commit_msg>Use dense JSON format in release mode<commit_after>#include "stdafx.h"
#include <dukat/json.h>
#include <dukat/log.h>
#include <json/json.h>
#include <dukat/settings.h>

namespace dukat
{
	Json::Value load_json(const std::string& filename)
	{
		Json::Value root;
		load_json(filename, root);
		return root;
	}

	void load_json(const std::string& filename, Json::Value& root)
	{
		Json::Reader reader;
		log->debug("Loading: {}", filename);
		std::fstream fs(filename, std::fstream::in);
		if (!reader.parse(fs, root))
		{
			log->warn("Failed to parse JSON: {}", reader.getFormattedErrorMessages());
			throw std::runtime_error("Failed to parse JSON.");
		}
	}

	void merge_json_subtree(Json::Value& base, const Json::Value& patch)
	{
		for (auto p : patch.getMemberNames())
		{
			auto& dest = base[p];
			const auto& src = patch[p];
			if (src.isObject() && dest.isObject())
			{
				merge_json_subtree(dest, src);
			}
			else if (src.isArray() && dest.isArray())
			{
				assert(src.size() == dest.size());
				for (auto i = 0u; i < src.size(); i++)
				{
					if (src[i].isObject())
						merge_json_subtree(dest[i], src[i]);
					else
						dest[i] = src[i];
				}
			}
			else // primitive
			{
				dest = src;
			}
		}
	}

	Json::Value merge_json(Json::Value base, const Json::Value& patch)
	{
		merge_json_subtree(base, patch);
		return base;
	}

	void save_json(const std::string& filename, const Json::Value& root)
	{
		log->debug("Saving: {}", filename);
		std::fstream fs(filename, std::fstream::out);
		if (!fs)
			throw std::runtime_error("Failed to write JSON.");

		Json::StreamWriterBuilder builder;
#ifdef _DEBUG
		builder.settings_["indentation"] = "";
#endif
		std::unique_ptr<Json::StreamWriter> writer(builder.newStreamWriter());
		writer->write(root, &fs);
		fs.close();
	}

	void save_settings(const Settings& settings, const std::string& filename)
	{
		log->info("Saving settings to: {}", filename);
		Json::Value root;
		for (const auto& it : settings.map)
		{
			Json::Value* cur = &root;
			auto from = 0u;
			auto to = it.first.find('.');
			while (to != std::string::npos)
			{
				cur = &(*cur)[it.first.substr(from, to - from)];
				from = to + 1;
				to = it.first.find('.', from);
			}
			(*cur)[it.first.substr(from)] = it.second;
		}
		save_json(filename, root);
	}

	void load_settings_from_json(const Json::Value& node, const std::string prefix, std::map<std::string, std::string>& map)
	{
		if (node.isObject())
		{
			for (const auto& key : node.getMemberNames())
				load_settings_from_json(node[key], (prefix.length() ? prefix + "." : "") + key, map);
		}
		else if (node.isArray())
		{
			auto i = 0;
			for (const auto& val : node)
				load_settings_from_json(val, (prefix.length() ? prefix + "." : "") + std::to_string(i++), map);
		}
		else
		{
			map[prefix] = node.asString();
		}
	}

	void load_settings(const std::string& filename, Settings& settings)
	{
		log->info("Loading settings from: {}", filename);
		const auto root = load_json(filename);
		load_settings_from_json(root, "", settings.map);
	}
}<|endoftext|>


<commit_before>#include <node.h>
#include <node_buffer.h>
#include <nan.h>
#include <string.h>
#include <stdlib.h>

#ifdef _WIN32
# include <io.h>
# include <fcntl.h>
# include <wchar.h>
#endif

#include "magic.h"

using namespace node;
using namespace v8;

struct Baton {
  uv_work_t request;
  Nan::Callback* callback;

  char* data;
  uint32_t dataLen;
  bool dataIsPath;

  // libmagic info
  const char* path;
  int flags;

  bool error;
  bool free_error;
  char* error_message;

  const char* result;
};

static Nan::Persistent<Function> constructor;
static const char* fallbackPath;

class Magic : public ObjectWrap {
  public:
    const char* mpath;
    int mflags;

    Magic(const char* path, int flags) {
      if (path != NULL) {
        /* Windows blows up trying to look up the path '(null)' returned by
           magic_getpath() */
        if (strncmp(path, "(null)", 6) == 0)
          path = NULL;
      }
      mpath = (path == NULL ? strdup(fallbackPath) : path);
      mflags = flags;
    }
    ~Magic() {
      if (mpath != NULL) {
        free((void*)mpath);
        mpath = NULL;
      }
    }

    static void New(const Nan::FunctionCallbackInfo<v8::Value>& args) {
      Nan::HandleScope();
#ifndef _WIN32
      int magic_flags = MAGIC_SYMLINK;
#else
      int magic_flags = MAGIC_NONE;
#endif
      char* path = NULL;
      bool use_bundled = true;

      if (!args.IsConstructCall())
        return Nan::ThrowTypeError("Use `new` to create instances of this object.");

      if (args.Length() > 1) {
        if (args[1]->IsInt32())
          magic_flags = args[1]->Int32Value();
        else
          return Nan::ThrowTypeError("Second argument must be an integer");
      }

      if (args.Length() > 0) {
        if (args[0]->IsString()) {
          use_bundled = false;
          String::Utf8Value str(args[0]->ToString());
          path = strdup((const char*)(*str));
        } else if (args[0]->IsInt32())
          magic_flags = args[0]->Int32Value();
        else if (args[0]->IsBoolean() && !args[0]->BooleanValue()) {
          use_bundled = false;
          path = strdup(magic_getpath(NULL, 0/*FILE_LOAD*/));
        } else
          return Nan::ThrowTypeError("First argument must be a string or integer");
      }

      Magic* obj = new Magic((use_bundled ? NULL : path), magic_flags);
      obj->Wrap(args.This());
      obj->Ref();

      return args.GetReturnValue().Set(args.This());
    }

    static void DetectFile(const Nan::FunctionCallbackInfo<v8::Value>& args) {
      Nan::HandleScope();
      Magic* obj = ObjectWrap::Unwrap<Magic>(args.This());

      if (!args[0]->IsString())
        return Nan::ThrowTypeError("First argument must be a string");
      if (!args[1]->IsFunction())
        return Nan::ThrowTypeError("Second argument must be a callback function");

      Local<Function> callback = Local<Function>::Cast(args[1]);

      String::Utf8Value str(args[0]->ToString());

      Baton* baton = new Baton();
      baton->error = false;
      baton->free_error = true;
      baton->error_message = NULL;
      baton->request.data = baton;
      baton->callback = new Nan::Callback(callback);
      baton->data = strdup((const char*)*str);
      baton->dataIsPath = true;
      baton->path = obj->mpath;
      baton->flags = obj->mflags;
      baton->result = NULL;

      int status = uv_queue_work(uv_default_loop(),
                                 &baton->request,
                                 Magic::DetectWork,
                                 (uv_after_work_cb)Magic::DetectAfter);
      assert(status == 0);

      args.GetReturnValue().Set(Nan::Undefined());
    }

    static void Detect(const Nan::FunctionCallbackInfo<v8::Value>& args) {
      Nan::HandleScope();
      Magic* obj = ObjectWrap::Unwrap<Magic>(args.This());

      if (args.Length() < 2)
        return Nan::ThrowTypeError("Expecting 2 arguments");
      if (!Buffer::HasInstance(args[0]))
        return Nan::ThrowTypeError("First argument must be a Buffer");
      if (!args[1]->IsFunction())
        return Nan::ThrowTypeError("Second argument must be a callback function");

      Local<Function> callback = Local<Function>::Cast(args[1]);
#if NODE_MAJOR_VERSION == 0 && NODE_MINOR_VERSION < 10
      Local<Object> buffer_obj = args[0]->ToObject();
#else
      Local<Value> buffer_obj = args[0];
#endif

      Baton* baton = new Baton();
      baton->error = false;
      baton->free_error = true;
      baton->error_message = NULL;
      baton->request.data = baton;
      baton->callback = new Nan::Callback(callback);
      baton->data = Buffer::Data(buffer_obj);
      baton->dataLen = Buffer::Length(buffer_obj);
      baton->dataIsPath = false;
      baton->path = obj->mpath;
      baton->flags = obj->mflags;
      baton->result = NULL;

      int status = uv_queue_work(uv_default_loop(),
                                 &baton->request,
                                 Magic::DetectWork,
                                 (uv_after_work_cb)Magic::DetectAfter);
      assert(status == 0);

      return args.GetReturnValue().Set(args.This());
    }

    static void DetectWork(uv_work_t* req) {
      Baton* baton = static_cast<Baton*>(req->data);
      const char* result;
      struct magic_set *magic = magic_open(baton->flags
                                           | MAGIC_NO_CHECK_COMPRESS
                                           | MAGIC_ERROR);

      if (magic == NULL) {
#if NODE_MODULE_VERSION <= 0x000B
        baton->error_message = strdup(uv_strerror(
                                        uv_last_error(uv_default_loop())));
#else
// XXX libuv 1.x currently has no public cross-platform function to convert an
//     OS-specific error number to a libuv error number. `-errno` should work
//     for *nix, but just passing GetLastError() on Windows will not work ...
# ifdef _MSC_VER
        baton->error_message = strdup(uv_strerror(GetLastError()));
# else
        baton->error_message = strdup(uv_strerror(-errno));
# endif
#endif
      } else if (magic_load(magic, baton->path) == -1
                 && magic_load(magic, fallbackPath) == -1) {
        baton->error_message = strdup(magic_error(magic));
        magic_close(magic);
        magic = NULL;
      }

      if (magic == NULL) {
        if (baton->error_message)
          baton->error = true;
        return;
      }

      if (baton->dataIsPath) {
#ifdef _WIN32
        // open the file manually to help cope with potential unicode characters
        // in filename
        const char* ofn = baton->data;
        int flags = O_RDONLY|O_BINARY;
        int fd = -1;
        int wLen;
        wLen = MultiByteToWideChar(CP_UTF8, 0, ofn, -1, NULL, 0);
        if (wLen > 0) {
          wchar_t* wfn = (wchar_t*)malloc(wLen * sizeof(wchar_t));
          if (wfn) {
            int wret = MultiByteToWideChar(CP_UTF8, 0, ofn, -1, wfn, wLen);
            if (wret != 0)
              fd = _wopen(wfn, flags);
            free(wfn);
            wfn = NULL;
          }
        }
        if (fd == -1) {
          baton->error = true;
          baton->free_error = false;
          baton->error_message = "Error while opening file";
          magic_close(magic);
          return;
        }
        result = magic_descriptor(magic, fd);
        _close(fd);
#else
        result = magic_file(magic, baton->data);
#endif
      } else
        result = magic_buffer(magic, (const void*)baton->data, baton->dataLen);

      if (result == NULL) {
        const char* error = magic_error(magic);
        if (error) {
          baton->error = true;
          baton->error_message = strdup(error);
        }
      } else
        baton->result = strdup(result);

      magic_close(magic);
    }

    static void DetectAfter(uv_work_t* req) {
      Nan::HandleScope scope;
      Baton* baton = static_cast<Baton*>(req->data);

      if (baton->error) {
        Local<Value> err = Nan::Error(baton->error_message);

        if (baton->free_error)
          free(baton->error_message);

        Local<Value> argv[1] = { err };
        baton->callback->Call(1, argv);
      } else {
        Local<Value> argv[2] = {
          Nan::Null(),
          Local<Value>(baton->result
                       ? Nan::New<String>(baton->result).ToLocalChecked()
                       : Nan::New<String>().ToLocalChecked())
        };

        if (baton->result)
          free((void*)baton->result);

        baton->callback->Call(2, argv);
      }

      if (baton->dataIsPath)
        free(baton->data);
      delete baton->callback;
      delete baton;
    }

    static void SetFallback(const Nan::FunctionCallbackInfo<v8::Value>& args) {

      if (fallbackPath)
        free((void*)fallbackPath);

      if (args.Length() > 0 && args[0]->IsString()
          && args[0]->ToString()->Length() > 0) {
        String::Utf8Value str(args[0]->ToString());
        fallbackPath = strdup((const char*)(*str));
      } else
        fallbackPath = NULL;

      return args.GetReturnValue().Set(args.This());
    }

    static void Initialize(Handle<Object> target) {

      Local<FunctionTemplate> tpl = Nan::New<FunctionTemplate>(New);

      tpl->InstanceTemplate()->SetInternalFieldCount(1);
      tpl->SetClassName(Nan::New<String>("Magic").ToLocalChecked());
      Nan::SetPrototypeMethod(tpl, "detectFile", DetectFile);
      Nan::SetPrototypeMethod(tpl, "detect", Detect);

      constructor.Reset(tpl->GetFunction());
      target->Set(Nan::New<String>("setFallback").ToLocalChecked(),
                  Nan::New<FunctionTemplate>(SetFallback)->GetFunction());

      target->Set(Nan::New<String>("Magic").ToLocalChecked(), tpl->GetFunction());
    }
};

extern "C" {
  void init(Handle<Object> target) {
    Nan::HandleScope();
    Magic::Initialize(target);
  }

  NODE_MODULE(magic, init);
}
<commit_msg>src: switch from deprecated API function on Windows<commit_after>#include <node.h>
#include <node_buffer.h>
#include <nan.h>
#include <string.h>
#include <stdlib.h>

#ifdef _WIN32
# include <io.h>
# include <fcntl.h>
# include <wchar.h>
#endif

#include "magic.h"

using namespace node;
using namespace v8;

struct Baton {
  uv_work_t request;
  Nan::Callback* callback;

  char* data;
  uint32_t dataLen;
  bool dataIsPath;

  // libmagic info
  const char* path;
  int flags;

  bool error;
  bool free_error;
  char* error_message;

  const char* result;
};

static Nan::Persistent<Function> constructor;
static const char* fallbackPath;

class Magic : public ObjectWrap {
  public:
    const char* mpath;
    int mflags;

    Magic(const char* path, int flags) {
      if (path != NULL) {
        /* Windows blows up trying to look up the path '(null)' returned by
           magic_getpath() */
        if (strncmp(path, "(null)", 6) == 0)
          path = NULL;
      }
      mpath = (path == NULL ? strdup(fallbackPath) : path);
      mflags = flags;
    }
    ~Magic() {
      if (mpath != NULL) {
        free((void*)mpath);
        mpath = NULL;
      }
    }

    static void New(const Nan::FunctionCallbackInfo<v8::Value>& args) {
      Nan::HandleScope();
#ifndef _WIN32
      int magic_flags = MAGIC_SYMLINK;
#else
      int magic_flags = MAGIC_NONE;
#endif
      char* path = NULL;
      bool use_bundled = true;

      if (!args.IsConstructCall())
        return Nan::ThrowTypeError("Use `new` to create instances of this object.");

      if (args.Length() > 1) {
        if (args[1]->IsInt32())
          magic_flags = args[1]->Int32Value();
        else
          return Nan::ThrowTypeError("Second argument must be an integer");
      }

      if (args.Length() > 0) {
        if (args[0]->IsString()) {
          use_bundled = false;
          String::Utf8Value str(args[0]->ToString());
          path = strdup((const char*)(*str));
        } else if (args[0]->IsInt32())
          magic_flags = args[0]->Int32Value();
        else if (args[0]->IsBoolean() && !args[0]->BooleanValue()) {
          use_bundled = false;
          path = strdup(magic_getpath(NULL, 0/*FILE_LOAD*/));
        } else
          return Nan::ThrowTypeError("First argument must be a string or integer");
      }

      Magic* obj = new Magic((use_bundled ? NULL : path), magic_flags);
      obj->Wrap(args.This());
      obj->Ref();

      return args.GetReturnValue().Set(args.This());
    }

    static void DetectFile(const Nan::FunctionCallbackInfo<v8::Value>& args) {
      Nan::HandleScope();
      Magic* obj = ObjectWrap::Unwrap<Magic>(args.This());

      if (!args[0]->IsString())
        return Nan::ThrowTypeError("First argument must be a string");
      if (!args[1]->IsFunction())
        return Nan::ThrowTypeError("Second argument must be a callback function");

      Local<Function> callback = Local<Function>::Cast(args[1]);

      String::Utf8Value str(args[0]->ToString());

      Baton* baton = new Baton();
      baton->error = false;
      baton->free_error = true;
      baton->error_message = NULL;
      baton->request.data = baton;
      baton->callback = new Nan::Callback(callback);
      baton->data = strdup((const char*)*str);
      baton->dataIsPath = true;
      baton->path = obj->mpath;
      baton->flags = obj->mflags;
      baton->result = NULL;

      int status = uv_queue_work(uv_default_loop(),
                                 &baton->request,
                                 Magic::DetectWork,
                                 (uv_after_work_cb)Magic::DetectAfter);
      assert(status == 0);

      args.GetReturnValue().Set(Nan::Undefined());
    }

    static void Detect(const Nan::FunctionCallbackInfo<v8::Value>& args) {
      Nan::HandleScope();
      Magic* obj = ObjectWrap::Unwrap<Magic>(args.This());

      if (args.Length() < 2)
        return Nan::ThrowTypeError("Expecting 2 arguments");
      if (!Buffer::HasInstance(args[0]))
        return Nan::ThrowTypeError("First argument must be a Buffer");
      if (!args[1]->IsFunction())
        return Nan::ThrowTypeError("Second argument must be a callback function");

      Local<Function> callback = Local<Function>::Cast(args[1]);
#if NODE_MAJOR_VERSION == 0 && NODE_MINOR_VERSION < 10
      Local<Object> buffer_obj = args[0]->ToObject();
#else
      Local<Value> buffer_obj = args[0];
#endif

      Baton* baton = new Baton();
      baton->error = false;
      baton->free_error = true;
      baton->error_message = NULL;
      baton->request.data = baton;
      baton->callback = new Nan::Callback(callback);
      baton->data = Buffer::Data(buffer_obj);
      baton->dataLen = Buffer::Length(buffer_obj);
      baton->dataIsPath = false;
      baton->path = obj->mpath;
      baton->flags = obj->mflags;
      baton->result = NULL;

      int status = uv_queue_work(uv_default_loop(),
                                 &baton->request,
                                 Magic::DetectWork,
                                 (uv_after_work_cb)Magic::DetectAfter);
      assert(status == 0);

      return args.GetReturnValue().Set(args.This());
    }

    static void DetectWork(uv_work_t* req) {
      Baton* baton = static_cast<Baton*>(req->data);
      const char* result;
      struct magic_set *magic = magic_open(baton->flags
                                           | MAGIC_NO_CHECK_COMPRESS
                                           | MAGIC_ERROR);

      if (magic == NULL) {
#if NODE_MODULE_VERSION <= 0x000B
        baton->error_message = strdup(uv_strerror(
                                        uv_last_error(uv_default_loop())));
#else
// XXX libuv 1.x currently has no public cross-platform function to convert an
//     OS-specific error number to a libuv error number. `-errno` should work
//     for *nix, but just passing GetLastError() on Windows will not work ...
# ifdef _MSC_VER
        baton->error_message = strdup(uv_strerror(GetLastError()));
# else
        baton->error_message = strdup(uv_strerror(-errno));
# endif
#endif
      } else if (magic_load(magic, baton->path) == -1
                 && magic_load(magic, fallbackPath) == -1) {
        baton->error_message = strdup(magic_error(magic));
        magic_close(magic);
        magic = NULL;
      }

      if (magic == NULL) {
        if (baton->error_message)
          baton->error = true;
        return;
      }

      if (baton->dataIsPath) {
#ifdef _WIN32
        // open the file manually to help cope with potential unicode characters
        // in filename
        const char* ofn = baton->data;
        int flags = O_RDONLY|O_BINARY;
        int fd = -1;
        int wLen;
        wLen = MultiByteToWideChar(CP_UTF8, 0, ofn, -1, NULL, 0);
        if (wLen > 0) {
          wchar_t* wfn = (wchar_t*)malloc(wLen * sizeof(wchar_t));
          if (wfn) {
            int wret = MultiByteToWideChar(CP_UTF8, 0, ofn, -1, wfn, wLen);
            if (wret != 0)
              _wsopen_s(&fd, wfn, flags, _SH_DENYNO, _S_IREAD);
            free(wfn);
            wfn = NULL;
          }
        }
        if (fd == -1) {
          baton->error = true;
          baton->free_error = false;
          baton->error_message = "Error while opening file";
          magic_close(magic);
          return;
        }
        result = magic_descriptor(magic, fd);
        _close(fd);
#else
        result = magic_file(magic, baton->data);
#endif
      } else
        result = magic_buffer(magic, (const void*)baton->data, baton->dataLen);

      if (result == NULL) {
        const char* error = magic_error(magic);
        if (error) {
          baton->error = true;
          baton->error_message = strdup(error);
        }
      } else
        baton->result = strdup(result);

      magic_close(magic);
    }

    static void DetectAfter(uv_work_t* req) {
      Nan::HandleScope scope;
      Baton* baton = static_cast<Baton*>(req->data);

      if (baton->error) {
        Local<Value> err = Nan::Error(baton->error_message);

        if (baton->free_error)
          free(baton->error_message);

        Local<Value> argv[1] = { err };
        baton->callback->Call(1, argv);
      } else {
        Local<Value> argv[2] = {
          Nan::Null(),
          Local<Value>(baton->result
                       ? Nan::New<String>(baton->result).ToLocalChecked()
                       : Nan::New<String>().ToLocalChecked())
        };

        if (baton->result)
          free((void*)baton->result);

        baton->callback->Call(2, argv);
      }

      if (baton->dataIsPath)
        free(baton->data);
      delete baton->callback;
      delete baton;
    }

    static void SetFallback(const Nan::FunctionCallbackInfo<v8::Value>& args) {

      if (fallbackPath)
        free((void*)fallbackPath);

      if (args.Length() > 0 && args[0]->IsString()
          && args[0]->ToString()->Length() > 0) {
        String::Utf8Value str(args[0]->ToString());
        fallbackPath = strdup((const char*)(*str));
      } else
        fallbackPath = NULL;

      return args.GetReturnValue().Set(args.This());
    }

    static void Initialize(Handle<Object> target) {

      Local<FunctionTemplate> tpl = Nan::New<FunctionTemplate>(New);

      tpl->InstanceTemplate()->SetInternalFieldCount(1);
      tpl->SetClassName(Nan::New<String>("Magic").ToLocalChecked());
      Nan::SetPrototypeMethod(tpl, "detectFile", DetectFile);
      Nan::SetPrototypeMethod(tpl, "detect", Detect);

      constructor.Reset(tpl->GetFunction());
      target->Set(Nan::New<String>("setFallback").ToLocalChecked(),
                  Nan::New<FunctionTemplate>(SetFallback)->GetFunction());

      target->Set(Nan::New<String>("Magic").ToLocalChecked(), tpl->GetFunction());
    }
};

extern "C" {
  void init(Handle<Object> target) {
    Nan::HandleScope();
    Magic::Initialize(target);
  }

  NODE_MODULE(magic, init);
}
<|endoftext|>


<commit_before>/*
 * This program is free software; you can redistribute it and/or modify it under
 * the terms of the GNU General Public License as published by the Free Software
 * Foundation; version 3 of the License.
 *
 * This program is distributed in the hope that it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
 * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
 * details.
 */

#include <QtGui/QApplication>
#include "config.h"
#include "dbmanager.h"
#include "iconmanager.h"
#include "mainwindow.h"
#include "plugins/pluginmanager.h"
#include "sqlhighlighter.h"
#include "tabwidget/abstracttabwidget.h"
#include "widgets/querytextedit.h"

int main(int argc, char *argv[]) {
  QApplication::setApplicationName("dbmaster");
  QApplication::setApplicationVersion("0.8.1");
  QApplication::setOrganizationDomain("dbmaster.org");
  QApplication a(argc, argv);

  QSplashScreen splash(QPixmap(":/img/splash.png"));
  splash.show();

  // Loading translations
  splash.showMessage(QObject::tr("Loading translations..."), Qt::AlignBottom);

  QTranslator translator;
  // getting the current locale
  QString lang = QLocale::system().name();
  QString transdir;
#if defined(Q_WS_X11)
  // for *nix
  transdir = QString(PREFIX).append("/share/dbmaster/tr");
#endif

#if defined(Q_WS_WIN)
  transdir = "share/tr";
#endif

  QString path;
  /* on teste d'abord si le .qm est dans le dossier courant -> alors on est en
   * dev, on le charge, sinon il est dans le répertoire d'installation. */
  path = QDir::currentPath() + QString("/../tr/%1.qm").arg(lang);
  if (!QFile::exists(path))
    path = transdir.append("/%1.qm").arg(lang);
  translator.load(path);
  a.installTranslator(&translator);

  QTranslator qtTranslator;
  qtTranslator.load("qt_" + lang,
#if defined (Q_WS_X11)
                    QLibraryInfo::location(QLibraryInfo::TranslationsPath));
#endif
#if defined (Q_WS_WIN)
                    QDir::currentPath());
#endif
  a.installTranslator(&qtTranslator);

  // Ajout des plugins
  splash.showMessage(QObject::tr("Loading plugins..."), Qt::AlignBottom);
  PluginManager::init();

  splash.showMessage(QObject::tr("Initialization..."), Qt::AlignBottom);

  IconManager::init();
  DbManager::init();
  Config::init();
  QueryTextEdit::reloadCompleter();

  MainWindow *w = new MainWindow();
  w->show();
  splash.finish(w);

  if (a.arguments().size() >= 2) {
    for (int i=1; i<a.arguments().size(); i++) {
      w->openQuery(a.arguments()[i]);
    }
  }

  return a.exec();
}
<commit_msg>Num version<commit_after>/*
 * This program is free software; you can redistribute it and/or modify it under
 * the terms of the GNU General Public License as published by the Free Software
 * Foundation; version 3 of the License.
 *
 * This program is distributed in the hope that it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
 * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
 * details.
 */

#include <QtGui/QApplication>
#include "config.h"
#include "dbmanager.h"
#include "iconmanager.h"
#include "mainwindow.h"
#include "plugins/pluginmanager.h"
#include "sqlhighlighter.h"
#include "tabwidget/abstracttabwidget.h"
#include "widgets/querytextedit.h"

int main(int argc, char *argv[]) {
  QApplication::setApplicationName("dbmaster");
  QApplication::setApplicationVersion("0.8.2");
  QApplication::setOrganizationDomain("dbmaster.org");
  QApplication a(argc, argv);

  QSplashScreen splash(QPixmap(":/img/splash.png"));
  splash.show();

  // Loading translations
  splash.showMessage(QObject::tr("Loading translations..."), Qt::AlignBottom);

  QTranslator translator;
  // getting the current locale
  QString lang = QLocale::system().name();
  QString transdir;
#if defined(Q_WS_X11)
  // for *nix
  transdir = QString(PREFIX).append("/share/dbmaster/tr");
#endif

#if defined(Q_WS_WIN)
  transdir = "share/tr";
#endif

  QString path;
  /* on teste d'abord si le .qm est dans le dossier courant -> alors on est en
   * dev, on le charge, sinon il est dans le répertoire d'installation. */
  path = QDir::currentPath() + QString("/../tr/%1.qm").arg(lang);
  if (!QFile::exists(path))
    path = transdir.append("/%1.qm").arg(lang);
  translator.load(path);
  a.installTranslator(&translator);

  QTranslator qtTranslator;
  qtTranslator.load("qt_" + lang,
#if defined (Q_WS_X11)
                    QLibraryInfo::location(QLibraryInfo::TranslationsPath));
#endif
#if defined (Q_WS_WIN)
                    QDir::currentPath());
#endif
  a.installTranslator(&qtTranslator);

  // Ajout des plugins
  splash.showMessage(QObject::tr("Loading plugins..."), Qt::AlignBottom);
  PluginManager::init();

  splash.showMessage(QObject::tr("Initialization..."), Qt::AlignBottom);

  IconManager::init();
  DbManager::init();
  Config::init();
  QueryTextEdit::reloadCompleter();

  MainWindow *w = new MainWindow();
  w->show();
  splash.finish(w);

  if (a.arguments().size() >= 2) {
    for (int i=1; i<a.arguments().size(); i++) {
      w->openQuery(a.arguments()[i]);
    }
  }

  return a.exec();
}
<|endoftext|>


<commit_before>#include "strigihtmlgui.h"
#include "socketclient.h"
#include <unistd.h>
#include <sys/types.h>
#include <dirent.h>
using namespace std;
using namespace jstreams;

class StrigiHtmlGui::Private {
private:
    HtmlHelper* h;
public:
    SocketClient strigi;

    Private(HtmlHelper* h);
    void printSearchResult(ostream& out,
        const jstreams::IndexedDocument& doc);
    void printSearchResults(ostream& out, const ClientInterface::Hits&);
};

StrigiHtmlGui::StrigiHtmlGui(HtmlHelper* h) : helper(h) {
    p = new Private(helper);
}
StrigiHtmlGui::~StrigiHtmlGui() {
    delete p;
}
void
StrigiHtmlGui::printHeader(ostream& out, const string& path,
        const map<std::string, std::string> &params) {
    out << "<?xml version='1.0' encoding='utf-8'?>\n"
        << "<!DOCTYPE html PUBLIC '-//W3C//DTD XHTML 1.0 Strict//EN' "
        << "'http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd'>\n"
        << ""
        << "<meta http-equiv='Content-Type' "
        << "content='text/html; charset=utf-8' />";
    out << "<title>Strigi Desktop Search</title>";
    out << "";
    out << "
Strigi Desktop Search
";
    printMenu(out, path, params);
}
void
StrigiHtmlGui::printFooter(ostream& out, const string& path,
        const map<std::string, std::string> &params) {
    out << "";
}
void
StrigiHtmlGui::printHelp(ostream& out, const string& path,
        const map<std::string, std::string> &params) {
    out << "Help!";
}
void
StrigiHtmlGui::printAbout(ostream& out, const string& path,
        const map<std::string, std::string> &params) {
    out << "About";
}
void
StrigiHtmlGui::printConfig(ostream& out, const string& path,
        const map<std::string, std::string> &params) {
    printIndexedDirs(out, path, params);
}
void
startDaemon() {
    if (fork()) {
        char * const args[] = {"strigidaemon", "clucene", 0};
        execvp("/home/oever/testinstall/bin/strigidaemon", args);
    }
}
void
StrigiHtmlGui::printStatus(ostream& out, const string& path,
        const map<std::string, std::string> &params) {
    map<string, string> status;
    if (path == "status/start") {
        status = p->strigi.getStatus();
        if (status.size() == 0) {
            startDaemon();
            int n = 0;
            while (n < 5 && status.size() == 0) {
                sleep(1);
                status = p->strigi.getStatus();
                n++;
            }
        }
    } else if (path == "status/stop") {
        p->strigi.stopDaemon();
    } else if (path == "status/stopindexing") {
        p->strigi.stopIndexing();
        status = p->strigi.getStatus();
    } else if (path == "status/startindexing") {
        p->strigi.startIndexing();
        status = p->strigi.getStatus();
    } else {
        status = p->strigi.getStatus();
    }
    if (status.size() == 0) {
        out << "
Start daemon
";
    } else {
        map<string, string>::const_iterator i;
        out << "
";
        for (i = status.begin(); i != status.end(); ++i) {
            out << "
" <first << "	" <second
                << "
";
        }
        out << "
";
        out << "
Stop daemon
";
        if (status["Status"] == "indexing") {
            out << "
Stop indexing
";
        } else {
            out << "
Start indexing
";
        }
    }
    // automatically reload the status page
    out << "\n";
}
void
StrigiHtmlGui::printSearch(ostream& out, const string& path,
        const map<std::string, std::string> &params) {
    string query;
    map<string, string>::const_iterator i = params.find("q");
    if (i != params.end()) query = i->second;
    int max = 10;
    i = params.find("m");
    if (i != params.end()) {
        max = atoi(i->second.c_str());
    }
    if (max == 0) max = 10;
    int off = 0;
    i = params.find("o");
    if (i != params.end()) {
        off = atoi(i->second.c_str());
    }
    string selectedtab;
    i = params.find("t");
    if (i != params.end()) {
        selectedtab = i->second;
    }

    // print tabs
    int count = p->strigi.countHits(query);
    string activetab;
    string activequery = query;
    map<string, int> hitcounts;
    if (count) {
        map<string, string> tabs;
        bool doother = true;
        tabs["Images"] = "mimetype:image*";
        tabs["Mail"] = "mimetype:message/*";
        tabs["Web"] = "mimetype:text/html";
        tabs["Text"] = "mimetype:text/*";
        map<string, string>::const_iterator j;
        string otherq = query;
        for (j = tabs.begin(); j != tabs.end(); ++j) {
            string q = query+" "+j->second;
            int c = p->strigi.countHits(q);
            if (c > 0) {
                hitcounts[j->first] = c;
                doother &= c < count;
		otherq += " -" + j->second;
                if (j->first == selectedtab || activetab.size() == 0) {
                    activetab = j->first;
                    activequery = q;
                }
            }
        }
        doother &= hitcounts.size() > 0;
        int othercount = 0;
        if (doother) {
            othercount = p->strigi.countHits(otherq);
            if (othercount > 0) {
                hitcounts["Other"] = othercount;
                if (selectedtab == "Other") {
                    activetab = selectedtab;
                    activequery = otherq;
                }
            }
        }
    }

    // print gui
    out << "
";
    out << "<form method='get'>";
    out << "<input type='text' name='q' value='" << query << "'/>";
    out << "<input type='hidden' name='o' value='" << off << "'/>";
    out << "<input type='hidden' name='m' value='" << max << "'/>";
    out << "<input type='hidden' name='t' value='" << activetab << "'/>";
    out << "<input type='submit' value='search'/>";
    if (hitcounts.size() == 0 && count > 0) {
        out << " Found " << count << " results.";
    } else {
        map<string, int>::const_iterator l;
        for (l = hitcounts.begin(); l != hitcounts.end(); ++l) {
            if (l->first == activetab) {
                out << " <a class='activetab' ";
            } else {
                out << " <a class='tab' ";
            }
            out << "href='?q=" << query << "&t=" << l->first << "'>"
                << l->first << " (" << l->second << ")" << "";
        }
    }
    out << "</form>
\n";

    const ClientInterface::Hits hits = p->strigi.getHits(activequery, max, off);
    p->printSearchResults(out, hits);
}
void
StrigiHtmlGui::printMenu(ostream& out, const std::string& path,
        const map<std::string, std::string> &params) {
    out << "
" << endl;
    out << "search " << endl;
    out << "status " << endl;
    out << "preferences " << endl;
    out << "help " << endl;
    out << "about " << endl;
    out << "
" << endl;
}
void
StrigiHtmlGui::printIndexedDirs(ostream& out, const std::string& path,
        const map<std::string, std::string> &params) {
    set<string> dirs = p->strigi.getIndexedDirectories();
    map<string,string>::const_iterator i = params.find("adddir");
    if (i != params.end()) {
        DIR* dir = opendir(i->second.c_str());
        if (dir) {
            dirs.insert(i->second);
            closedir(dir);
            p->strigi.setIndexedDirectories(dirs);
            out << "
Directory added. Don't forget to start indexing.
";
        }
    }
    i = params.find("deldir");
    if (i != params.end()) {
        uint oldsize = dirs.size();
        dirs.insert(i->second);
        if (dirs.size() != oldsize) {
            p->strigi.setIndexedDirectories(dirs);
        }
    }

    out << "
";
    set<string>::const_iterator j;
    for (j = dirs.begin(); j != dirs.end(); ++j) {
        out << "
<form method='get'>"
            "<input type='hidden' name='deldir' value='" << *j << "'/>"
            "<input type='submit' value='delete directory'/></form>	"
            << *j << "
";
    }
    out << "<form>
<input type='submit' value='add directory'/>	"
        "<input name='adddir' type='file'/>
</form>";
    out << "
";
}
void
StrigiHtmlGui::printPage(ostream& out, const string& path,
        const map<std::string, std::string> &params) {
    printHeader(out, path, params);

    bool running = p->strigi.getStatus().size() > 0;
    if (strncmp(path.c_str(), "help", 4) == 0) {
        printHelp(out, path, params);
    } else if (strncmp(path.c_str(), "about", 5) == 0) {
        printAbout(out, path, params);
    } else if (running && strncmp(path.c_str(), "config", 6) == 0) {
        printConfig(out, path, params);
    } else if (strncmp(path.c_str(), "status", 6) == 0) {
        printStatus(out, path, params);
    } else if (running) {
        printSearch(out, path, params);
    } else {
        printStatus(out, path, params);
    }

    printFooter(out, path, params);
}
StrigiHtmlGui::Private::Private(HtmlHelper* helper) :h(helper) {
    string homedir = getenv("HOME");
    strigi.setSocketName(homedir+"/.strigi/socket");
}
void
StrigiHtmlGui::Private::printSearchResult(ostream& out,
        const jstreams::IndexedDocument& doc) {
    string link, icon, name, folder;
    link = h->mapLinkUrl(doc.uri);
    icon = "mapMimetypeIcon(doc.uri, doc.mimetype);
    icon += "'/>";
    map<string, string>::const_iterator t = doc.properties.find("title");
    size_t l = doc.uri.rfind('/');
    if (t != doc.properties.end()) {
        name = t->second.c_str();
    } else if (l != string::npos) {
        name = doc.uri.substr(l+1);
    } else {
        name = doc.uri;
    }
    if (l != string::npos) {
        folder = doc.uri.substr(0, l);
    }
    out << "
" << icon << "
<a href='" << link << "'>";
    out << name << "

score: ";
    out << doc.score << ", mime-type: " << doc.mimetype.c_str() << ", size: ";
    out << doc.size << ", last modified: " << h->formatDate(doc.mtime);
    string fragment = h->escapeString(doc.fragment.substr(0,100));
    out << "
" << fragment << "

";
    map<string, string>::const_iterator j;
    for (j = doc.properties.begin(); j != doc.properties.end(); ++j) {
        out << "
" << j->first << ":	" << j->second.c_str()
            << "
";
    }
    out << "

";
}
void
StrigiHtmlGui::Private::printSearchResults(ostream& out,
        const ClientInterface::Hits& hits) {
    vector<jstreams::IndexedDocument>::const_iterator i;
    for (i = hits.hits.begin(); i != hits.hits.end(); ++i) {
        printSearchResult(out, *i);
    }
}
<commit_msg>Two small bugfixes.<commit_after>#include "strigihtmlgui.h"
#include "socketclient.h"
#include <unistd.h>
#include <sys/types.h>
#include <dirent.h>
using namespace std;
using namespace jstreams;

class StrigiHtmlGui::Private {
private:
    HtmlHelper* h;
public:
    SocketClient strigi;

    Private(HtmlHelper* h);
    void printSearchResult(ostream& out,
        const jstreams::IndexedDocument& doc);
    void printSearchResults(ostream& out, const ClientInterface::Hits&);
};

StrigiHtmlGui::StrigiHtmlGui(HtmlHelper* h) : helper(h) {
    p = new Private(helper);
}
StrigiHtmlGui::~StrigiHtmlGui() {
    delete p;
}
void
StrigiHtmlGui::printHeader(ostream& out, const string& path,
        const map<std::string, std::string> &params) {
    out << "<?xml version='1.0' encoding='utf-8'?>\n"
        << "<!DOCTYPE html PUBLIC '-//W3C//DTD XHTML 1.0 Strict//EN' "
        << "'http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd'>\n"
        << ""
        << "<meta http-equiv='Content-Type' "
        << "content='text/html; charset=utf-8' />";
    out << "<title>Strigi Desktop Search</title>";
    out << "";
    out << "
Strigi Desktop Search
";
    printMenu(out, path, params);
}
void
StrigiHtmlGui::printFooter(ostream& out, const string& path,
        const map<std::string, std::string> &params) {
    out << "";
}
void
StrigiHtmlGui::printHelp(ostream& out, const string& path,
        const map<std::string, std::string> &params) {
    out << "Help!";
}
void
StrigiHtmlGui::printAbout(ostream& out, const string& path,
        const map<std::string, std::string> &params) {
    out << "About";
}
void
StrigiHtmlGui::printConfig(ostream& out, const string& path,
        const map<std::string, std::string> &params) {
    printIndexedDirs(out, path, params);
}
void
startDaemon() {
    if (fork()) {
        char * const args[] = {"strigidaemon", "clucene", 0};
        execvp("/home/oever/testinstall/bin/strigidaemon", args);
    }
}
void
StrigiHtmlGui::printStatus(ostream& out, const string& path,
        const map<std::string, std::string> &params) {
    map<string, string> status;
    if (path == "status/start") {
        status = p->strigi.getStatus();
        if (status.size() == 0) {
            startDaemon();
            int n = 0;
            while (n < 5 && status.size() == 0) {
                sleep(1);
                status = p->strigi.getStatus();
                n++;
            }
        }
    } else if (path == "status/stop") {
        p->strigi.stopDaemon();
    } else if (path == "status/stopindexing") {
        p->strigi.stopIndexing();
        status = p->strigi.getStatus();
    } else if (path == "status/startindexing") {
        p->strigi.startIndexing();
        status = p->strigi.getStatus();
    } else {
        status = p->strigi.getStatus();
    }
    if (status.size() == 0) {
        out << "
Start daemon
";
    } else {
        map<string, string>::const_iterator i;
        out << "
";
        for (i = status.begin(); i != status.end(); ++i) {
            out << "
" <first << "	" <second
                << "
";
        }
        out << "
";
        out << "
Stop daemon
";
        if (status["Status"] == "indexing") {
            out << "
Stop indexing
";
        } else {
            out << "
Start indexing
";
        }
    }
    // automatically reload the status page
    out << "\n";
}
void
StrigiHtmlGui::printSearch(ostream& out, const string& path,
        const map<std::string, std::string> &params) {
    string query;
    map<string, string>::const_iterator i = params.find("q");
    if (i != params.end()) query = i->second;
    int max = 10;
    i = params.find("m");
    if (i != params.end()) {
        max = atoi(i->second.c_str());
    }
    if (max == 0) max = 10;
    int off = 0;
    i = params.find("o");
    if (i != params.end()) {
        off = atoi(i->second.c_str());
    }
    string selectedtab;
    i = params.find("t");
    if (i != params.end()) {
        selectedtab = i->second;
    }

    // print tabs
    int count = 0;
    if (query.length()) {
        count = p->strigi.countHits(query);
    }
    string activetab;
    string activequery = query;
    map<string, int> hitcounts;
    if (count) {
        map<string, string> tabs;
        bool doother = true;
        tabs["Images"] = "mimetype:image*";
        tabs["Mail"] = "mimetype:message/*";
        tabs["Web"] = "mimetype:text/html";
        tabs["Text"] = "mimetype:text/*";
        map<string, string>::const_iterator j;
        string otherq = query;
        for (j = tabs.begin(); j != tabs.end(); ++j) {
            string q = query+" "+j->second;
            int c = p->strigi.countHits(q);
            if (c > 0) {
                hitcounts[j->first] = c;
                doother &= c < count;
		otherq += " -" + j->second;
                if (j->first == selectedtab || activetab.size() == 0) {
                    activetab = j->first;
                    activequery = q;
                }
            }
        }
        doother &= hitcounts.size() > 0;
        int othercount = 0;
        if (doother) {
            othercount = p->strigi.countHits(otherq);
            if (othercount > 0) {
                hitcounts["Other"] = othercount;
                if (selectedtab == "Other") {
                    activetab = selectedtab;
                    activequery = otherq;
                }
            }
        }
    }

    // print gui
    out << "
";
    out << "<form method='get'>";
    out << "<input type='text' name='q' value='" << query << "'/>";
    out << "<input type='hidden' name='o' value='" << off << "'/>";
    out << "<input type='hidden' name='m' value='" << max << "'/>";
    out << "<input type='hidden' name='t' value='" << activetab << "'/>";
    out << "<input type='submit' value='search'/>";
    if (hitcounts.size() == 0 && count > 0) {
        out << " Found " << count << " results.";
    } else {
        map<string, int>::const_iterator l;
        for (l = hitcounts.begin(); l != hitcounts.end(); ++l) {
            if (l->first == activetab) {
                out << " <a class='activetab' ";
            } else {
                out << " <a class='tab' ";
            }
            out << "href='?q=" << query << "&t=" << l->first << "'>"
                << l->first << " (" << l->second << ")" << "";
        }
    }
    out << "</form>
\n";

    if (activequery.length()) {
        const ClientInterface::Hits hits = p->strigi.getHits(activequery,
            max, off);
        p->printSearchResults(out, hits);
    }
}
void
StrigiHtmlGui::printMenu(ostream& out, const std::string& path,
        const map<std::string, std::string> &params) {
    out << "
" << endl;
    out << "search " << endl;
    out << "status " << endl;
    out << "preferences " << endl;
    out << "help " << endl;
    out << "about " << endl;
    out << "
" << endl;
}
void
StrigiHtmlGui::printIndexedDirs(ostream& out, const std::string& path,
        const map<std::string, std::string> &params) {
    set<string> dirs = p->strigi.getIndexedDirectories();
    map<string,string>::const_iterator i = params.find("adddir");
    if (i != params.end()) {
        DIR* dir = opendir(i->second.c_str());
        if (dir) {
            dirs.insert(i->second);
            closedir(dir);
            p->strigi.setIndexedDirectories(dirs);
            out << "
Directory added. Don't forget to start indexing.
";
        }
    }
    i = params.find("deldir");
    if (i != params.end()) {
        uint oldsize = dirs.size();
        dirs.erase(i->second);
        if (dirs.size() != oldsize) {
            p->strigi.setIndexedDirectories(dirs);
        }
    }

    out << "
";
    set<string>::const_iterator j;
    for (j = dirs.begin(); j != dirs.end(); ++j) {
        out << "
<form method='get'>"
            "<input type='hidden' name='deldir' value='" << *j << "'/>"
            "<input type='submit' value='delete directory'/></form>	"
            << *j << "
";
    }
    out << "<form>
<input type='submit' value='add directory'/>	"
        "<input name='adddir' type='file'/>
</form>";
    out << "
";
}
void
StrigiHtmlGui::printPage(ostream& out, const string& path,
        const map<std::string, std::string> &params) {
    printHeader(out, path, params);

    bool running = p->strigi.getStatus().size() > 0;
    if (strncmp(path.c_str(), "help", 4) == 0) {
        printHelp(out, path, params);
    } else if (strncmp(path.c_str(), "about", 5) == 0) {
        printAbout(out, path, params);
    } else if (running && strncmp(path.c_str(), "config", 6) == 0) {
        printConfig(out, path, params);
    } else if (strncmp(path.c_str(), "status", 6) == 0) {
        printStatus(out, path, params);
    } else if (running) {
        printSearch(out, path, params);
    } else {
        printStatus(out, path, params);
    }

    printFooter(out, path, params);
}
StrigiHtmlGui::Private::Private(HtmlHelper* helper) :h(helper) {
    string homedir = getenv("HOME");
    strigi.setSocketName(homedir+"/.strigi/socket");
}
void
StrigiHtmlGui::Private::printSearchResult(ostream& out,
        const jstreams::IndexedDocument& doc) {
    string link, icon, name, folder;
    link = h->mapLinkUrl(doc.uri);
    icon = "mapMimetypeIcon(doc.uri, doc.mimetype);
    icon += "'/>";
    map<string, string>::const_iterator t = doc.properties.find("title");
    size_t l = doc.uri.rfind('/');
    if (t != doc.properties.end()) {
        name = t->second.c_str();
    } else if (l != string::npos) {
        name = doc.uri.substr(l+1);
    } else {
        name = doc.uri;
    }
    if (l != string::npos) {
        folder = doc.uri.substr(0, l);
    }
    out << "
" << icon << "
<a href='" << link << "'>";
    out << name << "

score: ";
    out << doc.score << ", mime-type: " << doc.mimetype.c_str() << ", size: ";
    out << doc.size << ", last modified: " << h->formatDate(doc.mtime);
    string fragment = h->escapeString(doc.fragment.substr(0,100));
    out << "
" << fragment << "

";
    map<string, string>::const_iterator j;
    for (j = doc.properties.begin(); j != doc.properties.end(); ++j) {
        out << "
" << j->first << ":	" << j->second.c_str()
            << "
";
    }
    out << "

";
}
void
StrigiHtmlGui::Private::printSearchResults(ostream& out,
        const ClientInterface::Hits& hits) {
    vector<jstreams::IndexedDocument>::const_iterator i;
    for (i = hits.hits.begin(); i != hits.hits.end(); ++i) {
        printSearchResult(out, *i);
    }
}
<|endoftext|>


<commit_before>// This file is distributed under the BSD License.
// See "license.txt" for details.
// Copyright 2009-2010, Jonathan Turner (jonathan@emptycrate.com)
// and Jason Turner (jason@emptycrate.com)
// http://www.chaiscript.com

#include <iostream>

#include <list>

#define _CRT_SECURE_NO_WARNINGS

#ifdef READLINE_AVAILABLE
#include <readline/readline.h>
#include <readline/history.h>
#endif

#include <chaiscript/chaiscript.hpp>

void print_help() {
  std::cout << "ChaiScript evaluator.  To evaluate an expression, type it and press <enter>." << std::endl;
  std::cout << "Additionally, you can inspect the runtime system using:" << std::endl;
  std::cout << "  dump_system() - outputs all functions registered to the system" << std::endl;
  std::cout << "  dump_object(x) - dumps information about the given symbol" << std::endl;
}

bool throws_exception(const chaiscript::Proxy_Function &f)
{
  try {
    chaiscript::functor<void ()>(f)();
  } catch (...) {
    return true;
  }

  return false;
}

std::string get_next_command() {
#ifdef READLINE_AVAILABLE
  char *input_raw;
  input_raw = readline("eval> ");
  add_history(input_raw);
  return std::string(input_raw);
#else
  std::string retval;
  std::cout << "eval> ";
  std::getline(std::cin, retval);
  return retval;
#endif
}

void myexit(int return_val) {
  exit(return_val);
}

int main(int argc, char *argv[]) {
  std::string input;

  std::vector<std::string> usepaths;
  std::vector<std::string> modulepaths;

  // Disable deprecation warning for getenv call.
#ifdef BOOST_MSVC
#pragma warning(push)
#pragma warning(disable : 4996)
#endif

  const char *usepath = getenv("CHAI_USE_PATH");
  const char *modulepath = getenv("CHAI_MODULE_PATH");

#ifdef BOOST_MSVC
#pragma warning(pop)
#endif

  usepaths.push_back("");

  if (usepath)
  {
    usepaths.push_back(usepath);
  }

  modulepaths.push_back("");

  if (modulepath)
  {
    modulepaths.push_back(modulepath);
  }

  chaiscript::ChaiScript chai(modulepaths,usepaths);

  chai.add(chaiscript::fun(&myexit), "exit");
  chai.add(chaiscript::fun(&throws_exception), "throws_exception");

  if (argc < 2) {
#ifdef READLINE_AVAILABLE
    using_history();
#endif
    input = get_next_command();
    while (input != "quit") {

      chaiscript::Boxed_Value val;

      if (input == "help") {
        print_help();
      }
      else {
        try {
          //First, we evaluate it
          val = chai.eval(input);

          //Then, we try to print the result of the evaluation to the user
          if (!val.get_type_info().bare_equal(chaiscript::user_type<void>())) {
            try {
              chaiscript::dispatch(chai.get_eval_engine().get_function("print"), chaiscript::Param_List_Builder() << val);
            }
            catch (...) {
              //If we can't, do nothing
            }
          }
        }
        catch (chaiscript::Eval_Error &ee) {
          std::cout << ee.what();
          if (ee.call_stack.size() > 0) {
            std::cout << "during evaluation at (" << ee.call_stack[0]->start.line << ", " << ee.call_stack[0]->start.column << ")";
          }
          std::cout << std::endl;
        }
        catch (std::exception &e) {
          std::cout << e.what();
          std::cout << std::endl;
        }
      }

      input = get_next_command();
    }
  }
  else {
    for (int i = 1; i < argc; ++i) {
      try {
        chaiscript::Boxed_Value val = chai.eval_file(argv[i]);
      }
      catch (chaiscript::Eval_Error &ee) {
        std::cout << ee.what();
        if (ee.call_stack.size() > 0) {
          std::cout << "during evaluation at (" << ee.call_stack[0]->filename << " " << ee.call_stack[0]->start.line << ", " << ee.call_stack[0]->start.column << ")";
          for (unsigned int j = 1; j < ee.call_stack.size(); ++j) {
            std::cout << std::endl;
            std::cout << "  from " << ee.call_stack[j]->filename << " (" << ee.call_stack[j]->start.line << ", " << ee.call_stack[j]->start.column << ")";
          }
        }
        std::cout << std::endl;
        return EXIT_FAILURE;
      }
      catch (std::exception &e) {
        std::cout << e.what() << std::endl;
        return EXIT_FAILURE;
      }
    }
  }

  return EXIT_SUCCESS;
}

<commit_msg>Add comment about clang work around<commit_after>// This file is distributed under the BSD License.
// See "license.txt" for details.
// Copyright 2009-2010, Jonathan Turner (jonathan@emptycrate.com)
// and Jason Turner (jason@emptycrate.com)
// http://www.chaiscript.com

#include <iostream>

#include <list>

#define _CRT_SECURE_NO_WARNINGS

#ifdef READLINE_AVAILABLE
#include <readline/readline.h>
#include <readline/history.h>
#endif

#include <chaiscript/chaiscript.hpp>

void print_help() {
  std::cout << "ChaiScript evaluator.  To evaluate an expression, type it and press <enter>." << std::endl;
  std::cout << "Additionally, you can inspect the runtime system using:" << std::endl;
  std::cout << "  dump_system() - outputs all functions registered to the system" << std::endl;
  std::cout << "  dump_object(x) - dumps information about the given symbol" << std::endl;
}

bool throws_exception(const chaiscript::Proxy_Function &f)
{
  try {
    chaiscript::functor<void ()>(f)();
  } catch (...) {
    return true;
  }

  return false;
}

std::string get_next_command() {
#ifdef READLINE_AVAILABLE
  char *input_raw;
  input_raw = readline("eval> ");
  add_history(input_raw);
  return std::string(input_raw);
#else
  std::string retval;
  std::cout << "eval> ";
  std::getline(std::cin, retval);
  return retval;
#endif
}

// We have to wrap exit with our own because Clang has a hard time with
// function pointers to functions with special attributes (system exit being marked NORETURN)
void myexit(int return_val) {
  exit(return_val);
}

int main(int argc, char *argv[]) {
  std::string input;

  std::vector<std::string> usepaths;
  std::vector<std::string> modulepaths;

  // Disable deprecation warning for getenv call.
#ifdef BOOST_MSVC
#pragma warning(push)
#pragma warning(disable : 4996)
#endif

  const char *usepath = getenv("CHAI_USE_PATH");
  const char *modulepath = getenv("CHAI_MODULE_PATH");

#ifdef BOOST_MSVC
#pragma warning(pop)
#endif

  usepaths.push_back("");

  if (usepath)
  {
    usepaths.push_back(usepath);
  }

  modulepaths.push_back("");

  if (modulepath)
  {
    modulepaths.push_back(modulepath);
  }

  chaiscript::ChaiScript chai(modulepaths,usepaths);

  chai.add(chaiscript::fun(&myexit), "exit");
  chai.add(chaiscript::fun(&throws_exception), "throws_exception");

  if (argc < 2) {
#ifdef READLINE_AVAILABLE
    using_history();
#endif
    input = get_next_command();
    while (input != "quit") {

      chaiscript::Boxed_Value val;

      if (input == "help") {
        print_help();
      }
      else {
        try {
          //First, we evaluate it
          val = chai.eval(input);

          //Then, we try to print the result of the evaluation to the user
          if (!val.get_type_info().bare_equal(chaiscript::user_type<void>())) {
            try {
              chaiscript::dispatch(chai.get_eval_engine().get_function("print"), chaiscript::Param_List_Builder() << val);
            }
            catch (...) {
              //If we can't, do nothing
            }
          }
        }
        catch (chaiscript::Eval_Error &ee) {
          std::cout << ee.what();
          if (ee.call_stack.size() > 0) {
            std::cout << "during evaluation at (" << ee.call_stack[0]->start.line << ", " << ee.call_stack[0]->start.column << ")";
          }
          std::cout << std::endl;
        }
        catch (std::exception &e) {
          std::cout << e.what();
          std::cout << std::endl;
        }
      }

      input = get_next_command();
    }
  }
  else {
    for (int i = 1; i < argc; ++i) {
      try {
        chaiscript::Boxed_Value val = chai.eval_file(argv[i]);
      }
      catch (chaiscript::Eval_Error &ee) {
        std::cout << ee.what();
        if (ee.call_stack.size() > 0) {
          std::cout << "during evaluation at (" << ee.call_stack[0]->filename << " " << ee.call_stack[0]->start.line << ", " << ee.call_stack[0]->start.column << ")";
          for (unsigned int j = 1; j < ee.call_stack.size(); ++j) {
            std::cout << std::endl;
            std::cout << "  from " << ee.call_stack[j]->filename << " (" << ee.call_stack[j]->start.line << ", " << ee.call_stack[j]->start.column << ")";
          }
        }
        std::cout << std::endl;
        return EXIT_FAILURE;
      }
      catch (std::exception &e) {
        std::cout << e.what() << std::endl;
        return EXIT_FAILURE;
      }
    }
  }

  return EXIT_SUCCESS;
}

<|endoftext|>