<commit_before>/*
 base64.cpp and base64.h

 Copyright (C) 2004-2008 René Nyffenegger

 This source code is provided 'as-is', without any express or implied
 warranty. In no event will the author be held liable for any damages
 arising from the use of this software.

 Permission is granted to anyone to use this software for any purpose,
 including commercial applications, and to alter it and redistribute it
 freely, subject to the following restrictions:

 1. The origin of this source code must not be misrepresented; you must not
 claim that you wrote the original source code. If you use this source code
 in a product, an acknowledgment in the product documentation would be
 appreciated but is not required.

 2. Altered source versions must be plainly marked as such, and must not be
 misrepresented as being the original source code.

 3. This notice may not be removed or altered from any source distribution.

 René Nyffenegger rene.nyffenegger@adp-gmbh.ch

 */

#include <cstring>
#include <iostream>

#include "base64.hpp"

static const char * const base64_chars =
"ABCDEFGHIJKLMNOPQRSTUVWXYZ"
"abcdefghijklmnopqrstuvwxyz"
"0123456789+/";

static inline bool is_base64(unsigned char c) {
	return (isalnum(c) || (c == '+') || (c == '/'));
}

std::string base64_encode(unsigned char const* bytes_to_encode, unsigned int in_len) {
	std::string ret;
	int i = 0;
	int j = 0;
	unsigned char char_array_3[3];
	unsigned char char_array_4[4];

	while (in_len--) {
		char_array_3[i++] = *(bytes_to_encode++);
		if (i == 3) {
			char_array_4[0] = (char_array_3[0] & 0xfc) >> 2;
			char_array_4[1] = ((char_array_3[0] & 0x03) << 4) + ((char_array_3[1] & 0xf0) >> 4);
			char_array_4[2] = ((char_array_3[1] & 0x0f) << 2) + ((char_array_3[2] & 0xc0) >> 6);
			char_array_4[3] = char_array_3[2] & 0x3f;

			for(i = 0; (i <4) ; i++)
				ret += base64_chars[char_array_4[i]];
			i = 0;
		}
	}

	if (i)
	{
		for(j = i; j < 3; j++)
			char_array_3[j] = '\0';

		char_array_4[0] = (char_array_3[0] & 0xfc) >> 2;
		char_array_4[1] = ((char_array_3[0] & 0x03) << 4) + ((char_array_3[1] & 0xf0) >> 4);
		char_array_4[2] = ((char_array_3[1] & 0x0f) << 2) + ((char_array_3[2] & 0xc0) >> 6);
		char_array_4[3] = char_array_3[2] & 0x3f;

		for (j = 0; (j < i + 1); j++)
			ret += base64_chars[char_array_4[j]];

		while((i++ < 3))
			ret += '=';

	}

	return ret;

}

inline int strfnd(const char *str, char ch)
{
  return static_cast<int>(strchr(str, ch) - str);
}

inline int strfnd(const char *str, char ch)
{
  return static_cast<int>(strchr(str, ch) - str);
}

std::string base64_decode(std::string const& encoded_string) {
	int in_len = static_cast<int>(encoded_string.size());
	int i = 0;
	int j = 0;
	int in_ = 0;
	unsigned char char_array_4[4], char_array_3[3];
	std::string ret;

	while (in_len-- && ( encoded_string[in_] != '=') && is_base64(encoded_string[in_])) {
		char_array_4[i++] = encoded_string[in_]; in_++;
		if (i ==4) {
			for (i = 0; i <4; i++) {
				char_array_4[i] = strfnd(base64_chars, char_array_4[i]);
			}

			char_array_3[0] = (char_array_4[0] << 2) + ((char_array_4[1] & 0x30) >> 4);
			char_array_3[1] = ((char_array_4[1] & 0xf) << 4) + ((char_array_4[2] & 0x3c) >> 2);
			char_array_3[2] = ((char_array_4[2] & 0x3) << 6) + char_array_4[3];

			for (i = 0; (i < 3); i++)
				ret += char_array_3[i];
			i = 0;
		}
	}

	if (i) {
		for (j = i; j <4; j++)
			char_array_4[j] = 0;

		for (j = 0; j <4; j++)
			char_array_4[j] = strfnd(base64_chars, char_array_4[j]);

		char_array_3[0] = (char_array_4[0] << 2) + ((char_array_4[1] & 0x30) >> 4);
		char_array_3[1] = ((char_array_4[1] & 0xf) << 4) + ((char_array_4[2] & 0x3c) >> 2);
		char_array_3[2] = ((char_array_4[2] & 0x3) << 6) + char_array_4[3];

		for (j = 0; (j < i - 1); j++) ret += char_array_3[j];
	}

	return ret;
}
<commit_msg>bugfix<commit_after>/*
 base64.cpp and base64.h

 Copyright (C) 2004-2008 René Nyffenegger

 This source code is provided 'as-is', without any express or implied
 warranty. In no event will the author be held liable for any damages
 arising from the use of this software.

 Permission is granted to anyone to use this software for any purpose,
 including commercial applications, and to alter it and redistribute it
 freely, subject to the following restrictions:

 1. The origin of this source code must not be misrepresented; you must not
 claim that you wrote the original source code. If you use this source code
 in a product, an acknowledgment in the product documentation would be
 appreciated but is not required.

 2. Altered source versions must be plainly marked as such, and must not be
 misrepresented as being the original source code.

 3. This notice may not be removed or altered from any source distribution.

 René Nyffenegger rene.nyffenegger@adp-gmbh.ch

 */

#include <cstring>
#include <iostream>

#include "base64.hpp"

static const char * const base64_chars =
"ABCDEFGHIJKLMNOPQRSTUVWXYZ"
"abcdefghijklmnopqrstuvwxyz"
"0123456789+/";

static inline bool is_base64(unsigned char c) {
	return (isalnum(c) || (c == '+') || (c == '/'));
}

std::string base64_encode(unsigned char const* bytes_to_encode, unsigned int in_len) {
	std::string ret;
	int i = 0;
	int j = 0;
	unsigned char char_array_3[3];
	unsigned char char_array_4[4];

	while (in_len--) {
		char_array_3[i++] = *(bytes_to_encode++);
		if (i == 3) {
			char_array_4[0] = (char_array_3[0] & 0xfc) >> 2;
			char_array_4[1] = ((char_array_3[0] & 0x03) << 4) + ((char_array_3[1] & 0xf0) >> 4);
			char_array_4[2] = ((char_array_3[1] & 0x0f) << 2) + ((char_array_3[2] & 0xc0) >> 6);
			char_array_4[3] = char_array_3[2] & 0x3f;

			for(i = 0; (i <4) ; i++)
				ret += base64_chars[char_array_4[i]];
			i = 0;
		}
	}

	if (i)
	{
		for(j = i; j < 3; j++)
			char_array_3[j] = '\0';

		char_array_4[0] = (char_array_3[0] & 0xfc) >> 2;
		char_array_4[1] = ((char_array_3[0] & 0x03) << 4) + ((char_array_3[1] & 0xf0) >> 4);
		char_array_4[2] = ((char_array_3[1] & 0x0f) << 2) + ((char_array_3[2] & 0xc0) >> 6);
		char_array_4[3] = char_array_3[2] & 0x3f;

		for (j = 0; (j < i + 1); j++)
			ret += base64_chars[char_array_4[j]];

		while((i++ < 3))
			ret += '=';

	}

	return ret;

}

inline int strfnd(const char *str, char ch)
{
  return static_cast<int>(strchr(str, ch) - str);
}

std::string base64_decode(std::string const& encoded_string) {
	int in_len = static_cast<int>(encoded_string.size());
	int i = 0;
	int j = 0;
	int in_ = 0;
	unsigned char char_array_4[4], char_array_3[3];
	std::string ret;

	while (in_len-- && ( encoded_string[in_] != '=') && is_base64(encoded_string[in_])) {
		char_array_4[i++] = encoded_string[in_]; in_++;
		if (i ==4) {
			for (i = 0; i <4; i++) {
				char_array_4[i] = strfnd(base64_chars, char_array_4[i]);
			}

			char_array_3[0] = (char_array_4[0] << 2) + ((char_array_4[1] & 0x30) >> 4);
			char_array_3[1] = ((char_array_4[1] & 0xf) << 4) + ((char_array_4[2] & 0x3c) >> 2);
			char_array_3[2] = ((char_array_4[2] & 0x3) << 6) + char_array_4[3];

			for (i = 0; (i < 3); i++)
				ret += char_array_3[i];
			i = 0;
		}
	}

	if (i) {
		for (j = i; j <4; j++)
			char_array_4[j] = 0;

		for (j = 0; j <4; j++)
			char_array_4[j] = strfnd(base64_chars, char_array_4[j]);

		char_array_3[0] = (char_array_4[0] << 2) + ((char_array_4[1] & 0x30) >> 4);
		char_array_3[1] = ((char_array_4[1] & 0xf) << 4) + ((char_array_4[2] & 0x3c) >> 2);
		char_array_3[2] = ((char_array_4[2] & 0x3) << 6) + char_array_4[3];

		for (j = 0; (j < i - 1); j++) ret += char_array_3[j];
	}

	return ret;
}
<|endoftext|>


<commit_before>/* $Id$ */
/* Author: Wolfgang Bangerth, University of Heidelberg, 2000 */

/*    $Id$       */
/*    Version: $Name$                                          */
/*                                                                */
/*    Copyright (C) 2000, 2001, 2002, 2003, 2004, 2006 by the deal.II authors */
/*                                                                */
/*    This file is subject to QPL and may not be  distributed     */
/*    without copyright and license information. Please refer     */
/*    to the file deal.II/doc/license.html for the  text  and     */
/*    further information on this license.                        */

                                 // @sect3{Include files}

				 // The first few files have already
				 // been covered in previous examples
				 // and will thus not be further
				 // commented on.
#include <base/quadrature_lib.h>
#include <base/function.h>
#include <base/logstream.h>
#include <base/utilities.h>
#include <lac/vector.h>
#include <lac/full_matrix.h>
#include <lac/sparse_matrix.h>
#include <lac/solver_cg.h>
#include <lac/precondition.h>
#include <grid/tria.h>
#include <dofs/hp_dof_handler.h>
#include <grid/grid_generator.h>
#include <grid/tria_accessor.h>
#include <grid/tria_iterator.h>
#include <grid/tria_boundary_lib.h>
#include <dofs/dof_accessor.h>
#include <dofs/dof_tools.h>
#include <fe/fe_values.h>
#include <numerics/vectors.h>
#include <numerics/matrices.h>
#include <numerics/data_out.h>

#include <fstream>
#include <iostream>

#include <fe/fe_q.h>
#include <grid/grid_out.h>
#include <dofs/dof_constraints.h>
#include <grid/grid_refinement.h>
#include <numerics/error_estimator.h>

				 // Finally, this is as in previous
				 // programs:
using namespace dealii;

template <int dim>
class LaplaceProblem
{
  public:
    LaplaceProblem ();
    ~LaplaceProblem ();

    void run ();

  private:
    void setup_system ();
    void assemble_system ();
    void solve ();
    void refine_grid ();
    void output_results (const unsigned int cycle) const;

    Triangulation<dim>   triangulation;

    DoFHandler<dim>      dof_handler;
    FE_Q<dim>            fe;

    ConstraintMatrix     hanging_node_constraints;

    SparsityPattern      sparsity_pattern;
    SparseMatrix<double> system_matrix;

    Vector<double>       solution;
    Vector<double>       system_rhs;
};

template <int dim>
LaplaceProblem<dim>::LaplaceProblem () :
		dof_handler (triangulation),
                fe (2)
{}

template <int dim>
LaplaceProblem<dim>::~LaplaceProblem ()
{
  dof_handler.clear ();
}

template <int dim>
void LaplaceProblem<dim>::setup_system ()
{
  dof_handler.distribute_dofs (fe);

  sparsity_pattern.reinit (dof_handler.n_dofs(),
			   dof_handler.n_dofs(),
			   dof_handler.max_couplings_between_dofs());
  DoFTools::make_sparsity_pattern (dof_handler, sparsity_pattern);

  solution.reinit (dof_handler.n_dofs());
  system_rhs.reinit (dof_handler.n_dofs());

  hanging_node_constraints.clear ();
  DoFTools::make_hanging_node_constraints (dof_handler,
					   hanging_node_constraints);

  hanging_node_constraints.close ();

  hanging_node_constraints.condense (sparsity_pattern);
  sparsity_pattern.compress();

  system_matrix.reinit (sparsity_pattern);
}

template <int dim>
void LaplaceProblem<dim>::assemble_system ()
{
  const QGauss<dim>  quadrature_formula(3);

  FEValues<dim> fe_values (fe, quadrature_formula,
			   update_values    |  update_gradients |
			   update_q_points  |  update_JxW_values);

  const unsigned int   dofs_per_cell = fe.dofs_per_cell;
  const unsigned int   n_q_points    = quadrature_formula.n_quadrature_points;

  FullMatrix<double>   cell_matrix (dofs_per_cell, dofs_per_cell);
  Vector<double>       cell_rhs (dofs_per_cell);

  std::vector<unsigned int> local_dof_indices (dofs_per_cell);

  typename DoFHandler<dim>::active_cell_iterator
    cell = dof_handler.begin_active(),
    endc = dof_handler.end();
  for (; cell!=endc; ++cell)
    {
      cell_matrix = 0;
      cell_rhs = 0;

      fe_values.reinit (cell);

      for (unsigned int q_point=0; q_point<n_q_points; ++q_point)
	for (unsigned int i=0; i<dofs_per_cell; ++i)
	  {
	    for (unsigned int j=0; j<dofs_per_cell; ++j)
	      cell_matrix(i,j) += (fe_values.shape_grad(i,q_point) *
				   fe_values.shape_grad(j,q_point) *
				   fe_values.JxW(q_point));

	    cell_rhs(i) += (fe_values.shape_value(i,q_point) *
			    1.0 *
			    fe_values.JxW(q_point));
	  }

      cell->get_dof_indices (local_dof_indices);
      for (unsigned int i=0; i<dofs_per_cell; ++i)
	{
	  for (unsigned int j=0; j<dofs_per_cell; ++j)
	    system_matrix.add (local_dof_indices[i],
			       local_dof_indices[j],
			       cell_matrix(i,j));

	  system_rhs(local_dof_indices[i]) += cell_rhs(i);
	}
    }

  hanging_node_constraints.condense (system_matrix);
  hanging_node_constraints.condense (system_rhs);
  std::map<unsigned int,double> boundary_values;
  VectorTools::interpolate_boundary_values (dof_handler,
					    0,
					    ZeroFunction<dim>(),
					    boundary_values);
  MatrixTools::apply_boundary_values (boundary_values,
				      system_matrix,
				      solution,
				      system_rhs);
}

template <int dim>
void LaplaceProblem<dim>::solve ()
{
  SolverControl           solver_control (1000, 1e-12);
  SolverCG<>              cg (solver_control);

  PreconditionSSOR<> preconditioner;
  preconditioner.initialize(system_matrix, 1.2);

  cg.solve (system_matrix, solution, system_rhs,
	    preconditioner);

  hanging_node_constraints.distribute (solution);
}

template <int dim>
void LaplaceProblem<dim>::refine_grid ()
{
  Vector<float> estimated_error_per_cell (triangulation.n_active_cells());

  KellyErrorEstimator<dim>::estimate (dof_handler,
				      QGauss<dim-1>(3),
				      typename FunctionMap<dim>::type(),
				      solution,
				      estimated_error_per_cell);

  GridRefinement::refine_and_coarsen_fixed_number (triangulation,
						   estimated_error_per_cell,
						   0.3, 0.03);

  triangulation.execute_coarsening_and_refinement ();
}

template <int dim>
void LaplaceProblem<dim>::output_results (const unsigned int cycle) const
{
  Assert (cycle < 10, ExcNotImplemented());

  {
    const std::string filename = "grid-" +
				 Utilities::int_to_string (cycle, 2) +
				 ".eps";
    std::ofstream output (filename.c_str());

    GridOut grid_out;
    grid_out.write_eps (triangulation, output);
  }

  {
    const std::string filename = "solution-" +
				 Utilities::int_to_string (cycle, 2) +
				 ".gnuplot";
    DataOut<dim> data_out;

    data_out.attach_dof_handler (dof_handler);
    data_out.add_data_vector (solution, "solution");
    data_out.build_patches ();

    std::ofstream output (filename.c_str());
    data_out.write_gnuplot (output);
  }
}

void
create_coarse_grid (Triangulation<2> &coarse_grid)
{
  const unsigned int dim = 2;
  static const Point<2> vertices_1[]
    = {  Point<2> (-1.,   -1.),
         Point<2> (-1./2, -1.),
         Point<2> (0.,    -1.),
         Point<2> (+1./2, -1.),
         Point<2> (+1,    -1.),

         Point<2> (-1.,   -1./2.),
         Point<2> (-1./2, -1./2.),
         Point<2> (0.,    -1./2.),
         Point<2> (+1./2, -1./2.),
         Point<2> (+1,    -1./2.),

         Point<2> (-1.,   0.),
         Point<2> (-1./2, 0.),
         Point<2> (+1./2, 0.),
         Point<2> (+1,    0.),

         Point<2> (-1.,   1./2.),
         Point<2> (-1./2, 1./2.),
         Point<2> (0.,    1./2.),
         Point<2> (+1./2, 1./2.),
         Point<2> (+1,    1./2.),

         Point<2> (-1.,   1.),
         Point<2> (-1./2, 1.),
         Point<2> (0.,    1.),
         Point<2> (+1./2, 1.),
         Point<2> (+1,    1.)    };
  const unsigned int
    n_vertices = sizeof(vertices_1) / sizeof(vertices_1[0]);
  const std::vector<Point<dim> > vertices (&vertices_1[0],
                                           &vertices_1[n_vertices]);
  static const int cell_vertices[][GeometryInfo<dim>::vertices_per_cell]
    = {{0, 1, 5, 6},
       {1, 2, 6, 7},
       {2, 3, 7, 8},
       {3, 4, 8, 9},
       {5, 6, 10, 11},
       {8, 9, 12, 13},
       {10, 11, 14, 15},
       {12, 13, 17, 18},
       {14, 15, 19, 20},
       {15, 16, 20, 21},
       {16, 17, 21, 22},
       {17, 18, 22, 23}};
  const unsigned int
    n_cells = sizeof(cell_vertices) / sizeof(cell_vertices[0]);

  std::vector<CellData<dim> > cells (n_cells, CellData<dim>());
  for (unsigned int i=0; i<n_cells; ++i)
    {
      for (unsigned int j=0;
           j<GeometryInfo<dim>::vertices_per_cell;
           ++j)
        cells[i].vertices[j] = cell_vertices[i][j];
      cells[i].material_id = 0;
    }

  coarse_grid.create_triangulation (vertices,
                                    cells,
                                    SubCellData());
  coarse_grid.refine_global (1);
}

template <int dim>
void LaplaceProblem<dim>::run ()
{
  for (unsigned int cycle=0; cycle<5; ++cycle)
    {
      std::cout << "Cycle " << cycle << ':' << std::endl;

      if (cycle == 0)
	create_coarse_grid (triangulation);
      else
	refine_grid ();

      std::cout << "   Number of active cells:       "
		<< triangulation.n_active_cells()
		<< std::endl;

      setup_system ();

      std::cout << "   Number of degrees of freedom: "
		<< dof_handler.n_dofs()
		<< std::endl;

      assemble_system ();
      solve ();
      output_results (cycle);
    }
}

int main ()
{
  try
    {
      deallog.depth_console (0);

      LaplaceProblem<2> laplace_problem_2d;
      laplace_problem_2d.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>hp-ify the code.<commit_after>/* $Id$ */
/* Author: Wolfgang Bangerth, University of Heidelberg, 2000 */

/*    $Id$       */
/*    Version: $Name$                                          */
/*                                                                */
/*    Copyright (C) 2000, 2001, 2002, 2003, 2004, 2006 by the deal.II authors */
/*                                                                */
/*    This file is subject to QPL and may not be  distributed     */
/*    without copyright and license information. Please refer     */
/*    to the file deal.II/doc/license.html for the  text  and     */
/*    further information on this license.                        */

                                 // @sect3{Include files}

				 // The first few files have already
				 // been covered in previous examples
				 // and will thus not be further
				 // commented on.
#include <base/quadrature_lib.h>
#include <base/function.h>
#include <base/logstream.h>
#include <base/utilities.h>
#include <lac/vector.h>
#include <lac/full_matrix.h>
#include <lac/sparse_matrix.h>
#include <lac/solver_cg.h>
#include <lac/precondition.h>
#include <grid/tria.h>
#include <dofs/hp_dof_handler.h>
#include <grid/grid_generator.h>
#include <grid/tria_accessor.h>
#include <grid/tria_iterator.h>
#include <grid/tria_boundary_lib.h>
#include <dofs/dof_accessor.h>
#include <dofs/dof_tools.h>
#include <fe/hp_fe_values.h>
#include <numerics/vectors.h>
#include <numerics/matrices.h>
#include <numerics/data_out.h>

#include <fstream>
#include <iostream>

#include <fe/fe_q.h>
#include <grid/grid_out.h>
#include <dofs/dof_constraints.h>
#include <grid/grid_refinement.h>
#include <numerics/error_estimator.h>

				 // Finally, this is as in previous
				 // programs:
using namespace dealii;

template <int dim>
class LaplaceProblem
{
  public:
    LaplaceProblem ();
    ~LaplaceProblem ();

    void run ();

  private:
    void setup_system ();
    void assemble_system ();
    void solve ();
    void refine_grid ();
    void output_results (const unsigned int cycle) const;

    Triangulation<dim>   triangulation;

    hp::DoFHandler<dim>      dof_handler;
    hp::FECollection<dim>    fe_collection;
    hp::QCollection<dim>     quadrature_collection;

    ConstraintMatrix     hanging_node_constraints;

    SparsityPattern      sparsity_pattern;
    SparseMatrix<double> system_matrix;

    Vector<double>       solution;
    Vector<double>       system_rhs;
};

template <int dim>
LaplaceProblem<dim>::LaplaceProblem () :
		dof_handler (triangulation)
{
  for (unsigned int degree=1; degree<5; ++degree)
    {
      fe_collection.push_back (FE_Q<dim>(degree));
      quadrature_collection.push_back (QGauss<dim>(degree+2));
    }
}

template <int dim>
LaplaceProblem<dim>::~LaplaceProblem ()
{
  dof_handler.clear ();
}

template <int dim>
void LaplaceProblem<dim>::setup_system ()
{
  dof_handler.distribute_dofs (fe_collection);

  sparsity_pattern.reinit (dof_handler.n_dofs(),
			   dof_handler.n_dofs(),
			   dof_handler.max_couplings_between_dofs());
  DoFTools::make_sparsity_pattern (dof_handler, sparsity_pattern);

  solution.reinit (dof_handler.n_dofs());
  system_rhs.reinit (dof_handler.n_dofs());

  hanging_node_constraints.clear ();
  DoFTools::make_hanging_node_constraints (dof_handler,
					   hanging_node_constraints);

  hanging_node_constraints.close ();

  hanging_node_constraints.condense (sparsity_pattern);
  sparsity_pattern.compress();

  system_matrix.reinit (sparsity_pattern);
}

template <int dim>
void LaplaceProblem<dim>::assemble_system ()
{
  hp::FEValues<dim> hp_fe_values (fe_collection,
				  quadrature_collection,
				  update_values    |  update_gradients |
				  update_q_points  |  update_JxW_values);

  typename hp::DoFHandler<dim>::active_cell_iterator
    cell = dof_handler.begin_active(),
    endc = dof_handler.end();
  for (; cell!=endc; ++cell)
    {
      const unsigned int   dofs_per_cell = cell->get_fe().dofs_per_cell;
      FullMatrix<double>   cell_matrix (dofs_per_cell, dofs_per_cell);
      Vector<double>       cell_rhs (dofs_per_cell);

      std::vector<unsigned int> local_dof_indices (dofs_per_cell);

      cell_matrix = 0;
      cell_rhs = 0;

      hp_fe_values.reinit (cell);

      const FEValues<dim> &fe_values = hp_fe_values.get_present_fe_values ();

      for (unsigned int q_point=0; q_point<fe_values.n_quadrature_points; ++q_point)
	for (unsigned int i=0; i<dofs_per_cell; ++i)
	  {
	    for (unsigned int j=0; j<dofs_per_cell; ++j)
	      cell_matrix(i,j) += (fe_values.shape_grad(i,q_point) *
				   fe_values.shape_grad(j,q_point) *
				   fe_values.JxW(q_point));

	    cell_rhs(i) += (fe_values.shape_value(i,q_point) *
			    1.0 *
			    fe_values.JxW(q_point));
	  }

      cell->get_dof_indices (local_dof_indices);
      for (unsigned int i=0; i<dofs_per_cell; ++i)
	{
	  for (unsigned int j=0; j<dofs_per_cell; ++j)
	    system_matrix.add (local_dof_indices[i],
			       local_dof_indices[j],
			       cell_matrix(i,j));

	  system_rhs(local_dof_indices[i]) += cell_rhs(i);
	}
    }

  hanging_node_constraints.condense (system_matrix);
  hanging_node_constraints.condense (system_rhs);
  std::map<unsigned int,double> boundary_values;
  VectorTools::interpolate_boundary_values (dof_handler,
					    0,
					    ZeroFunction<dim>(),
					    boundary_values);
  MatrixTools::apply_boundary_values (boundary_values,
				      system_matrix,
				      solution,
				      system_rhs);
}

template <int dim>
void LaplaceProblem<dim>::solve ()
{
  SolverControl           solver_control (1000, 1e-12);
  SolverCG<>              cg (solver_control);

  PreconditionSSOR<> preconditioner;
  preconditioner.initialize(system_matrix, 1.2);

  cg.solve (system_matrix, solution, system_rhs,
	    preconditioner);

  hanging_node_constraints.distribute (solution);
}

template <int dim>
void LaplaceProblem<dim>::refine_grid ()
{
  Vector<float> estimated_error_per_cell (triangulation.n_active_cells());

  KellyErrorEstimator<dim>::estimate (dof_handler,
				      QGauss<dim-1>(3),
				      typename FunctionMap<dim>::type(),
				      solution,
				      estimated_error_per_cell);

  GridRefinement::refine_and_coarsen_fixed_number (triangulation,
						   estimated_error_per_cell,
						   0.3, 0.03);

  triangulation.execute_coarsening_and_refinement ();
}

template <int dim>
void LaplaceProblem<dim>::output_results (const unsigned int cycle) const
{
  Assert (cycle < 10, ExcNotImplemented());

  {
    const std::string filename = "grid-" +
				 Utilities::int_to_string (cycle, 2) +
				 ".eps";
    std::ofstream output (filename.c_str());

    GridOut grid_out;
    grid_out.write_eps (triangulation, output);
  }

  {
    const std::string filename = "solution-" +
				 Utilities::int_to_string (cycle, 2) +
				 ".gnuplot";
    DataOut<dim,hp::DoFHandler<dim> > data_out;

    data_out.attach_dof_handler (dof_handler);
    data_out.add_data_vector (solution, "solution");
    data_out.build_patches ();

    std::ofstream output (filename.c_str());
    data_out.write_gnuplot (output);
  }
}

void
create_coarse_grid (Triangulation<2> &coarse_grid)
{
  const unsigned int dim = 2;
  static const Point<2> vertices_1[]
    = {  Point<2> (-1.,   -1.),
         Point<2> (-1./2, -1.),
         Point<2> (0.,    -1.),
         Point<2> (+1./2, -1.),
         Point<2> (+1,    -1.),

         Point<2> (-1.,   -1./2.),
         Point<2> (-1./2, -1./2.),
         Point<2> (0.,    -1./2.),
         Point<2> (+1./2, -1./2.),
         Point<2> (+1,    -1./2.),

         Point<2> (-1.,   0.),
         Point<2> (-1./2, 0.),
         Point<2> (+1./2, 0.),
         Point<2> (+1,    0.),

         Point<2> (-1.,   1./2.),
         Point<2> (-1./2, 1./2.),
         Point<2> (0.,    1./2.),
         Point<2> (+1./2, 1./2.),
         Point<2> (+1,    1./2.),

         Point<2> (-1.,   1.),
         Point<2> (-1./2, 1.),
         Point<2> (0.,    1.),
         Point<2> (+1./2, 1.),
         Point<2> (+1,    1.)    };
  const unsigned int
    n_vertices = sizeof(vertices_1) / sizeof(vertices_1[0]);
  const std::vector<Point<dim> > vertices (&vertices_1[0],
                                           &vertices_1[n_vertices]);
  static const int cell_vertices[][GeometryInfo<dim>::vertices_per_cell]
    = {{0, 1, 5, 6},
       {1, 2, 6, 7},
       {2, 3, 7, 8},
       {3, 4, 8, 9},
       {5, 6, 10, 11},
       {8, 9, 12, 13},
       {10, 11, 14, 15},
       {12, 13, 17, 18},
       {14, 15, 19, 20},
       {15, 16, 20, 21},
       {16, 17, 21, 22},
       {17, 18, 22, 23}};
  const unsigned int
    n_cells = sizeof(cell_vertices) / sizeof(cell_vertices[0]);

  std::vector<CellData<dim> > cells (n_cells, CellData<dim>());
  for (unsigned int i=0; i<n_cells; ++i)
    {
      for (unsigned int j=0;
           j<GeometryInfo<dim>::vertices_per_cell;
           ++j)
        cells[i].vertices[j] = cell_vertices[i][j];
      cells[i].material_id = 0;
    }

  coarse_grid.create_triangulation (vertices,
                                    cells,
                                    SubCellData());
  coarse_grid.refine_global (1);
}

template <int dim>
void LaplaceProblem<dim>::run ()
{
  for (unsigned int cycle=0; cycle<5; ++cycle)
    {
      std::cout << "Cycle " << cycle << ':' << std::endl;

      if (cycle == 0)
	create_coarse_grid (triangulation);
      else
	refine_grid ();

      std::cout << "   Number of active cells:       "
		<< triangulation.n_active_cells()
		<< std::endl;

      setup_system ();

      std::cout << "   Number of degrees of freedom: "
		<< dof_handler.n_dofs()
		<< std::endl;

      assemble_system ();
      solve ();
      output_results (cycle);
    }
}

int main ()
{
  try
    {
      deallog.depth_console (0);

      LaplaceProblem<2> laplace_problem_2d;
      laplace_problem_2d.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>// Copyright 2008, Google Inc. All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
//  1. Redistributions of source code must retain the above copyright notice,
//     this list of conditions and the following disclaimer.
//  2. Redistributions in binary form must reproduce the above copyright notice,
//     this list of conditions and the following disclaimer in the documentation
//     and/or other materials provided with the distribution.
//  3. Neither the name of Google Inc. nor the names of its contributors may be
//     used to endorse or promote products derived from this software without
//     specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
// WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
// MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
// EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
// OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
// WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
// OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
// ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

#include "kml/base/time_util.h"
#include <cstddef>  // NULL
#ifdef WIN32
#include <windows.h>
#include <winsock2.h>
#include <time.h>
#else
#include <sys/time.h>
#endif

namespace kmlbase {

#ifdef WIN32
// http://forums.msdn.microsoft.com/en/vcgeneral/thread/430449b3-f6dd-4e18-84de-eebd26a8d668/
#if defined(_MSC_VER) || defined(_MSC_EXTENSIONS)
#define DELTA_EPOCH_IN_MICROSECS  11644473600000000Ui64
#else
#define DELTA_EPOCH_IN_MICROSECS  11644473600000000ULL
#endif
//
void gettimeofday(struct timeval* tv, void *) {
  FILETIME file_time;
  GetSystemTimeAsFileTime(&file_time);

  // First covert file_time to a single 64 bit value.
  unsigned __int64 file_time64 = 0;
  file_time64 |= file_time.dwHighDateTime;
  file_time64 <<= 32;
  file_time64 |= file_time.dwLowDateTime;

  /* Now convert file_time64 to unix time. */
  file_time64 /= 10;  /* Convert into microseconds. */
  file_time64 -= DELTA_EPOCH_IN_MICROSECS;
  tv->tv_sec = (long)(file_time64 / 1000000UL);
  tv->tv_usec = (long)(file_time64 % 1000000UL);
}
#endif

// This is here because Windows has no gettimeofday().
double GetMicroTime() {
  struct timeval now_tv;
  gettimeofday(&now_tv, NULL);
  // Make this one double with secs.microseconds.
  return (double)now_tv.tv_sec + (double)now_tv.tv_usec/1000000;
}

}  // end namespace kmlbase
<commit_msg>BUG: KML bug correction on Windows platform (redefinition of fd_set, etc... structures). Replace #include <winsock2.h> by #include <winsock.h> Bug reported on libkml google.<commit_after>// Copyright 2008, Google Inc. All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
//  1. Redistributions of source code must retain the above copyright notice,
//     this list of conditions and the following disclaimer.
//  2. Redistributions in binary form must reproduce the above copyright notice,
//     this list of conditions and the following disclaimer in the documentation
//     and/or other materials provided with the distribution.
//  3. Neither the name of Google Inc. nor the names of its contributors may be
//     used to endorse or promote products derived from this software without
//     specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
// WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
// MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
// EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
// OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
// WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
// OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
// ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

#include "kml/base/time_util.h"
#include <cstddef>  // NULL
#ifdef WIN32
#include <windows.h>
// OTB Modifications (bug reported on libkml google issues
//#include <winsock2.h>
#include <winsock.h>
#include <time.h>
#else
#include <sys/time.h>
#endif

namespace kmlbase {

#ifdef WIN32
// http://forums.msdn.microsoft.com/en/vcgeneral/thread/430449b3-f6dd-4e18-84de-eebd26a8d668/
#if defined(_MSC_VER) || defined(_MSC_EXTENSIONS)
#define DELTA_EPOCH_IN_MICROSECS  11644473600000000Ui64
#else
#define DELTA_EPOCH_IN_MICROSECS  11644473600000000ULL
#endif
//
void gettimeofday(struct timeval* tv, void *) {
  FILETIME file_time;
  GetSystemTimeAsFileTime(&file_time);

  // First covert file_time to a single 64 bit value.
  unsigned __int64 file_time64 = 0;
  file_time64 |= file_time.dwHighDateTime;
  file_time64 <<= 32;
  file_time64 |= file_time.dwLowDateTime;

  /* Now convert file_time64 to unix time. */
  file_time64 /= 10;  /* Convert into microseconds. */
  file_time64 -= DELTA_EPOCH_IN_MICROSECS;
  tv->tv_sec = (long)(file_time64 / 1000000UL);
  tv->tv_usec = (long)(file_time64 % 1000000UL);
}
#endif

// This is here because Windows has no gettimeofday().
double GetMicroTime() {
  struct timeval now_tv;
  gettimeofday(&now_tv, NULL);
  // Make this one double with secs.microseconds.
  return (double)now_tv.tv_sec + (double)now_tv.tv_usec/1000000;
}

}  // end namespace kmlbase
<|endoftext|>


<commit_before>//===-- MachineInstr.cpp --------------------------------------------------===//
//
//                     The LLVM Compiler Infrastructure
//
// This file was developed by the LLVM research group and is distributed under
// the University of Illinois Open Source License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// Methods common to all machine instructions.
//
// FIXME: Now that MachineInstrs have parent pointers, they should always
// print themselves using their MachineFunction's TargetMachine.
//
//===----------------------------------------------------------------------===//

#include "llvm/CodeGen/MachineInstr.h"
#include "llvm/CodeGen/MachineFunction.h"
#include "llvm/Value.h"
#include "llvm/Target/TargetMachine.h"
#include "llvm/Target/TargetInstrInfo.h"
#include "llvm/Target/MRegisterInfo.h"
#include "llvm/Support/LeakDetector.h"
#include <iostream>

using namespace llvm;

// Global variable holding an array of descriptors for machine instructions.
// The actual object needs to be created separately for each target machine.
// This variable is initialized and reset by class TargetInstrInfo.
//
// FIXME: This should be a property of the target so that more than one target
// at a time can be active...
//
namespace llvm {
  extern const TargetInstrDescriptor *TargetInstrDescriptors;
}

// Constructor for instructions with variable #operands
MachineInstr::MachineInstr(short opcode, unsigned numOperands)
  : Opcode(opcode),
    operands(numOperands, MachineOperand()),
    parent(0) {
  // Make sure that we get added to a machine basicblock
  LeakDetector::addGarbageObject(this);
}

/// MachineInstr ctor - This constructor only does a _reserve_ of the operands,
/// not a resize for them.  It is expected that if you use this that you call
/// add* methods below to fill up the operands, instead of the Set methods.
/// Eventually, the "resizing" ctors will be phased out.
///
MachineInstr::MachineInstr(short opcode, unsigned numOperands, bool XX, bool YY)
  : Opcode(opcode), parent(0) {
  operands.reserve(numOperands);
  // Make sure that we get added to a machine basicblock
  LeakDetector::addGarbageObject(this);
}

/// MachineInstr ctor - Work exactly the same as the ctor above, except that the
/// MachineInstr is created and added to the end of the specified basic block.
///
MachineInstr::MachineInstr(MachineBasicBlock *MBB, short opcode,
                           unsigned numOperands)
  : Opcode(opcode), parent(0) {
  assert(MBB && "Cannot use inserting ctor with null basic block!");
  operands.reserve(numOperands);
  // Make sure that we get added to a machine basicblock
  LeakDetector::addGarbageObject(this);
  MBB->push_back(this);  // Add instruction to end of basic block!
}

/// MachineInstr ctor - Copies MachineInstr arg exactly
///
MachineInstr::MachineInstr(const MachineInstr &MI) {
  Opcode = MI.getOpcode();
  operands.reserve(MI.getNumOperands());

  // Add operands
  for (unsigned i = 0; i < MI.getNumOperands(); ++i)
    operands.push_back(MachineOperand(MI.getOperand(i)));

  // Set parent, next, and prev to null
  parent = 0;
  prev = 0;
  next = 0;
}

MachineInstr::~MachineInstr() {
  LeakDetector::removeGarbageObject(this);
}

/// clone - Create a copy of 'this' instruction that is identical in all ways
/// except the following: the new instruction has no parent and it has no name
///
MachineInstr* MachineInstr::clone() const {
  return new MachineInstr(*this);
}

/// removeFromParent - This method unlinks 'this' from the containing basic
/// block, and returns it, but does not delete it.
MachineInstr *MachineInstr::removeFromParent() {
  assert(getParent() && "Not embedded in a basic block!");
  getParent()->remove(this);
  return this;
}

/// OperandComplete - Return true if it's illegal to add a new operand
///
bool MachineInstr::OperandsComplete() const {
  int NumOperands = TargetInstrDescriptors[Opcode].numOperands;
  if (NumOperands >= 0 && getNumOperands() >= (unsigned)NumOperands)
    return true;  // Broken: we have all the operands of this instruction!
  return false;
}

void MachineInstr::SetMachineOperandVal(unsigned i,
                                        MachineOperand::MachineOperandType opTy,
                                        Value* V) {
  assert(i < operands.size());          // may be explicit or implicit op
  operands[i].opType = opTy;
  operands[i].contents.value = V;
  operands[i].extra.regNum = -1;
}

void
MachineInstr::SetMachineOperandConst(unsigned i,
                                     MachineOperand::MachineOperandType opTy,
                                     int intValue) {
  assert(i < getNumOperands());          // must be explicit op
  assert(TargetInstrDescriptors[Opcode].resultPos != (int) i &&
         "immed. constant cannot be defined");

  operands[i].opType = opTy;
  operands[i].contents.value = NULL;
  operands[i].contents.immedVal = intValue;
  operands[i].extra.regNum = -1;
  operands[i].flags = 0;
}

void MachineInstr::SetMachineOperandReg(unsigned i, int regNum) {
  assert(i < getNumOperands());          // must be explicit op

  operands[i].opType = MachineOperand::MO_MachineRegister;
  operands[i].contents.value = NULL;
  operands[i].extra.regNum = regNum;
}

void MachineInstr::dump() const {
  std::cerr << "  " << *this;
}

static inline std::ostream& OutputValue(std::ostream &os, const Value* val) {
  os << "(val ";
  os << (void*) val;                // print address always
  if (val && val->hasName())
    os << " " << val->getName();    // print name also, if available
  os << ")";
  return os;
}

static inline void OutputReg(std::ostream &os, unsigned RegNo,
                             const MRegisterInfo *MRI = 0) {
  if (!RegNo || MRegisterInfo::isPhysicalRegister(RegNo)) {
    if (MRI)
      os << "%" << MRI->get(RegNo).Name;
    else
      os << "%mreg(" << RegNo << ")";
  } else
    os << "%reg" << RegNo;
}

static void print(const MachineOperand &MO, std::ostream &OS,
                  const TargetMachine *TM) {
  const MRegisterInfo *MRI = 0;

  if (TM) MRI = TM->getRegisterInfo();

  bool CloseParen = true;
  if (MO.isHiBits32())
    OS << "%lm(";
  else if (MO.isLoBits32())
    OS << "%lo(";
  else if (MO.isHiBits64())
    OS << "%hh(";
  else if (MO.isLoBits64())
    OS << "%hm(";
  else
    CloseParen = false;

  switch (MO.getType()) {
  case MachineOperand::MO_VirtualRegister:
    if (MO.getVRegValue()) {
      OS << "%reg";
      OutputValue(OS, MO.getVRegValue());
      if (MO.hasAllocatedReg())
        OS << "==";
    }
    if (MO.hasAllocatedReg())
      OutputReg(OS, MO.getReg(), MRI);
    break;
  case MachineOperand::MO_CCRegister:
    OS << "%ccreg";
    OutputValue(OS, MO.getVRegValue());
    if (MO.hasAllocatedReg()) {
      OS << "==";
      OutputReg(OS, MO.getReg(), MRI);
    }
    break;
  case MachineOperand::MO_MachineRegister:
    OutputReg(OS, MO.getMachineRegNum(), MRI);
    break;
  case MachineOperand::MO_SignExtendedImmed:
    OS << (long)MO.getImmedValue();
    break;
  case MachineOperand::MO_UnextendedImmed:
    OS << (long)MO.getImmedValue();
    break;
  case MachineOperand::MO_PCRelativeDisp: {
    const Value* opVal = MO.getVRegValue();
    bool isLabel = isa<Function>(opVal) || isa<BasicBlock>(opVal);
    OS << "%disp(" << (isLabel? "label " : "addr-of-val ");
    if (opVal->hasName())
      OS << opVal->getName();
    else
      OS << (const void*) opVal;
    OS << ")";
    break;
  }
  case MachineOperand::MO_MachineBasicBlock:
    OS << "mbb<"
       << ((Value*)MO.getMachineBasicBlock()->getBasicBlock())->getName()
       << "," << (void*)MO.getMachineBasicBlock() << ">";
    break;
  case MachineOperand::MO_FrameIndex:
    OS << "<fi#" << MO.getFrameIndex() << ">";
    break;
  case MachineOperand::MO_ConstantPoolIndex:
    OS << "<cp#" << MO.getConstantPoolIndex() << ">";
    break;
  case MachineOperand::MO_GlobalAddress:
    OS << "<ga:" << ((Value*)MO.getGlobal())->getName();
    if (MO.getOffset()) OS << "+" << MO.getOffset();
    OS << ">";
    break;
  case MachineOperand::MO_ExternalSymbol:
    OS << "<es:" << MO.getSymbolName();
    if (MO.getOffset()) OS << "+" << MO.getOffset();
    OS << ">";
    break;
  default:
    assert(0 && "Unrecognized operand type");
  }

  if (CloseParen)
    OS << ")";
}

void MachineInstr::print(std::ostream &OS, const TargetMachine *TM) const {
  unsigned StartOp = 0;

   // Specialize printing if op#0 is definition
  if (getNumOperands() && getOperand(0).isDef() && !getOperand(0).isUse()) {
    ::print(getOperand(0), OS, TM);
    OS << " = ";
    ++StartOp;   // Don't print this operand again!
  }

  // Must check if Target machine is not null because machine BB could not
  // be attached to a Machine function yet
  if (TM)
    OS << TM->getInstrInfo()->getName(getOpcode());

  for (unsigned i = StartOp, e = getNumOperands(); i != e; ++i) {
    const MachineOperand& mop = getOperand(i);
    if (i != StartOp)
      OS << ",";
    OS << " ";
    ::print(mop, OS, TM);

    if (mop.isDef())
      if (mop.isUse())
        OS << "<def&use>";
      else
        OS << "<def>";
  }

  OS << "\n";
}

namespace llvm {
std::ostream &operator<<(std::ostream &os, const MachineInstr &MI) {
  // If the instruction is embedded into a basic block, we can find the target
  // info for the instruction.
  if (const MachineBasicBlock *MBB = MI.getParent()) {
    const MachineFunction *MF = MBB->getParent();
    if (MF)
      MI.print(os, &MF->getTarget());
    else
      MI.print(os, 0);
    return os;
  }

  // Otherwise, print it out in the "raw" format without symbolic register names
  // and such.
  os << TargetInstrDescriptors[MI.getOpcode()].Name;

  for (unsigned i = 0, N = MI.getNumOperands(); i < N; i++) {
    os << "\t" << MI.getOperand(i);
    if (MI.getOperand(i).isDef())
      if (MI.getOperand(i).isUse())
        os << "<d&u>";
      else
        os << "<d>";
  }

  return os << "\n";
}

std::ostream &operator<<(std::ostream &OS, const MachineOperand &MO) {
  if (MO.isHiBits32())
    OS << "%lm(";
  else if (MO.isLoBits32())
    OS << "%lo(";
  else if (MO.isHiBits64())
    OS << "%hh(";
  else if (MO.isLoBits64())
    OS << "%hm(";

  switch (MO.getType()) {
  case MachineOperand::MO_VirtualRegister:
    if (MO.hasAllocatedReg())
      OutputReg(OS, MO.getReg());

    if (MO.getVRegValue()) {
      if (MO.hasAllocatedReg()) OS << "==";
      OS << "%vreg";
      OutputValue(OS, MO.getVRegValue());
    }
    break;
  case MachineOperand::MO_CCRegister:
    OS << "%ccreg";
    OutputValue(OS, MO.getVRegValue());
    if (MO.hasAllocatedReg()) {
      OS << "==";
      OutputReg(OS, MO.getReg());
    }
    break;
  case MachineOperand::MO_MachineRegister:
    OutputReg(OS, MO.getMachineRegNum());
    break;
  case MachineOperand::MO_SignExtendedImmed:
    OS << (long)MO.getImmedValue();
    break;
  case MachineOperand::MO_UnextendedImmed:
    OS << (long)MO.getImmedValue();
    break;
  case MachineOperand::MO_PCRelativeDisp: {
    const Value* opVal = MO.getVRegValue();
    bool isLabel = isa<Function>(opVal) || isa<BasicBlock>(opVal);
    OS << "%disp(" << (isLabel? "label " : "addr-of-val ");
    if (opVal->hasName())
      OS << opVal->getName();
    else
      OS << (const void*) opVal;
    OS << ")";
    break;
  }
  case MachineOperand::MO_MachineBasicBlock:
    OS << "<mbb:"
       << ((Value*)MO.getMachineBasicBlock()->getBasicBlock())->getName()
       << "@" << (void*)MO.getMachineBasicBlock() << ">";
    break;
  case MachineOperand::MO_FrameIndex:
    OS << "<fi#" << MO.getFrameIndex() << ">";
    break;
  case MachineOperand::MO_ConstantPoolIndex:
    OS << "<cp#" << MO.getConstantPoolIndex() << ">";
    break;
  case MachineOperand::MO_GlobalAddress:
    OS << "<ga:" << ((Value*)MO.getGlobal())->getName() << ">";
    break;
  case MachineOperand::MO_ExternalSymbol:
    OS << "<es:" << MO.getSymbolName() << ">";
    break;
  default:
    assert(0 && "Unrecognized operand type");
    break;
  }

  if (MO.isHiBits32() || MO.isLoBits32() || MO.isHiBits64() || MO.isLoBits64())
    OS << ")";

  return OS;
}

}
<commit_msg>This field no longer exists<commit_after>//===-- MachineInstr.cpp --------------------------------------------------===//
//
//                     The LLVM Compiler Infrastructure
//
// This file was developed by the LLVM research group and is distributed under
// the University of Illinois Open Source License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// Methods common to all machine instructions.
//
// FIXME: Now that MachineInstrs have parent pointers, they should always
// print themselves using their MachineFunction's TargetMachine.
//
//===----------------------------------------------------------------------===//

#include "llvm/CodeGen/MachineInstr.h"
#include "llvm/CodeGen/MachineFunction.h"
#include "llvm/Value.h"
#include "llvm/Target/TargetMachine.h"
#include "llvm/Target/TargetInstrInfo.h"
#include "llvm/Target/MRegisterInfo.h"
#include "llvm/Support/LeakDetector.h"
#include <iostream>

using namespace llvm;

// Global variable holding an array of descriptors for machine instructions.
// The actual object needs to be created separately for each target machine.
// This variable is initialized and reset by class TargetInstrInfo.
//
// FIXME: This should be a property of the target so that more than one target
// at a time can be active...
//
namespace llvm {
  extern const TargetInstrDescriptor *TargetInstrDescriptors;
}

// Constructor for instructions with variable #operands
MachineInstr::MachineInstr(short opcode, unsigned numOperands)
  : Opcode(opcode),
    operands(numOperands, MachineOperand()),
    parent(0) {
  // Make sure that we get added to a machine basicblock
  LeakDetector::addGarbageObject(this);
}

/// MachineInstr ctor - This constructor only does a _reserve_ of the operands,
/// not a resize for them.  It is expected that if you use this that you call
/// add* methods below to fill up the operands, instead of the Set methods.
/// Eventually, the "resizing" ctors will be phased out.
///
MachineInstr::MachineInstr(short opcode, unsigned numOperands, bool XX, bool YY)
  : Opcode(opcode), parent(0) {
  operands.reserve(numOperands);
  // Make sure that we get added to a machine basicblock
  LeakDetector::addGarbageObject(this);
}

/// MachineInstr ctor - Work exactly the same as the ctor above, except that the
/// MachineInstr is created and added to the end of the specified basic block.
///
MachineInstr::MachineInstr(MachineBasicBlock *MBB, short opcode,
                           unsigned numOperands)
  : Opcode(opcode), parent(0) {
  assert(MBB && "Cannot use inserting ctor with null basic block!");
  operands.reserve(numOperands);
  // Make sure that we get added to a machine basicblock
  LeakDetector::addGarbageObject(this);
  MBB->push_back(this);  // Add instruction to end of basic block!
}

/// MachineInstr ctor - Copies MachineInstr arg exactly
///
MachineInstr::MachineInstr(const MachineInstr &MI) {
  Opcode = MI.getOpcode();
  operands.reserve(MI.getNumOperands());

  // Add operands
  for (unsigned i = 0; i < MI.getNumOperands(); ++i)
    operands.push_back(MachineOperand(MI.getOperand(i)));

  // Set parent, next, and prev to null
  parent = 0;
  prev = 0;
  next = 0;
}

MachineInstr::~MachineInstr() {
  LeakDetector::removeGarbageObject(this);
}

/// clone - Create a copy of 'this' instruction that is identical in all ways
/// except the following: the new instruction has no parent and it has no name
///
MachineInstr* MachineInstr::clone() const {
  return new MachineInstr(*this);
}

/// removeFromParent - This method unlinks 'this' from the containing basic
/// block, and returns it, but does not delete it.
MachineInstr *MachineInstr::removeFromParent() {
  assert(getParent() && "Not embedded in a basic block!");
  getParent()->remove(this);
  return this;
}

/// OperandComplete - Return true if it's illegal to add a new operand
///
bool MachineInstr::OperandsComplete() const {
  int NumOperands = TargetInstrDescriptors[Opcode].numOperands;
  if (NumOperands >= 0 && getNumOperands() >= (unsigned)NumOperands)
    return true;  // Broken: we have all the operands of this instruction!
  return false;
}

void MachineInstr::SetMachineOperandVal(unsigned i,
                                        MachineOperand::MachineOperandType opTy,
                                        Value* V) {
  assert(i < operands.size());          // may be explicit or implicit op
  operands[i].opType = opTy;
  operands[i].contents.value = V;
  operands[i].extra.regNum = -1;
}

void
MachineInstr::SetMachineOperandConst(unsigned i,
                                     MachineOperand::MachineOperandType opTy,
                                     int intValue) {
  assert(i < getNumOperands());          // must be explicit op

  operands[i].opType = opTy;
  operands[i].contents.value = NULL;
  operands[i].contents.immedVal = intValue;
  operands[i].extra.regNum = -1;
  operands[i].flags = 0;
}

void MachineInstr::SetMachineOperandReg(unsigned i, int regNum) {
  assert(i < getNumOperands());          // must be explicit op

  operands[i].opType = MachineOperand::MO_MachineRegister;
  operands[i].contents.value = NULL;
  operands[i].extra.regNum = regNum;
}

void MachineInstr::dump() const {
  std::cerr << "  " << *this;
}

static inline std::ostream& OutputValue(std::ostream &os, const Value* val) {
  os << "(val ";
  os << (void*) val;                // print address always
  if (val && val->hasName())
    os << " " << val->getName();    // print name also, if available
  os << ")";
  return os;
}

static inline void OutputReg(std::ostream &os, unsigned RegNo,
                             const MRegisterInfo *MRI = 0) {
  if (!RegNo || MRegisterInfo::isPhysicalRegister(RegNo)) {
    if (MRI)
      os << "%" << MRI->get(RegNo).Name;
    else
      os << "%mreg(" << RegNo << ")";
  } else
    os << "%reg" << RegNo;
}

static void print(const MachineOperand &MO, std::ostream &OS,
                  const TargetMachine *TM) {
  const MRegisterInfo *MRI = 0;

  if (TM) MRI = TM->getRegisterInfo();

  bool CloseParen = true;
  if (MO.isHiBits32())
    OS << "%lm(";
  else if (MO.isLoBits32())
    OS << "%lo(";
  else if (MO.isHiBits64())
    OS << "%hh(";
  else if (MO.isLoBits64())
    OS << "%hm(";
  else
    CloseParen = false;

  switch (MO.getType()) {
  case MachineOperand::MO_VirtualRegister:
    if (MO.getVRegValue()) {
      OS << "%reg";
      OutputValue(OS, MO.getVRegValue());
      if (MO.hasAllocatedReg())
        OS << "==";
    }
    if (MO.hasAllocatedReg())
      OutputReg(OS, MO.getReg(), MRI);
    break;
  case MachineOperand::MO_CCRegister:
    OS << "%ccreg";
    OutputValue(OS, MO.getVRegValue());
    if (MO.hasAllocatedReg()) {
      OS << "==";
      OutputReg(OS, MO.getReg(), MRI);
    }
    break;
  case MachineOperand::MO_MachineRegister:
    OutputReg(OS, MO.getMachineRegNum(), MRI);
    break;
  case MachineOperand::MO_SignExtendedImmed:
    OS << (long)MO.getImmedValue();
    break;
  case MachineOperand::MO_UnextendedImmed:
    OS << (long)MO.getImmedValue();
    break;
  case MachineOperand::MO_PCRelativeDisp: {
    const Value* opVal = MO.getVRegValue();
    bool isLabel = isa<Function>(opVal) || isa<BasicBlock>(opVal);
    OS << "%disp(" << (isLabel? "label " : "addr-of-val ");
    if (opVal->hasName())
      OS << opVal->getName();
    else
      OS << (const void*) opVal;
    OS << ")";
    break;
  }
  case MachineOperand::MO_MachineBasicBlock:
    OS << "mbb<"
       << ((Value*)MO.getMachineBasicBlock()->getBasicBlock())->getName()
       << "," << (void*)MO.getMachineBasicBlock() << ">";
    break;
  case MachineOperand::MO_FrameIndex:
    OS << "<fi#" << MO.getFrameIndex() << ">";
    break;
  case MachineOperand::MO_ConstantPoolIndex:
    OS << "<cp#" << MO.getConstantPoolIndex() << ">";
    break;
  case MachineOperand::MO_GlobalAddress:
    OS << "<ga:" << ((Value*)MO.getGlobal())->getName();
    if (MO.getOffset()) OS << "+" << MO.getOffset();
    OS << ">";
    break;
  case MachineOperand::MO_ExternalSymbol:
    OS << "<es:" << MO.getSymbolName();
    if (MO.getOffset()) OS << "+" << MO.getOffset();
    OS << ">";
    break;
  default:
    assert(0 && "Unrecognized operand type");
  }

  if (CloseParen)
    OS << ")";
}

void MachineInstr::print(std::ostream &OS, const TargetMachine *TM) const {
  unsigned StartOp = 0;

   // Specialize printing if op#0 is definition
  if (getNumOperands() && getOperand(0).isDef() && !getOperand(0).isUse()) {
    ::print(getOperand(0), OS, TM);
    OS << " = ";
    ++StartOp;   // Don't print this operand again!
  }

  // Must check if Target machine is not null because machine BB could not
  // be attached to a Machine function yet
  if (TM)
    OS << TM->getInstrInfo()->getName(getOpcode());

  for (unsigned i = StartOp, e = getNumOperands(); i != e; ++i) {
    const MachineOperand& mop = getOperand(i);
    if (i != StartOp)
      OS << ",";
    OS << " ";
    ::print(mop, OS, TM);

    if (mop.isDef())
      if (mop.isUse())
        OS << "<def&use>";
      else
        OS << "<def>";
  }

  OS << "\n";
}

namespace llvm {
std::ostream &operator<<(std::ostream &os, const MachineInstr &MI) {
  // If the instruction is embedded into a basic block, we can find the target
  // info for the instruction.
  if (const MachineBasicBlock *MBB = MI.getParent()) {
    const MachineFunction *MF = MBB->getParent();
    if (MF)
      MI.print(os, &MF->getTarget());
    else
      MI.print(os, 0);
    return os;
  }

  // Otherwise, print it out in the "raw" format without symbolic register names
  // and such.
  os << TargetInstrDescriptors[MI.getOpcode()].Name;

  for (unsigned i = 0, N = MI.getNumOperands(); i < N; i++) {
    os << "\t" << MI.getOperand(i);
    if (MI.getOperand(i).isDef())
      if (MI.getOperand(i).isUse())
        os << "<d&u>";
      else
        os << "<d>";
  }

  return os << "\n";
}

std::ostream &operator<<(std::ostream &OS, const MachineOperand &MO) {
  if (MO.isHiBits32())
    OS << "%lm(";
  else if (MO.isLoBits32())
    OS << "%lo(";
  else if (MO.isHiBits64())
    OS << "%hh(";
  else if (MO.isLoBits64())
    OS << "%hm(";

  switch (MO.getType()) {
  case MachineOperand::MO_VirtualRegister:
    if (MO.hasAllocatedReg())
      OutputReg(OS, MO.getReg());

    if (MO.getVRegValue()) {
      if (MO.hasAllocatedReg()) OS << "==";
      OS << "%vreg";
      OutputValue(OS, MO.getVRegValue());
    }
    break;
  case MachineOperand::MO_CCRegister:
    OS << "%ccreg";
    OutputValue(OS, MO.getVRegValue());
    if (MO.hasAllocatedReg()) {
      OS << "==";
      OutputReg(OS, MO.getReg());
    }
    break;
  case MachineOperand::MO_MachineRegister:
    OutputReg(OS, MO.getMachineRegNum());
    break;
  case MachineOperand::MO_SignExtendedImmed:
    OS << (long)MO.getImmedValue();
    break;
  case MachineOperand::MO_UnextendedImmed:
    OS << (long)MO.getImmedValue();
    break;
  case MachineOperand::MO_PCRelativeDisp: {
    const Value* opVal = MO.getVRegValue();
    bool isLabel = isa<Function>(opVal) || isa<BasicBlock>(opVal);
    OS << "%disp(" << (isLabel? "label " : "addr-of-val ");
    if (opVal->hasName())
      OS << opVal->getName();
    else
      OS << (const void*) opVal;
    OS << ")";
    break;
  }
  case MachineOperand::MO_MachineBasicBlock:
    OS << "<mbb:"
       << ((Value*)MO.getMachineBasicBlock()->getBasicBlock())->getName()
       << "@" << (void*)MO.getMachineBasicBlock() << ">";
    break;
  case MachineOperand::MO_FrameIndex:
    OS << "<fi#" << MO.getFrameIndex() << ">";
    break;
  case MachineOperand::MO_ConstantPoolIndex:
    OS << "<cp#" << MO.getConstantPoolIndex() << ">";
    break;
  case MachineOperand::MO_GlobalAddress:
    OS << "<ga:" << ((Value*)MO.getGlobal())->getName() << ">";
    break;
  case MachineOperand::MO_ExternalSymbol:
    OS << "<es:" << MO.getSymbolName() << ">";
    break;
  default:
    assert(0 && "Unrecognized operand type");
    break;
  }

  if (MO.isHiBits32() || MO.isLoBits32() || MO.isHiBits64() || MO.isLoBits64())
    OS << ")";

  return OS;
}

}
<|endoftext|>


<commit_before>#include "pixelboost/graphics/camera/camera.h"
#include "pixelboost/graphics/camera/viewport.h"
#include "pixelboost/graphics/renderer/common/renderable.h"
#include "pixelboost/graphics/renderer/common/renderer.h"
#include "pixelboost/logic/system/graphics/render/distance.h"

using namespace pb;

DistanceRenderSystem::DistanceRenderSystem(float distance)
    : _Distance(distance)
{

}

Uid DistanceRenderSystem::GetStaticType()
{
    return RenderSystem::GetStaticType();
}

void DistanceRenderSystem::Render(Scene* scene, Viewport* viewport)
{
    glm::vec3 cameraPosition = viewport->GetCamera()->Position;
    cameraPosition.z = 0;

    for (RenderableSet::iterator it = _Renderables.begin(); it != _Renderables.end(); ++it)
    {
        glm::vec4 position = (*it)->GetWorldMatrix()[3];

        if (glm::distance(cameraPosition, glm::vec3(position.x, position.y, 0)) < _Distance)
            RenderItem(*it);
    }
}

void DistanceRenderSystem::AddItem(Renderable* renderable)
{
    _Renderables.insert(renderable);
}

void DistanceRenderSystem::RemoveItem(Renderable* renderable)
{
    _Renderables.erase(renderable);
}
<commit_msg>Fix issue with particles not appearing with distance render system<commit_after>#include "pixelboost/graphics/camera/camera.h"
#include "pixelboost/graphics/camera/viewport.h"
#include "pixelboost/graphics/renderer/common/renderable.h"
#include "pixelboost/graphics/renderer/common/renderer.h"
#include "pixelboost/logic/system/graphics/render/distance.h"

using namespace pb;

DistanceRenderSystem::DistanceRenderSystem(float distance)
    : _Distance(distance)
{

}

Uid DistanceRenderSystem::GetStaticType()
{
    return RenderSystem::GetStaticType();
}

void DistanceRenderSystem::Render(Scene* scene, Viewport* viewport)
{
    glm::vec3 cameraPosition = viewport->GetCamera()->Position;
    cameraPosition.z = 0;

    for (RenderableSet::iterator it = _Renderables.begin(); it != _Renderables.end(); ++it)
    {
        glm::vec4 position = (*it)->GetWorldMatrix()[3];

        if ((*it)->GetRenderableType() == TypeHash("particle")|| glm::distance(cameraPosition, glm::vec3(position.x, position.y, 0)) < _Distance)
            RenderItem(*it);
    }
}

void DistanceRenderSystem::AddItem(Renderable* renderable)
{
    _Renderables.insert(renderable);
}

void DistanceRenderSystem::RemoveItem(Renderable* renderable)
{
    _Renderables.erase(renderable);
}
<|endoftext|>


<commit_before>AliAnalysisTask *AddTask_jbook_JPsi(TString config="1",
				    Bool_t gridconf=kFALSE,
				    Bool_t hasMC=kFALSE,
				    ULong64_t triggers=AliVEvent::kCentral | AliVEvent::kSemiCentral | AliVEvent::kMB){

  //get the current analysis manager
  AliAnalysisManager *mgr = AliAnalysisManager::GetAnalysisManager();
  if (!mgr) {
    Error("AddTask_jbook_JPsi", "No analysis manager found.");
    return 0;
  }

  //Do we have an MC handler?
  TString list = gSystem->Getenv("LIST");
  if(!list.IsNull()) {
    if( list.Contains("LHC10h")   || list.Contains("LHC11h")   ) hasMC=kFALSE;
    if( list.Contains("LHC11a10") || list.Contains("LHC12a17") ) hasMC=kTRUE;
  }

  //Do we have an AOD handler?
  Bool_t isAOD=(mgr->GetInputEventHandler()->IsA()==AliAODInputHandler::Class() ? kTRUE : kFALSE);

  // set AOD debug levels
  if(isAOD) {
    mgr->AddClassDebug("AliAODTrack", AliLog::kFatal);
    mgr->AddClassDebug("AliAODpidUtil", AliLog::kInfo);
  }

  //set config file name
  TString configFile("");
  printf("%s \n",gSystem->pwd());
  TString trainRoot=gSystem->Getenv("TRAIN_ROOT");

  // gsi config
  if (!trainRoot.IsNull())  configFile="$TRAIN_ROOT/jbook_jpsi/ConfigJpsi_jb_PbPb.C";
  // alien config
  else if(!gSystem->Exec("alien_cp alien:///alice/cern.ch/user/j/jbook/PWGDQ/dielectron/macrosJPSI/ConfigJpsi_jb_PbPb.C .")) {
    gSystem->Exec(Form("ls -l %s",gSystem->pwd()));
    configFile=Form("%s/ConfigJpsi_jb_PbPb.C",gSystem->pwd());
  }
  else {
    printf("ERROR: couldn't copy file %s from grid \n",
	   "alien:///alice/cern.ch/user/j/jbook/PWGDQ/dielectron/macrosJPSI/ConfigJpsi_jb_PbPb.C");
    return;
  }

  // aliroot config
  if(!gridconf && trainRoot.IsNull())
    configFile="$ALICE_ROOT/PWGDQ/dielectron/macrosJPSI/ConfigJpsi_jb_PbPb.C"; // aliroot config

  //create task
  AliAnalysisTaskMultiDielectron *task;

  // trigger selection
  ULong64_t triggerSets[]={AliVEvent::kCentral , AliVEvent::kSemiCentral , AliVEvent::kMB,
			   AliVEvent::kCentral | AliVEvent::kSemiCentral | AliVEvent::kMB};
  const char* triggerNames[]={"Central","SemiCentral","MB","ALL"};
  const char* onlineRejection[]={"","CCENT","",""};

  // find out the configured triggers
  Int_t j=0;
  for(j=0; j<4; j++) {
    if(triggers!=triggerSets[j]) continue;
    else break;
  }

  // print overall configuration
  printf("production: %s MC: %d \n",  list.Data(),hasMC);
  printf("triggers:   %s \n",         triggerNames[j]  );
  printf("config:     %s Grid: %d \n",configFile.Data(),gridconf);

  //load dielectron configuration file (only once)
  TString checkconfig="ConfigJpsi_jb_PbPb";
  if (!gROOT->GetListOfGlobalFunctions()->FindObject(checkconfig.Data()))
    gROOT->LoadMacro(configFile.Data());

  //define default output container
  TString containerName = "JPSI.root";

  //add dielectron analysis with different cuts to the task
  for (Int_t i=0; i<nDie; ++i) { //nDie defined in config file

    //only configs switched ON will pass
    if(config.Length()<=i || config(i,1)!="1") { printf(" %d switched OFF \n",i); continue; }

    // load configuration
    AliDielectron *jpsi=ConfigJpsi_jb_PbPb(i,hasMC,triggers);
    if(!jpsi) continue;

    // create unique title
    TString unitit = Form("%s_%s",triggerNames[j],jpsi->GetName());

    // create single tasks instead of one multi task (decreasing size of CF container)
    task = new AliAnalysisTaskMultiDielectron(Form("MultiDieJB_%s",unitit.Data()));
    task->SetBeamEnergy(1380.);
    task->SetTriggerMask(triggers);
    if(strlen(onlineRejection[j])) task->SetFiredTriggerName(onlineRejection[j],kTRUE);
    if(!hasMC) task->UsePhysicsSelection();

    // add dielectron to the task and manager
    task->AddDielectron(jpsi);
    mgr->AddTask(task);

    //create output sub containers
    AliAnalysisDataContainer *cOutputHist1 =
      mgr->CreateContainer(Form("jbook_QA_%s",unitit.Data()),
			   TList::Class(),
			   AliAnalysisManager::kOutputContainer,
			   containerName.Data());

    AliAnalysisDataContainer *cOutputHist2 =
      mgr->CreateContainer(Form("jbook_CF_%s",unitit.Data()),
			   TList::Class(),
			   AliAnalysisManager::kOutputContainer,
			   containerName.Data());

    AliAnalysisDataContainer *cOutputHist3 =
      mgr->CreateContainer(Form("jbook_EventStat_%s",unitit.Data()),
			   TH1D::Class(),
			   AliAnalysisManager::kOutputContainer,
			   containerName.Data());

    mgr->ConnectInput(task,  0, mgr->GetCommonInputContainer());
    //  mgr->ConnectOutput(task, 0, coutput1 );
    mgr->ConnectOutput(task, 1, cOutputHist1);
    mgr->ConnectOutput(task, 2, cOutputHist2);
    mgr->ConnectOutput(task, 3, cOutputHist3);

    printf(" %s added\n",jpsi->GetName());

  }

  return task;
}
<commit_msg>-update<commit_after>AliAnalysisTask *AddTask_jbook_JPsi(TString config="1",
				    Bool_t gridconf=kFALSE,
				    Bool_t hasMC=kFALSE,
				    ULong64_t triggers=AliVEvent::kCentral | AliVEvent::kSemiCentral | AliVEvent::kMB){

  //get the current analysis manager
  AliAnalysisManager *mgr = AliAnalysisManager::GetAnalysisManager();
  if (!mgr) {
    Error("AddTask_jbook_JPsi", "No analysis manager found.");
    return 0;
  }

  //Do we have an MC handler?
  TString list = gSystem->Getenv("LIST");
  if(!list.IsNull()) {
    if( list.Contains("LHC10h")   || list.Contains("LHC11h")   ) hasMC=kFALSE;
    if( list.Contains("LHC11a10") || list.Contains("LHC12a17") ) hasMC=kTRUE;
  }

  //Do we have an AOD handler?
  Bool_t isAOD=(mgr->GetInputEventHandler()->IsA()==AliAODInputHandler::Class() ? kTRUE : kFALSE);

  // set AOD debug levels
  if(isAOD) {
    mgr->AddClassDebug("AliAODTrack", AliLog::kFatal);
    mgr->AddClassDebug("AliAODpidUtil", AliLog::kInfo);
  }

  //set config file name
  TString configFile("");
  printf("%s \n",gSystem->pwd());
  TString trainRoot=gSystem->Getenv("TRAIN_ROOT");

  // gsi config
  if (!trainRoot.IsNull())  configFile="$TRAIN_ROOT/jbook_jpsi/ConfigJpsi_jb_PbPb.C";
  // alien config
  else if(!gSystem->Exec("alien_cp alien:///alice/cern.ch/user/j/jbook/PWGDQ/dielectron/macrosJPSI/ConfigJpsi_jb_PbPb.C .")) {
    gSystem->Exec(Form("ls -l %s",gSystem->pwd()));
    configFile=Form("%s/ConfigJpsi_jb_PbPb.C",gSystem->pwd());
  }
  else {
    printf("ERROR: couldn't copy file %s from grid \n",
	   "alien:///alice/cern.ch/user/j/jbook/PWGDQ/dielectron/macrosJPSI/ConfigJpsi_jb_PbPb.C");
    return;
  }

  // aliroot config
  if(!gridconf && trainRoot.IsNull())
    configFile="$ALICE_ROOT/PWGDQ/dielectron/macrosJPSI/ConfigJpsi_jb_PbPb.C"; // aliroot config

  //create task
  AliAnalysisTaskMultiDielectron *task;

  // trigger selection
  ULong64_t triggerSets[]={AliVEvent::kCentral , AliVEvent::kSemiCentral , AliVEvent::kMB,
			   AliVEvent::kCentral | AliVEvent::kSemiCentral | AliVEvent::kMB};
  const char* triggerNames[]={"Central","SemiCentral","MB","ALL"};
  const char* onlineRejection[]={"","CCENT","",""};

  // find out the configured triggers
  Int_t j=0;
  for(j=0; j<4; j++) {
    if(triggers!=triggerSets[j]) continue;
    else break;
  }

  // print overall configuration
  printf("production: %s MC: %d \n",  list.Data(),hasMC);
  printf("triggers:   %s \n",         triggerNames[j]  );
  printf("config:     %s Grid: %d \n",configFile.Data(),gridconf);

  //load dielectron configuration file (only once)
  TString checkconfig="ConfigJpsi_jb_PbPb";
  if (!gROOT->GetListOfGlobalFunctions()->FindObject(checkconfig.Data()))
    gROOT->LoadMacro(configFile.Data());

  //define default output container
  TString containerName = "JPSI.root";

  //add dielectron analysis with different cuts to the task
  for (Int_t i=0; i<nDie; ++i) { //nDie defined in config file

    //only configs switched ON will pass
    if(config.Length()<=i || config(i,1)!="1") { printf(" %d switched OFF \n",i); continue; }

    // load configuration
    AliDielectron *jpsi=ConfigJpsi_jb_PbPb(i,hasMC,triggers);
    if(!jpsi) continue;

    // create unique title
    TString unitit = Form("%s_%s",triggerNames[j],jpsi->GetName());

    // create single tasks instead of one multi task (decreasing size of CF container)
    task = new AliAnalysisTaskMultiDielectron(Form("MultiDieJB_%s",unitit.Data()));
    task->SetBeamEnergy(1380.);
    task->SetTriggerMask(triggers);
    if(strlen(onlineRejection[j])) task->SetFiredTriggerName(onlineRejection[j],kTRUE);
    if(!hasMC) task->UsePhysicsSelection();

    // event filter
    AliDielectronEventCuts *eventCuts=new AliDielectronEventCuts("vertex","vertex");
    if(isAOD) eventCuts->SetVertexType(AliDielectronEventCuts::kVtxAny);
    eventCuts->SetRequireVertex();
    eventCuts->SetMinVtxContributors(1);
    eventCuts->SetVertexZ(-10.,+10.);
    eventCuts->SetCentralityRange(0,90.);
    eventCuts->Print();
    task->SetEventFilter(eventCuts);

    // add dielectron to the task and manager
    task->AddDielectron(jpsi);
    mgr->AddTask(task);

    //create output sub containers
    AliAnalysisDataContainer *cOutputHist1 =
      mgr->CreateContainer(Form("jbook_QA_%s",unitit.Data()),
			   TList::Class(),
			   AliAnalysisManager::kOutputContainer,
			   containerName.Data());

    AliAnalysisDataContainer *cOutputHist2 =
      mgr->CreateContainer(Form("jbook_CF_%s",unitit.Data()),
			   TList::Class(),
			   AliAnalysisManager::kOutputContainer,
			   containerName.Data());

    AliAnalysisDataContainer *cOutputHist3 =
      mgr->CreateContainer(Form("jbook_EventStat_%s",unitit.Data()),
			   TH1D::Class(),
			   AliAnalysisManager::kOutputContainer,
			   containerName.Data());

    mgr->ConnectInput(task,  0, mgr->GetCommonInputContainer());
    //  mgr->ConnectOutput(task, 0, coutput1 );
    mgr->ConnectOutput(task, 1, cOutputHist1);
    mgr->ConnectOutput(task, 2, cOutputHist2);
    mgr->ConnectOutput(task, 3, cOutputHist3);

    printf(" %s added\n",jpsi->GetName());

  }

  return task;
}
<|endoftext|>


<commit_before>/*
 * Copyright (c) 2016, Ford Motor Company
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *
 * Redistributions of source code must retain the above copyright notice, this
 * list of conditions and the following disclaimer.
 *
 * Redistributions in binary form must reproduce the above copyright notice,
 * this list of conditions and the following
 * disclaimer in the documentation and/or other materials provided with the
 * distribution.
 *
 * Neither the name of the Ford Motor Company nor the names of its contributors
 * may be used to endorse or promote products derived from this software
 * without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
 * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 * POSSIBILITY OF SUCH DAMAGE.
 */

#include "application_manager/commands/hmi/get_urls.h"
#include "application_manager/message.h"
#include "application_manager/application_manager.h"
#include "application_manager/policies/policy_handler.h"

namespace application_manager {
namespace commands {

GetUrls::GetUrls(const MessageSharedPtr& message,
                 ApplicationManager& application_manager)
    : RequestFromHMI(message, application_manager) {}

GetUrls::~GetUrls() {}

void GetUrls::Run() {
  LOG4CXX_AUTO_TRACE(logger_);
  namespace Common_Result = hmi_apis::Common_Result;
  using policy::EndpointUrls;

  if (!application_manager_.GetPolicyHandler().PolicyEnabled()) {
    SendResponseToHMI(Common_Result::DATA_NOT_AVAILABLE);
    return;
  }

  const uint32_t service_to_check =
      (*message_)[strings::msg_params][hmi_request::service].asUInt();

  EndpointUrls endpoints;
  application_manager_.GetPolicyHandler().GetUpdateUrls(service_to_check,
                                                        endpoints);

  if (endpoints.empty()) {
    LOG4CXX_ERROR(logger_, "No URLs for service " << service_to_check);
    SendResponseToHMI(Common_Result::DATA_NOT_AVAILABLE);
    return;
  }

#ifdef EXTENDED_POLICY
  const uint32_t policy_service = 7;

  if (policy_service == service_to_check) {
    ProcessPolicyServiceURLs(endpoints);
    return;
  }
#endif  // EXTENDED_POLICY

  ProcessServiceURLs(endpoints);
}

void GetUrls::ProcessServiceURLs(const policy::EndpointUrls& endpoints) {
  namespace Common_Result = hmi_apis::Common_Result;
  using smart_objects::SmartObject;

  (*message_)[strings::msg_params].erase(hmi_request::service);
  SmartObject& urls = (*message_)[strings::msg_params][hmi_response::urls];

  size_t index = 0;
  for (size_t e = 0; e < endpoints.size(); ++e) {
    for (size_t u = 0; u < endpoints[e].url.size(); ++u, ++index) {
      const std::string app_url = endpoints[e].url[u];

      SmartObject& service_info = urls[index];

      service_info[strings::url] = app_url;
      if (policy::kDefaultId != endpoints[e].app_id) {
#ifndef EXTENDED_PROPRIETARY
        service_info[hmi_response::policy_app_id] = endpoints[e].app_id;
#else   // EXTENDED_PROPRIETARY
        ApplicationSharedPtr app =
            application_manager_.application_by_policy_id(endpoints[e].app_id);

        if (!app) {
          LOG4CXX_ERROR(logger_,
                        "Can't find application with policy id "
                            << endpoints[e].app_id
                            << " URLs adding for this appliation is skipped.");
          continue;
        }

        service_info[strings::app_id] = app->hmi_app_id();
#endif  // EXTENDED_PROPRIETARY
      }
    }
  }
  SendResponseToHMI(Common_Result::SUCCESS);
}

void GetUrls::SendResponseToHMI(hmi_apis::Common_Result::eType result) {
  (*message_)[strings::params][strings::message_type] = MessageType::kResponse;
  (*message_)[strings::params][hmi_response::code] = result;
  application_manager_.ManageHMICommand(message_);
}

#ifdef EXTENDED_POLICY
struct PolicyAppIdComparator {
  PolicyAppIdComparator(const std::string& policy_app_id)
      : policy_app_id_(policy_app_id) {}

  bool operator()(const policy::EndpointData& data) {
    return data.app_id == policy_app_id_;
  }
  std::string policy_app_id_;
};

void FillSODefaultUrls(smart_objects::SmartObject& urls,
                       const policy::EndpointUrls& endpoints) {
  using smart_objects::SmartObject;
  PolicyAppIdComparator comparator(policy::kDefaultId);
  policy::EndpointUrls::const_iterator it =
      std::find_if(endpoints.begin(), endpoints.end(), comparator);
  if (it == endpoints.end()) {
    return;
  }
  SmartObject service_info = SmartObject(smart_objects::SmartType_Map);
  for (size_t i = 0; i < (*it).url.size(); ++i) {
    service_info[strings::url] = (*it).url[i];
    urls[i] = service_info;
  }
}

void GetUrls::ProcessPolicyServiceURLs(const policy::EndpointUrls& endpoints) {
  LOG4CXX_AUTO_TRACE(logger_);
  using namespace smart_objects;
  using namespace application_manager;
  using namespace strings;
  using namespace hmi_apis;

  const uint32_t app_id_to_send_to =
      application_manager_.GetPolicyHandler().GetAppIdForSending();

  if (!app_id_to_send_to) {
    LOG4CXX_ERROR(logger_,
                  "There are no available applications for processing.");
    SmartObject urls(SmartType_Array);
    FillSODefaultUrls(urls, endpoints);
    if (!urls.empty()) {
      (*message_)[msg_params][hmi_response::urls] = urls;
    }
    (*message_).erase(hmi_request::service);
    SendResponseToHMI(Common_Result::SUCCESS);
    return;
  }

  ApplicationSharedPtr app =
      application_manager_.application(app_id_to_send_to);

  if (!app.valid()) {
    LOG4CXX_WARN(logger_,
                 "There is no registered application with "
                 "connection key '"
                     << app_id_to_send_to << "'");
    SendResponseToHMI(Common_Result::DATA_NOT_AVAILABLE);
    return;
  }

  SmartObject& object = *message_;
  object[msg_params].erase(hmi_request::service);
  object[msg_params][hmi_response::urls] = SmartObject(SmartType_Array);
  SmartObject& urls = object[msg_params][hmi_response::urls];
  const std::string mobile_app_id = app->policy_app_id();
  std::string default_url = "URL is not found";

  // Will use only one URL for particular application if it will be found
  // Otherwise URL from default section will used
  SmartObject service_info = SmartObject(SmartType_Map);

  for (size_t e = 0; e < endpoints.size(); ++e) {
    if (mobile_app_id == endpoints[e].app_id) {
      if (endpoints[e].url.size()) {
        service_info[url] = endpoints[e].url[0];
        SendResponseToHMI(Common_Result::SUCCESS);
        return;
      }
    }
    if (policy::kDefaultId == endpoints[e].app_id) {
      if (endpoints[e].url.size()) {
        default_url = endpoints[e].url[0];
      }
    }
  }

  service_info[strings::app_id] = app->app_id();
  service_info[strings::url] = default_url;
  urls[0] = service_info;
  // TODO(AOleynik): Issue with absent policy_app_id. Need to fix later on.
  // Possibly related to smart schema
  SendResponseToHMI(Common_Result::SUCCESS);
  return;
}
#endif  // EXTENDED_POLICY

}  // namespace commands
}  // namespace application_manager
<commit_msg>Fux int\uint mistmatch<commit_after>/*
 * Copyright (c) 2016, Ford Motor Company
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *
 * Redistributions of source code must retain the above copyright notice, this
 * list of conditions and the following disclaimer.
 *
 * Redistributions in binary form must reproduce the above copyright notice,
 * this list of conditions and the following
 * disclaimer in the documentation and/or other materials provided with the
 * distribution.
 *
 * Neither the name of the Ford Motor Company nor the names of its contributors
 * may be used to endorse or promote products derived from this software
 * without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
 * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 * POSSIBILITY OF SUCH DAMAGE.
 */

#include "application_manager/commands/hmi/get_urls.h"
#include "application_manager/message.h"
#include "application_manager/application_manager.h"
#include "application_manager/policies/policy_handler.h"

namespace application_manager {
namespace commands {

GetUrls::GetUrls(const MessageSharedPtr& message,
                 ApplicationManager& application_manager)
    : RequestFromHMI(message, application_manager) {}

GetUrls::~GetUrls() {}

void GetUrls::Run() {
  LOG4CXX_AUTO_TRACE(logger_);
  namespace Common_Result = hmi_apis::Common_Result;
  using policy::EndpointUrls;

  if (!application_manager_.GetPolicyHandler().PolicyEnabled()) {
    SendResponseToHMI(Common_Result::DATA_NOT_AVAILABLE);
    return;
  }

  const uint32_t service_to_check =
      (*message_)[strings::msg_params][hmi_request::service].asUInt();

  EndpointUrls endpoints;
  application_manager_.GetPolicyHandler().GetUpdateUrls(service_to_check,
                                                        endpoints);

  if (endpoints.empty()) {
    LOG4CXX_ERROR(logger_, "No URLs for service " << service_to_check);
    SendResponseToHMI(Common_Result::DATA_NOT_AVAILABLE);
    return;
  }

#ifdef EXTENDED_POLICY
  const uint32_t policy_service = 7u;

  if (policy_service == service_to_check) {
    ProcessPolicyServiceURLs(endpoints);
    return;
  }
#endif  // EXTENDED_POLICY

  ProcessServiceURLs(endpoints);
}

void GetUrls::ProcessServiceURLs(const policy::EndpointUrls& endpoints) {
  namespace Common_Result = hmi_apis::Common_Result;
  using smart_objects::SmartObject;

  (*message_)[strings::msg_params].erase(hmi_request::service);
  SmartObject& urls = (*message_)[strings::msg_params][hmi_response::urls];

  size_t index = 0;
  for (size_t e = 0; e < endpoints.size(); ++e) {
    for (size_t u = 0; u < endpoints[e].url.size(); ++u, ++index) {
      const std::string app_url = endpoints[e].url[u];

      SmartObject& service_info = urls[index];

      service_info[strings::url] = app_url;
      if (policy::kDefaultId != endpoints[e].app_id) {
#ifndef EXTENDED_PROPRIETARY
        service_info[hmi_response::policy_app_id] = endpoints[e].app_id;
#else   // EXTENDED_PROPRIETARY
        ApplicationSharedPtr app =
            application_manager_.application_by_policy_id(endpoints[e].app_id);

        if (!app) {
          LOG4CXX_ERROR(logger_,
                        "Can't find application with policy id "
                            << endpoints[e].app_id
                            << " URLs adding for this appliation is skipped.");
          continue;
        }

        service_info[strings::app_id] = app->hmi_app_id();
#endif  // EXTENDED_PROPRIETARY
      }
    }
  }
  SendResponseToHMI(Common_Result::SUCCESS);
}

void GetUrls::SendResponseToHMI(hmi_apis::Common_Result::eType result) {
  (*message_)[strings::params][strings::message_type] = MessageType::kResponse;
  (*message_)[strings::params][hmi_response::code] = result;
  application_manager_.ManageHMICommand(message_);
}

#ifdef EXTENDED_POLICY
struct PolicyAppIdComparator {
  PolicyAppIdComparator(const std::string& policy_app_id)
      : policy_app_id_(policy_app_id) {}

  bool operator()(const policy::EndpointData& data) {
    return data.app_id == policy_app_id_;
  }
  std::string policy_app_id_;
};

void FillSODefaultUrls(smart_objects::SmartObject& urls,
                       const policy::EndpointUrls& endpoints) {
  using smart_objects::SmartObject;
  PolicyAppIdComparator comparator(policy::kDefaultId);
  policy::EndpointUrls::const_iterator it =
      std::find_if(endpoints.begin(), endpoints.end(), comparator);
  if (it == endpoints.end()) {
    return;
  }
  SmartObject service_info = SmartObject(smart_objects::SmartType_Map);
  for (size_t i = 0; i < (*it).url.size(); ++i) {
    service_info[strings::url] = (*it).url[i];
    urls[i] = service_info;
  }
}

void GetUrls::ProcessPolicyServiceURLs(const policy::EndpointUrls& endpoints) {
  LOG4CXX_AUTO_TRACE(logger_);
  using namespace smart_objects;
  using namespace application_manager;
  using namespace strings;
  using namespace hmi_apis;

  const uint32_t app_id_to_send_to =
      application_manager_.GetPolicyHandler().GetAppIdForSending();

  if (!app_id_to_send_to) {
    LOG4CXX_ERROR(logger_,
                  "There are no available applications for processing.");
    SmartObject urls(SmartType_Array);
    FillSODefaultUrls(urls, endpoints);
    if (!urls.empty()) {
      (*message_)[msg_params][hmi_response::urls] = urls;
    }
    (*message_).erase(hmi_request::service);
    SendResponseToHMI(Common_Result::SUCCESS);
    return;
  }

  ApplicationSharedPtr app =
      application_manager_.application(app_id_to_send_to);

  if (!app.valid()) {
    LOG4CXX_WARN(logger_,
                 "There is no registered application with "
                 "connection key '"
                     << app_id_to_send_to << "'");
    SendResponseToHMI(Common_Result::DATA_NOT_AVAILABLE);
    return;
  }

  SmartObject& object = *message_;
  object[msg_params].erase(hmi_request::service);
  object[msg_params][hmi_response::urls] = SmartObject(SmartType_Array);
  SmartObject& urls = object[msg_params][hmi_response::urls];
  const std::string mobile_app_id = app->policy_app_id();
  std::string default_url = "URL is not found";

  // Will use only one URL for particular application if it will be found
  // Otherwise URL from default section will used
  SmartObject service_info = SmartObject(SmartType_Map);

  for (size_t e = 0; e < endpoints.size(); ++e) {
    if (mobile_app_id == endpoints[e].app_id) {
      if (endpoints[e].url.size()) {
        service_info[url] = endpoints[e].url[0];
        SendResponseToHMI(Common_Result::SUCCESS);
        return;
      }
    }
    if (policy::kDefaultId == endpoints[e].app_id) {
      if (endpoints[e].url.size()) {
        default_url = endpoints[e].url[0];
      }
    }
  }

  service_info[strings::app_id] = app->app_id();
  service_info[strings::url] = default_url;
  urls[0] = service_info;
  // TODO(AOleynik): Issue with absent policy_app_id. Need to fix later on.
  // Possibly related to smart schema
  SendResponseToHMI(Common_Result::SUCCESS);
  return;
}
#endif  // EXTENDED_POLICY

}  // namespace commands
}  // namespace application_manager
<|endoftext|>


<commit_before>	AliAnalysisPseudoRapidityDensityTemp* AddTaskTemp(const char* taskname, const char* option){

    AliAnalysisManager *mgr = AliAnalysisManager::GetAnalysisManager();
    if (!mgr) {
        return 0x0;
    }
    if (!mgr->GetInputEventHandler()) {
        return 0x0;
    }

		AliAnalysisPseudoRapidityDensityTemp *task = new AliAnalysisPseudoRapidityDensityTemp(taskname, option);
		AliAnalysisDataContainer *cinput = mgr->GetCommonInputContainer();
		AliAnalysisDataContainer *coutput = mgr->CreateContainer("output", TList::Class(), AliAnalysisManager::kOutputContainer,"AnalysisResults.root");
		mgr->AddTask(task);
		mgr->ConnectInput(task, 0, cinput);
		mgr->ConnectOutput(task, 1, coutput);
		return task;
	}

<commit_msg>Update AddTaskPseudoRapidityDensity.C<commit_after>	AliAnalysisPseudoRapidityDensity* AddTaskPseudoRapidityDensity(const char* taskname, const char* option){

    AliAnalysisManager *mgr = AliAnalysisManager::GetAnalysisManager();
    if (!mgr) {
        return 0x0;
    }
    if (!mgr->GetInputEventHandler()) {
        return 0x0;
    }

		AliAnalysisPseudoRapidityDensity *task = new AliAnalysisPseudoRapidityDensity(taskname, option);
		AliAnalysisDataContainer *cinput = mgr->GetCommonInputContainer();
		AliAnalysisDataContainer *coutput = mgr->CreateContainer("output", TList::Class(), AliAnalysisManager::kOutputContainer,"AnalysisResults.root");
		mgr->AddTask(task);
		mgr->ConnectInput(task, 0, cinput);
		mgr->ConnectOutput(task, 1, coutput);
		return task;
	}

<|endoftext|>