<commit_before>//                                MFEM Example 1
//
// Compile with: make ex1
//
// Sample runs:  ex1 -m ../data/square-disc.mesh
//               ex1 -m ../data/star.mesh
//               ex1 -m ../data/star-mixed.mesh
//               ex1 -m ../data/escher.mesh
//               ex1 -m ../data/fichera.mesh
//               ex1 -m ../data/fichera-mixed.mesh
//               ex1 -m ../data/toroid-wedge.mesh
//               ex1 -m ../data/square-disc-p2.vtk -o 2
//               ex1 -m ../data/square-disc-p3.mesh -o 3
//               ex1 -m ../data/square-disc-nurbs.mesh -o -1
//               ex1 -m ../data/star-mixed-p2.mesh -o 2
//               ex1 -m ../data/disc-nurbs.mesh -o -1
//               ex1 -m ../data/pipe-nurbs.mesh -o -1
//               ex1 -m ../data/fichera-mixed-p2.mesh -o 2
//               ex1 -m ../data/star-surf.mesh
//               ex1 -m ../data/square-disc-surf.mesh
//               ex1 -m ../data/inline-segment.mesh
//               ex1 -m ../data/amr-quad.mesh
//               ex1 -m ../data/amr-hex.mesh
//               ex1 -m ../data/fichera-amr.mesh
//               ex1 -m ../data/mobius-strip.mesh
//               ex1 -m ../data/mobius-strip.mesh -o -1 -sc
//
// Device runs:  ex1 -p -d cuda
//               ex1 -p -d 'cuda occa'
//               ex1 -p -d 'raja omp'
//               ex1 -m ../data/beam-hex.mesh -p -d cuda
//
// Description:  This example code demonstrates the use of MFEM to define a
//               simple finite element discretization of the Laplace problem
//               -Delta u = 1 with homogeneous Dirichlet boundary conditions.
//               Specifically, we discretize using a FE space of the specified
//               order, or if order < 1 using an isoparametric/isogeometric
//               space (i.e. quadratic for quadratic curvilinear mesh, NURBS for
//               NURBS mesh, etc.)
//
//               The example highlights the use of mesh refinement, finite
//               element grid functions, as well as linear and bilinear forms
//               corresponding to the left-hand side and right-hand side of the
//               discrete linear system. We also cover the explicit elimination
//               of essential boundary conditions, static condensation, and the
//               optional connection to the GLVis tool for visualization.

#include "mfem.hpp"
#include <fstream>
#include <iostream>

using namespace std;
using namespace mfem;

int main(int argc, char *argv[])
{
   // 1. Parse command-line options.
   const char *mesh_file = "../data/star.mesh";
   int order = 1;
   bool static_cond = false;
   bool pa = false;
   const char *device = "";
   bool visualization = true;

   OptionsParser args(argc, argv);
   args.AddOption(&mesh_file, "-m", "--mesh",
                  "Mesh file to use.");
   args.AddOption(&order, "-o", "--order",
                  "Finite element order (polynomial degree) or -1 for"
                  " isoparametric space.");
   args.AddOption(&static_cond, "-sc", "--static-condensation", "-no-sc",
                  "--no-static-condensation", "Enable static condensation.");
   args.AddOption(&pa, "-p", "--pa", "-no-p", "--no-pa",
                  "Enable Partial Assembly.");
   args.AddOption(&device, "-d", "--device",
                  "Device configuration, e.g. 'cuda', 'omp', 'raja', 'occa'.");
   args.AddOption(&visualization, "-vis", "--visualization", "-no-vis",
                  "--no-visualization",
                  "Enable or disable GLVis visualization.");
   args.Parse();
   if (!args.Good())
   {
      args.PrintUsage(cout);
      return 1;
   }
   args.PrintOptions(cout);

   // 2. Read the mesh from the given mesh file. We can handle triangular,
   //    quadrilateral, tetrahedral, hexahedral, surface and volume meshes with
   //    the same code.
   Mesh *mesh = new Mesh(mesh_file, 1, 1);
   int dim = mesh->Dimension();
   if (pa) { mesh->EnsureNodes(); }

   // 3. Refine the mesh to increase the resolution. In this example we do
   //    'ref_levels' of uniform refinement. We choose 'ref_levels' to be the
   //    largest number that gives a final mesh with no more than 50,000
   //    elements.
   {
      int ref_levels =
         (int)floor(log(50000./mesh->GetNE())/log(2.)/dim);
      for (int l = 0; l < ref_levels; l++)
      {
         mesh->UniformRefinement();
      }
   }

   // 4. Define a finite element space on the mesh. Here we use continuous
   //    Lagrange finite elements of the specified order. If order < 1, we
   //    instead use an isoparametric/isogeometric space.
   FiniteElementCollection *fec;
   if (order > 0)
   {
      fec = new H1_FECollection(order, dim);
   }
   else if (mesh->GetNodes())
   {
      fec = mesh->GetNodes()->OwnFEC();
      cout << "Using isoparametric FEs: " << fec->Name() << endl;
   }
   else
   {
      fec = new H1_FECollection(order = 1, dim);
   }
   FiniteElementSpace *fespace = new FiniteElementSpace(mesh, fec);
   cout << "Number of finite element unknowns: "
        << fespace->GetTrueVSize() << endl;

   // 5. Determine the list of true (i.e. conforming) essential boundary dofs.
   //    In this example, the boundary conditions are defined by marking all
   //    the boundary attributes from the mesh as essential (Dirichlet) and
   //    converting them to a list of true dofs.
   Array<int> ess_tdof_list;
   if (mesh->bdr_attributes.Size())
   {
      Array<int> ess_bdr(mesh->bdr_attributes.Max());
      ess_bdr = 1;
      fespace->GetEssentialTrueDofs(ess_bdr, ess_tdof_list);
   }

   // 6. Set up the linear form b(.) which corresponds to the right-hand side of
   //    the FEM linear system, which in this case is (1,phi_i) where phi_i are
   //    the basis functions in the finite element fespace.
   LinearForm *b = new LinearForm(fespace);
   ConstantCoefficient one(1.0);
   b->AddDomainIntegrator(new DomainLFIntegrator(one));
   b->Assemble();

   // 7. Set device config parameters from the command line options and switch
   //    to working on the device.
   Device::Configure(device);
   Device::Print();
   Device::Enable();

   // 8. Define the solution vector x as a finite element grid function
   //    corresponding to fespace. Initialize x with initial guess of zero,
   //    which satisfies the boundary conditions.
   GridFunction x(fespace);
   x = 0.0;

   // 9. Set up the bilinear form a(.,.) on the finite element space
   //    corresponding to the Laplacian operator -Delta, by adding the Diffusion
   //    domain integrator.
   AssemblyLevel assembly = (pa) ? AssemblyLevel::PARTIAL : AssemblyLevel::FULL;
   BilinearForm *a = new BilinearForm(fespace, assembly);
   a->AddDomainIntegrator(new DiffusionIntegrator(one));

   // 10. Assemble the bilinear form and the corresponding linear system,
   //     applying any necessary transformations such as: eliminating boundary
   //     conditions, applying conforming constraints for non-conforming AMR,
   //     static condensation, etc.
   if (static_cond) { a->EnableStaticCondensation(); }
   a->Assemble();

   Vector B, X;
   Operator *A;
   if (!pa) { A = new SparseMatrix; }

   a->FormLinearSystem(ess_tdof_list, x, *b, A, X, B);

   cout << "Size of linear system: " << A->Height() << endl;

   // 11. Solve the linear system A X = B.
   if (!pa)
   {
#ifndef MFEM_USE_SUITESPARSE
      // Use a simple symmetric Gauss-Seidel preconditioner with PCG.
      GSSmoother M(*(SparseMatrix*)A);
      PCG(*A, M, B, X, 1, 200, 1e-12, 0.0);
#else
      // If MFEM was compiled with SuiteSparse, use UMFPACK to solve the system.
      UMFPackSolver umf_solver;
      umf_solver.Control[UMFPACK_ORDERING] = UMFPACK_ORDERING_METIS;
      umf_solver.SetOperator(*A);
      umf_solver.Mult(B, X);
#endif
   }
   else // No preconditioning for now in partial assembly mode.
   {
      CG(*A, B, X, 1, 2000, 1e-12, 0.0);
   }

   // 12. Recover the solution as a finite element grid function.
   a->RecoverFEMSolution(X, *b, x);

   // 13. Switch back to the host.
   Device::Disable();

   // 14. Save the refined mesh and the solution. This output can be viewed later
   //     using GLVis: "glvis -m refined.mesh -g sol.gf".
   ofstream mesh_ofs("refined.mesh");
   mesh_ofs.precision(8);
   mesh->Print(mesh_ofs);
   ofstream sol_ofs("sol.gf");
   sol_ofs.precision(8);
   x.Save(sol_ofs);

   // 15. Send the solution by socket to a GLVis server.
   if (visualization)
   {
      char vishost[] = "localhost";
      int  visport   = 19916;
      socketstream sol_sock(vishost, visport);
      sol_sock.precision(8);
      sol_sock << "solution\n" << *mesh << x << flush;
   }

   // 16. Free the used memory.
   delete A;
   delete a;
   delete b;
   delete fespace;
   if (order > 0) { delete fec; }
   delete mesh;

   return 0;
}
<commit_msg>[Examples] Added additional okina device run examples<commit_after>//                                MFEM Example 1
//
// Compile with: make ex1
//
// Sample runs:  ex1 -m ../data/square-disc.mesh
//               ex1 -m ../data/star.mesh
//               ex1 -m ../data/star-mixed.mesh
//               ex1 -m ../data/escher.mesh
//               ex1 -m ../data/fichera.mesh
//               ex1 -m ../data/fichera-mixed.mesh
//               ex1 -m ../data/toroid-wedge.mesh
//               ex1 -m ../data/square-disc-p2.vtk -o 2
//               ex1 -m ../data/square-disc-p3.mesh -o 3
//               ex1 -m ../data/square-disc-nurbs.mesh -o -1
//               ex1 -m ../data/star-mixed-p2.mesh -o 2
//               ex1 -m ../data/disc-nurbs.mesh -o -1
//               ex1 -m ../data/pipe-nurbs.mesh -o -1
//               ex1 -m ../data/fichera-mixed-p2.mesh -o 2
//               ex1 -m ../data/star-surf.mesh
//               ex1 -m ../data/square-disc-surf.mesh
//               ex1 -m ../data/inline-segment.mesh
//               ex1 -m ../data/amr-quad.mesh
//               ex1 -m ../data/amr-hex.mesh
//               ex1 -m ../data/fichera-amr.mesh
//               ex1 -m ../data/mobius-strip.mesh
//               ex1 -m ../data/mobius-strip.mesh -o -1 -sc
//
// Device runs:  ex1 -p -d cuda
//               ex1 -p -d 'cuda raja'
//               ex1 -p -d 'cuda occa'
//               ex1 -p -d 'omp raja'
//               ex1 -p -d 'omp occa'
//               ex1 -m ../data/beam-hex.mesh -p -d cuda
//
// Description:  This example code demonstrates the use of MFEM to define a
//               simple finite element discretization of the Laplace problem
//               -Delta u = 1 with homogeneous Dirichlet boundary conditions.
//               Specifically, we discretize using a FE space of the specified
//               order, or if order < 1 using an isoparametric/isogeometric
//               space (i.e. quadratic for quadratic curvilinear mesh, NURBS for
//               NURBS mesh, etc.)
//
//               The example highlights the use of mesh refinement, finite
//               element grid functions, as well as linear and bilinear forms
//               corresponding to the left-hand side and right-hand side of the
//               discrete linear system. We also cover the explicit elimination
//               of essential boundary conditions, static condensation, and the
//               optional connection to the GLVis tool for visualization.

#include "mfem.hpp"
#include <fstream>
#include <iostream>

using namespace std;
using namespace mfem;

int main(int argc, char *argv[])
{
   // 1. Parse command-line options.
   const char *mesh_file = "../data/star.mesh";
   int order = 1;
   bool static_cond = false;
   bool pa = false;
   const char *device = "";
   bool visualization = true;

   OptionsParser args(argc, argv);
   args.AddOption(&mesh_file, "-m", "--mesh",
                  "Mesh file to use.");
   args.AddOption(&order, "-o", "--order",
                  "Finite element order (polynomial degree) or -1 for"
                  " isoparametric space.");
   args.AddOption(&static_cond, "-sc", "--static-condensation", "-no-sc",
                  "--no-static-condensation", "Enable static condensation.");
   args.AddOption(&pa, "-p", "--pa", "-no-p", "--no-pa",
                  "Enable Partial Assembly.");
   args.AddOption(&device, "-d", "--device",
                  "Device configuration, e.g. 'cuda', 'omp', 'raja', 'occa'.");
   args.AddOption(&visualization, "-vis", "--visualization", "-no-vis",
                  "--no-visualization",
                  "Enable or disable GLVis visualization.");
   args.Parse();
   if (!args.Good())
   {
      args.PrintUsage(cout);
      return 1;
   }
   args.PrintOptions(cout);

   // 2. Read the mesh from the given mesh file. We can handle triangular,
   //    quadrilateral, tetrahedral, hexahedral, surface and volume meshes with
   //    the same code.
   Mesh *mesh = new Mesh(mesh_file, 1, 1);
   int dim = mesh->Dimension();
   if (pa) { mesh->EnsureNodes(); }

   // 3. Refine the mesh to increase the resolution. In this example we do
   //    'ref_levels' of uniform refinement. We choose 'ref_levels' to be the
   //    largest number that gives a final mesh with no more than 50,000
   //    elements.
   {
      int ref_levels =
         (int)floor(log(50000./mesh->GetNE())/log(2.)/dim);
      for (int l = 0; l < ref_levels; l++)
      {
         mesh->UniformRefinement();
      }
   }

   // 4. Define a finite element space on the mesh. Here we use continuous
   //    Lagrange finite elements of the specified order. If order < 1, we
   //    instead use an isoparametric/isogeometric space.
   FiniteElementCollection *fec;
   if (order > 0)
   {
      fec = new H1_FECollection(order, dim);
   }
   else if (mesh->GetNodes())
   {
      fec = mesh->GetNodes()->OwnFEC();
      cout << "Using isoparametric FEs: " << fec->Name() << endl;
   }
   else
   {
      fec = new H1_FECollection(order = 1, dim);
   }
   FiniteElementSpace *fespace = new FiniteElementSpace(mesh, fec);
   cout << "Number of finite element unknowns: "
        << fespace->GetTrueVSize() << endl;

   // 5. Determine the list of true (i.e. conforming) essential boundary dofs.
   //    In this example, the boundary conditions are defined by marking all
   //    the boundary attributes from the mesh as essential (Dirichlet) and
   //    converting them to a list of true dofs.
   Array<int> ess_tdof_list;
   if (mesh->bdr_attributes.Size())
   {
      Array<int> ess_bdr(mesh->bdr_attributes.Max());
      ess_bdr = 1;
      fespace->GetEssentialTrueDofs(ess_bdr, ess_tdof_list);
   }

   // 6. Set up the linear form b(.) which corresponds to the right-hand side of
   //    the FEM linear system, which in this case is (1,phi_i) where phi_i are
   //    the basis functions in the finite element fespace.
   LinearForm *b = new LinearForm(fespace);
   ConstantCoefficient one(1.0);
   b->AddDomainIntegrator(new DomainLFIntegrator(one));
   b->Assemble();

   // 7. Set device config parameters from the command line options and switch
   //    to working on the device.
   Device::Configure(device);
   Device::Print();
   Device::Enable();

   // 8. Define the solution vector x as a finite element grid function
   //    corresponding to fespace. Initialize x with initial guess of zero,
   //    which satisfies the boundary conditions.
   GridFunction x(fespace);
   x = 0.0;

   // 9. Set up the bilinear form a(.,.) on the finite element space
   //    corresponding to the Laplacian operator -Delta, by adding the Diffusion
   //    domain integrator.
   AssemblyLevel assembly = (pa) ? AssemblyLevel::PARTIAL : AssemblyLevel::FULL;
   BilinearForm *a = new BilinearForm(fespace, assembly);
   a->AddDomainIntegrator(new DiffusionIntegrator(one));

   // 10. Assemble the bilinear form and the corresponding linear system,
   //     applying any necessary transformations such as: eliminating boundary
   //     conditions, applying conforming constraints for non-conforming AMR,
   //     static condensation, etc.
   if (static_cond) { a->EnableStaticCondensation(); }
   a->Assemble();

   Vector B, X;
   Operator *A;
   if (!pa) { A = new SparseMatrix; }

   a->FormLinearSystem(ess_tdof_list, x, *b, A, X, B);

   cout << "Size of linear system: " << A->Height() << endl;

   // 11. Solve the linear system A X = B.
   if (!pa)
   {
#ifndef MFEM_USE_SUITESPARSE
      // Use a simple symmetric Gauss-Seidel preconditioner with PCG.
      GSSmoother M(*(SparseMatrix*)A);
      PCG(*A, M, B, X, 1, 200, 1e-12, 0.0);
#else
      // If MFEM was compiled with SuiteSparse, use UMFPACK to solve the system.
      UMFPackSolver umf_solver;
      umf_solver.Control[UMFPACK_ORDERING] = UMFPACK_ORDERING_METIS;
      umf_solver.SetOperator(*A);
      umf_solver.Mult(B, X);
#endif
   }
   else // No preconditioning for now in partial assembly mode.
   {
      CG(*A, B, X, 1, 2000, 1e-12, 0.0);
   }

   // 12. Recover the solution as a finite element grid function.
   a->RecoverFEMSolution(X, *b, x);

   // 13. Switch back to the host.
   Device::Disable();

   // 14. Save the refined mesh and the solution. This output can be viewed later
   //     using GLVis: "glvis -m refined.mesh -g sol.gf".
   ofstream mesh_ofs("refined.mesh");
   mesh_ofs.precision(8);
   mesh->Print(mesh_ofs);
   ofstream sol_ofs("sol.gf");
   sol_ofs.precision(8);
   x.Save(sol_ofs);

   // 15. Send the solution by socket to a GLVis server.
   if (visualization)
   {
      char vishost[] = "localhost";
      int  visport   = 19916;
      socketstream sol_sock(vishost, visport);
      sol_sock.precision(8);
      sol_sock << "solution\n" << *mesh << x << flush;
   }

   // 16. Free the used memory.
   delete A;
   delete a;
   delete b;
   delete fespace;
   if (order > 0) { delete fec; }
   delete mesh;

   return 0;
}
<|endoftext|>


<commit_before>#include "blas.hpp"
#include "linalg.hpp"
#include "fast424_26_257.hpp"

#include <chrono>
#include <vector>

extern "C" {
  void dgetrf_(int *m, int *n, double *A, int *lda, int *ipiv, int *info);
  void sgetrf_(int *m, int *n, float *A, int *lda, int *ipiv, int *info);
}

void GetrfWrap(double *data, int m, int n, int lda, std::vector<int>& pivots) {
  int info;
  dgetrf_(&m, &n, data, &lda, &pivots[0], &info);
  assert(info == 0);
}

void GetrfWrap(float *data, int m, int n, int lda, std::vector<int>& pivots) {
  int info;
  sgetrf_(&m, &n, data, &lda, &pivots[0], &info);
  assert(info == 0);
}

template<typename Scalar>
void LU(Matrix<Scalar>& A, std::vector<int>& pivots) {
  assert(A.m() > 0 && A.n() > 0);
  int m = A.m();
  int n = A.n();
  pivots.resize(n);
  int lda = A.stride();
  Scalar *data = A.data();
  GetrfWrap(data, m, n, lda, pivots);
  // Convert back to C++ zero-indexing
  for (int i = 0; i < pivots.size(); ++i) {
	pivots[i] -= 1;
  }
}

template<typename Scalar>
void Pivot(Matrix<Scalar>& A, std::vector<int>& pivots) {
  Scalar *data = A.data();
  int stride = A.stride();
  for (int j = 0; j < A.n(); ++j) {
	for (int i = 0; i < pivots.size(); ++i) {
	  // Swap rows i and pivots[i]
	  int pivot_row = pivots[i];
	  Scalar aij = data[i + j * stride];
	  data[i + j * stride] = data[pivot_row + j * stride];
	  data[pivot_row + j * stride] = aij;
	}
  }
}

template<typename Scalar>
void FastLU(Matrix<Scalar>& A, int blocksize) {
  std::vector<int> all_pivots(A.m());
  for (int i = 0; i < A.m() && A.m() - i >= 2 * blocksize; i += blocksize) {
	Matrix<double> Panel = A.Submatrix(i, i, A.m() - i, blocksize);
	std::vector<int> pivots;
	LU(Panel, pivots);
	//Pivot(A, pivots);

	Matrix<double> L21 = Panel.Submatrix(i, 0, A.m() - i - blocksize, blocksize);
	Matrix<double> A22 = A.Submatrix(i, i, A.m() - i, A.n() - i);
	Matrix<double> A12 = A.Submatrix(0, i, blocksize, A.n() - i);
	// TODO: Need to update and multiply by negative one, not just overwrite
	grey424_26_257::FastMatmul(L21, A12, A22, 1);
	// Append pivots
	for (int j = i; j < i + blocksize; ++j) {
	  all_pivots[j] = pivots[j - i];
	}
  }

  // Now deal with the leftovers
  int start_ind = (A.m() / blocksize) * blocksize;
  int num_left = A.m() - start_ind;
  assert(num_left >= A.m());
  if (num_left == 0) {
	return;
  }
  std::vector<int> pivots;
  Matrix<double> A_end = A.Submatrix(start_ind, start_ind, num_left, A.n() - start_ind);
  LU(A_end, pivots);
  for (int j = start_ind; j < A.m(); ++j) {
	all_pivots[j] = pivots[j - start_ind];
  }
}

int main(int argc, char **argv) {
  int n = 10000;
  Matrix<double> A = RandomMatrix<double>(n, n);
  Matrix<double> B = A;

  auto t3 = std::chrono::high_resolution_clock::now();
  FastLU(B, 1600);
  auto t4 = std::chrono::high_resolution_clock::now();
  std::cout << "Fast LU took "
			<< std::chrono::duration_cast<std::chrono::milliseconds>(t4-t3).count()
			<< " milliseconds"
			<< std::endl;

  auto t1 = std::chrono::high_resolution_clock::now();
  std::vector<int> pivots(A.m());
  LU(A, pivots);
  auto t2 = std::chrono::high_resolution_clock::now();
  std::cout << "Classical LU took "
			<< std::chrono::duration_cast<std::chrono::milliseconds>(t2-t1).count()
			<< " milliseconds"
			<< std::endl;

}
<commit_msg>Small changes.<commit_after>#include "blas.hpp"
#include "linalg.hpp"
#include "fast424_26_257.hpp"

#include <chrono>
#include <vector>

extern "C" {
  void dgetrf_(int *m, int *n, double *A, int *lda, int *ipiv, int *info);
  void sgetrf_(int *m, int *n, float *A, int *lda, int *ipiv, int *info);
}

void GetrfWrap(double *data, int m, int n, int lda, std::vector<int>& pivots) {
  int info;
  dgetrf_(&m, &n, data, &lda, &pivots[0], &info);
  assert(info == 0);
}

void GetrfWrap(float *data, int m, int n, int lda, std::vector<int>& pivots) {
  int info;
  sgetrf_(&m, &n, data, &lda, &pivots[0], &info);
  assert(info == 0);
}

template<typename Scalar>
void LU(Matrix<Scalar>& A, std::vector<int>& pivots) {
  assert(A.m() > 0 && A.n() > 0);
  int m = A.m();
  int n = A.n();
  pivots.resize(n);
  int lda = A.stride();
  Scalar *data = A.data();
  GetrfWrap(data, m, n, lda, pivots);
  // Convert back to C++ zero-indexing
  for (int i = 0; i < pivots.size(); ++i) {
	pivots[i] -= 1;
  }
}

template<typename Scalar>
void Pivot(Matrix<Scalar>& A, std::vector<int>& pivots) {
  Scalar *data = A.data();
  int stride = A.stride();
  for (int j = 0; j < A.n(); ++j) {
	for (int i = 0; i < pivots.size(); ++i) {
	  // Swap rows i and pivots[i]
	  int pivot_row = pivots[i];
	  Scalar aij = data[i + j * stride];
	  data[i + j * stride] = data[pivot_row + j * stride];
	  data[pivot_row + j * stride] = aij;
	}
  }
}

template<typename Scalar>
void FastLU(Matrix<Scalar>& A, int blocksize) {
  std::vector<int> all_pivots(A.m());
  for (int i = 0; i < A.m() && A.m() - i >= blocksize; i += blocksize) {
	Matrix<double> Panel = A.Submatrix(i, i, A.m() - i, blocksize);
	std::vector<int> pivots;
	LU(Panel, pivots);
	Pivot(A, pivots);

	Matrix<double> L21 = Panel.Submatrix(i, 0, A.m() - i - blocksize, blocksize);
	Matrix<double> A22 = A.Submatrix(i, i, A.m() - i, A.n() - i);
	Matrix<double> A12 = A.Submatrix(0, i, blocksize, A.n() - i);
	// TODO: Need to update and multiply by negative one, not just overwrite
	grey424_26_257::FastMatmul(L21, A12, A22, 1);
	// Append pivots
	for (int j = i; j < i + blocksize; ++j) {
	  all_pivots[j] = pivots[j - i];
	}
  }

  // Now deal with the leftovers
  int start_ind = (A.m() / blocksize) * blocksize;
  int num_left = A.m() - start_ind;
  assert(num_left >= A.m());
  if (num_left == 0) {
	return;
  }
  std::vector<int> pivots;
  Matrix<double> A_end = A.Submatrix(start_ind, start_ind, num_left, A.n() - start_ind);
  LU(A_end, pivots);
  for (int j = start_ind; j < A.m(); ++j) {
	all_pivots[j] = pivots[j - start_ind];
  }
}

int main(int argc, char **argv) {
  int n = 10000;
  Matrix<double> A = RandomMatrix<double>(n, n);
  Matrix<double> B = A;

  auto t1 = std::chrono::high_resolution_clock::now();
  std::vector<int> pivots(A.m());
  LU(A, pivots);
  auto t2 = std::chrono::high_resolution_clock::now();
  std::cout << "Classical LU took "
			<< std::chrono::duration_cast<std::chrono::milliseconds>(t2-t1).count()
			<< " milliseconds"
			<< std::endl;

  auto t3 = std::chrono::high_resolution_clock::now();
  FastLU(B, 1600);
  auto t4 = std::chrono::high_resolution_clock::now();
  std::cout << "Fast LU took "
			<< std::chrono::duration_cast<std::chrono::milliseconds>(t4-t3).count()
			<< " milliseconds"
			<< std::endl;
}
<|endoftext|>


<commit_before><commit_msg>fix issue #13<commit_after><|endoftext|>


<commit_before><commit_msg>[TD]remove extra space in Angular Dims<commit_after><|endoftext|>


<commit_before><commit_msg>fix unhandled exception<commit_after><|endoftext|>


<commit_before>#include <iostream>
#include "SimpleHttpRequest.h"

using namespace std;

int main() {
  int r;

  uv_loop = uv_default_loop();

#if 1
  // request.get(url)
  SimpleHttpRequest request(uv_loop);
  request.get("http://192.168.10.9:10509/archive")
  .on("error", [](){
    cerr << endl << "on error" << endl;
  }).on("response", [&request](){
    cout << request.responseBody.str();
  }).end();
#endif

#if 0
  // request(options) GET
  map<string, string> options;
  options["hostname"] = "192.168.10.9";
  options["port"] = "10509";
  options["path"] = "/archive";
  options["method"] = "GET";

  SimpleHttpRequest request(options, uv_loop);
  request.setHeader("content-type","application/json")
  .on("error", [](){
    cerr << endl << "on error" << endl;
  }).on("response", [&request](){
    for (const auto &kv : request.responseHeaders)
      cout << kv.first << " : " << kv.second << endl;

    cout << request.responseBody.str().c_str();
  }).end();
#endif

#if 0
// request.post(url, body) POST
  string body = "{\"archive\":3}";
  SimpleHttpRequest request(uv_loop);
  request.setHeader("content-type","application/json")
  .post("http://192.168.10.9:10509/archive", body)
  .on("error", [](){
    cout << endl << "on error" << endl;
  })
  .on("response", [&request](){
    cout << endl << request.statusCode << endl;
    cout << request.responseBody.str() << endl;
  })
  .end();
#endif

#if 0
// request(options, headers) POST
  map<string, string> options;
  map<string, string> headers;
  options["hostname"] = "192.168.10.9";
  options["port"] = "10509";
  options["path"] = "/archive";
  options["method"] = "POST";
  headers["content-type"] = "application/json";

  SimpleHttpRequest request(options, headers, uv_loop);
  request.on("error", [](){
    cout << endl << "on error" << endl;
  });
  request.on("response", [&request](){
    cout << endl << request.statusCode << endl;
    cout << request.responseBody.str() << endl;
  });
  request.write("{\"archive\":3}");
  request.end();
#endif

  return uv_run(uv_loop, UV_RUN_DEFAULT);
}
<commit_msg>add an example for 'POST write(stream)' and timeout<commit_after>#include <iostream>
#include "SimpleHttpRequest.h"

using namespace std;

int main() {
  int r;

  uv_loop = uv_default_loop();

#if 1
  // request.get(url)
  SimpleHttpRequest request(uv_loop);
  request.timeout = 1000;
  request.get("http://127.0.0.1:10509/archive")
  .on("error", [](){
    cerr << endl << "on error" << endl;
  }).on("response", [&request](){
    cout << request.responseBody.str();
  }).end();
#endif

#if 0
  // request(options) GET
  map<string, string> options;
  options["hostname"] = "192.168.10.9";
  options["port"] = "10509";
  options["path"] = "/archive";
  options["method"] = "GET";

  SimpleHttpRequest request(options, uv_loop);
  request.setHeader("content-type","application/json")
  .on("error", [](){
    cerr << endl << "on error" << endl;
  }).on("response", [&request](){
    for (const auto &kv : request.responseHeaders)
      cout << kv.first << " : " << kv.second << endl;

    cout << request.responseBody.str().c_str();
  }).end();
#endif

#if 0
// request.post(url, body) POST
  string body = "{\"archive\":3}";
  SimpleHttpRequest request(uv_loop);
  request.setHeader("content-type","application/json")
  .post("http://192.168.10.9:10509/archive", body)
  .on("error", [](){
    cout << endl << "on error" << endl;
  })
  .on("response", [&request](){
    cout << endl << request.statusCode << endl;
    cout << request.responseBody.str() << endl;
  })
  .end();
#endif

#if 0
// request(options, headers) POST write(string)
  map<string, string> options;
  map<string, string> headers;
  options["hostname"] = "192.168.10.9";
  options["port"] = "10509";
  options["path"] = "/archive";
  options["method"] = "POST";
  headers["content-type"] = "application/json";

  SimpleHttpRequest request(options, headers, uv_loop);
  request.on("error", [](){
    cout << endl << "on error" << endl;
  });
  request.on("response", [&request](){
    cout << endl << request.statusCode << endl;
    cout << request.responseBody.str() << endl;
  });
  request.write("{\"archive\":3}");
  request.end();
#endif

#if 0
// request(options, headers) POST write(stream)
  map<string, string> options;
  map<string, string> headers;
  options["hostname"] = "192.168.10.9";
  options["port"] = "10509";
  options["path"] = "/archive";
  options["method"] = "POST";
  headers["content-type"] = "application/json"; // ignored!!

  stringstream body;
  body << "{\"archive\":3}";
  SimpleHttpRequest request(options, headers, uv_loop);
  request.on("error", [](){
    cout << endl << "on error" << endl;
  });
  request.on("response", [&request](){
    cout << endl << request.statusCode << endl;
    cout << request.responseBody.str() << endl;
  });
  request.write(body);  //contnet-type = "application/octet-stream"
  request.end();
#endif

  return uv_run(uv_loop, UV_RUN_DEFAULT);
}
<|endoftext|>


<commit_before>/*
 * IOGTest.cpp
 *
 *  Created on: 12.12.2012
 *      Author: Christian Staudt (christian.staudt@kit.edu)
 */

#ifndef NOGTEST

#include "IOGTest.h"

namespace NetworKit {

TEST_F(IOGTest, testGraphIOEdgeList) {
	GraphGenerator graphGen;
	Graph G = graphGen.makeCircularGraph(20);
	GraphIO graphio;
	std::string path = "output/edgelist.txt";
	graphio.writeEdgeList(G, path);

	bool exists = false;
	std::ifstream file(path);
	if (file) {
		exists = true;
	}
	EXPECT_TRUE(exists) << "A file should have been created : " << path;
}

TEST_F(IOGTest, testGraphIOAdjacencyList) {
	GraphGenerator graphGen;
	Graph G = graphGen.makeCircularGraph(20);
	GraphIO graphio;
	std::string path = "output/circular.adjlist";
	graphio.writeAdjacencyList(G, path);

	bool exists = false;
	std::ifstream file(path);
	if (file) {
		exists = true;
	}
	EXPECT_TRUE(exists) << "A file should have been created : " << path;
}

TEST_F(IOGTest, testGraphIOForIsolatedNodes) {
	GraphGenerator graphGen;
	Graph G(20);
	GraphIO graphio;
	std::string path = "output/isolated.adjlist";
	graphio.writeAdjacencyList(G, path);

	bool exists = false;
	std::ifstream file(path);
	if (file) {
		exists = true;
	}
	EXPECT_TRUE(exists) << "A file should have been created : " << path;
}

TEST_F(IOGTest, testMETISGraphReader) {
	std::string path = "input/jazz.graph";

	METISGraphReader reader;
	Graph G = reader.read(path);
	count n = 198;
	count m = 2742;
	EXPECT_FALSE(G.isEmpty());
	EXPECT_EQ(n, G.numberOfNodes()) << "There are " << n << " nodes in the  graph";
	EXPECT_EQ(m, G.numberOfEdges()) << "There are " << m << " edges in the  graph";
}

TEST_F(IOGTest, testMETISGraphReaderWithWeights) {
	std::string path = "input/lesmis.graph";

	METISGraphReader reader;
	Graph G = reader.read(path);

	EXPECT_FALSE(G.isEmpty());
	count n = 77;
	count m = 254;
	EXPECT_EQ(n, G.numberOfNodes()) << "There are " << n << " nodes in the  graph";
	EXPECT_EQ(m, G.numberOfEdges()) << "There are " << m << " edges in the  graph";
}

TEST_F(IOGTest, testMETISGraphWriter) {
	std::string path = "input/jazz1.graph";
	Graph G = Graph(3);
	G.addEdge(0,2);
	G.addEdge(1,1);
	G.addEdge(1,2);
	G.addEdge(2,2);

	METISGraphWriter writer;
	writer.write(G, false, path);
    bool exists = false;
	std::ifstream file(path);
	if (file) {
		exists = true;
	}
	EXPECT_TRUE(exists) << "A file should have been created : " << path;

}

TEST_F(IOGTest, testMETISGraphWriterWithWeights) {
	std::string path = "input/jazz2.graph";
	Graph G = Graph(5);
	G.addEdge(0,2);
	G.addEdge(0,1);
	G.addEdge(0,0);
	G.addEdge(1,1);

	METISGraphWriter writer;
	writer.write(G, true, path);
    bool exists = false;
	std::ifstream file(path);
	if (file) {
		exists = true;
	}
	EXPECT_TRUE(exists) << "A file should have been created : " << path;

}

TEST_F(IOGTest, testClusteringWriterAndReader) {
	// write clustering first
	std::string path = "output/example.clust";

	GraphGenerator graphGen;
	count n = 100;
	count k = 3;
	Graph G = graphGen.makeCompleteGraph(n);

	ClusteringGenerator clusteringGen;
	Clustering zeta = clusteringGen.makeRandomClustering(G, k);

	ClusteringWriter writer;
	writer.write(zeta, path);

	// check if file exists
	bool exists = false;
	std::ifstream file(path);
	if (file) {
		exists = true;
	}
	EXPECT_TRUE(exists) << "clustering file should have been written to: " << path;

	ClusteringReader reader;
	Clustering read = reader.read(path);

	EXPECT_EQ(n, read.numberOfNodes()) << "read clustering should contain n nodes";
	EXPECT_TRUE(read.isProper(G)) << "read clustering should be proper clustering of G";
	EXPECT_TRUE(read.equals(zeta, G)) << "read clustering should be identical to created clustering";
}

TEST_F(IOGTest, testDotGraphWriter) {
	GraphGenerator graphGen;
	Graph G = graphGen.makeCompleteGraph(42);

	std::string path = "output/example.dot";

	DotGraphWriter writer;
	writer.write(G, path);

	// check if file exists
	bool exists = false;
	std::ifstream file(path);
	if (file) {
		exists = true;
	}
	EXPECT_TRUE(exists) << "graph file should have been written to: " << path;
}

TEST_F(IOGTest, tryDGSReaderOnBigFile) {
	// read example graph
	DGSReader reader;
	Graph G;
	GraphEventProxy Gproxy(G);
	reader.read("/Users/forigem/KIT/NetworKit-CommunityDetection/input/AuthorsGraph.dgs", Gproxy);
}

TEST_F(IOGTest, tryDGSReader) {
	// read example graph
	DGSReader reader;
	Graph G;
	GraphEventProxy Gproxy(G);
	reader.read("input/example2.dgs", Gproxy);

	// get input parameters
	count nodeCount = G.numberOfNodes();
	DEBUG("Number of nodes " << nodeCount);
	EXPECT_EQ(3, nodeCount);
	count edgeCount = G.numberOfEdges();
	DEBUG("Number of edges " << edgeCount);
	EXPECT_EQ(2, edgeCount);

	G.forNodes([&](node n) {
		DEBUG("DEGREE OF NODE: " << G.degree(n) << std::endl);
	});

}

TEST_F(IOGTest, testEdgeListReader) {
	EdgeListReader reader;

	Graph G = reader.read("input/LFR-generator-example/network.dat");
	EXPECT_EQ(10, G.numberOfNodes());
	EXPECT_EQ(10, G.numberOfEdges());
	EXPECT_TRUE(G.hasEdge(0, 5));
	EXPECT_TRUE(G.hasEdge(2, 9));
	EXPECT_TRUE(G.hasEdge(1, 7));

}

TEST_F(IOGTest, testEdgeListClusteringReader) {
	EdgeListClusteringReader reader(1);

	Clustering zeta = reader.read("input/LFR-generator-example/community.dat");
	//EXPECT_EQ(10, zeta.size());
	EXPECT_EQ(1, zeta[0]);
	EXPECT_EQ(3, zeta[1]);
	EXPECT_EQ(2, zeta[2]);
	EXPECT_EQ(10, zeta.numberOfEntries());

}

TEST_F(IOGTest, testMETISGraphReaderForNodeExistence2) {
	METISGraphReader reader;
	Graph G = reader.read("input/jazz.graph");
	EXPECT_TRUE(G.hasNode(0));
	EXPECT_EQ(198, G.numberOfNodes());
	EXPECT_EQ(2742, G.numberOfEdges());
}

TEST_F(IOGTest, testMETISGraphReaderWithIsolatedNodes) {
	METISGraphReader reader;
	Graph G = reader.read("input/example.graph");
	EXPECT_EQ(4, G.numberOfNodes());
	EXPECT_EQ(1, G.numberOfEdges());
	EXPECT_TRUE(G.hasNode(0));
	EXPECT_TRUE(G.hasNode(1));
	EXPECT_TRUE(G.hasNode(2));
	EXPECT_TRUE(G.hasNode(3));
}

TEST_F(IOGTest, tryReadingLFR) {
	std::string graphPath;
	std::string clustPath;

	std::cout << "[INPUT] LFR graph file path >" << std::endl;
	std::getline(std::cin, graphPath);

	std::cout << "[INPUT] clustering file path >" << std::endl;
	std::getline(std::cin, clustPath);

	EdgeListReader graphReader;
	EdgeListClusteringReader clusteringReader;

	Graph G = graphReader.read(graphPath);
	Clustering truth = clusteringReader.read(clustPath);

	LabelPropagation PLP;
	Clustering zeta = PLP.run(G);

	Modularity mod;
	INFO("static clustering quality: " << mod.getQuality(zeta, G));
	INFO("static clustering number of clusters: " << zeta.numberOfClusters());
	INFO("ground truth quality: " << mod.getQuality(truth, G));
	INFO("ground truth number of clusters: " << truth.numberOfClusters());

}

TEST_F(IOGTest, tryReadingSNAP) {
	std::string graphPath;

	std::cout << "[INPUT] SNAP graph file path >" << std::endl;
	std::getline(std::cin, graphPath);

	EdgeListReader graphReader;

	Graph G = graphReader.read(graphPath);

	INFO("n = " << G.numberOfNodes());
	INFO("m = " << G.numberOfEdges());

}

} /* namespace NetworKit */

#endif /* NOGTEST */
<commit_msg>tryMETISGraphReaderWithIsolatedNodes<commit_after>/*
 * IOGTest.cpp
 *
 *  Created on: 12.12.2012
 *      Author: Christian Staudt (christian.staudt@kit.edu)
 */

#ifndef NOGTEST

#include "IOGTest.h"

namespace NetworKit {

TEST_F(IOGTest, testGraphIOEdgeList) {
	GraphGenerator graphGen;
	Graph G = graphGen.makeCircularGraph(20);
	GraphIO graphio;
	std::string path = "output/edgelist.txt";
	graphio.writeEdgeList(G, path);

	bool exists = false;
	std::ifstream file(path);
	if (file) {
		exists = true;
	}
	EXPECT_TRUE(exists) << "A file should have been created : " << path;
}

TEST_F(IOGTest, testGraphIOAdjacencyList) {
	GraphGenerator graphGen;
	Graph G = graphGen.makeCircularGraph(20);
	GraphIO graphio;
	std::string path = "output/circular.adjlist";
	graphio.writeAdjacencyList(G, path);

	bool exists = false;
	std::ifstream file(path);
	if (file) {
		exists = true;
	}
	EXPECT_TRUE(exists) << "A file should have been created : " << path;
}

TEST_F(IOGTest, testGraphIOForIsolatedNodes) {
	GraphGenerator graphGen;
	Graph G(20);
	GraphIO graphio;
	std::string path = "output/isolated.adjlist";
	graphio.writeAdjacencyList(G, path);

	bool exists = false;
	std::ifstream file(path);
	if (file) {
		exists = true;
	}
	EXPECT_TRUE(exists) << "A file should have been created : " << path;
}

TEST_F(IOGTest, testMETISGraphReader) {
	std::string path = "input/jazz.graph";

	METISGraphReader reader;
	Graph G = reader.read(path);
	count n = 198;
	count m = 2742;
	EXPECT_FALSE(G.isEmpty());
	EXPECT_EQ(n, G.numberOfNodes()) << "There are " << n << " nodes in the  graph";
	EXPECT_EQ(m, G.numberOfEdges()) << "There are " << m << " edges in the  graph";
}

TEST_F(IOGTest, testMETISGraphReaderWithWeights) {
	std::string path = "input/lesmis.graph";

	METISGraphReader reader;
	Graph G = reader.read(path);

	EXPECT_FALSE(G.isEmpty());
	count n = 77;
	count m = 254;
	EXPECT_EQ(n, G.numberOfNodes()) << "There are " << n << " nodes in the  graph";
	EXPECT_EQ(m, G.numberOfEdges()) << "There are " << m << " edges in the  graph";
}

TEST_F(IOGTest, testMETISGraphWriter) {
	std::string path = "input/jazz1.graph";
	Graph G = Graph(3);
	G.addEdge(0,2);
	G.addEdge(1,1);
	G.addEdge(1,2);
	G.addEdge(2,2);

	METISGraphWriter writer;
	writer.write(G, false, path);
    bool exists = false;
	std::ifstream file(path);
	if (file) {
		exists = true;
	}
	EXPECT_TRUE(exists) << "A file should have been created : " << path;

}

TEST_F(IOGTest, testMETISGraphWriterWithWeights) {
	std::string path = "input/jazz2.graph";
	Graph G = Graph(5);
	G.addEdge(0,2);
	G.addEdge(0,1);
	G.addEdge(0,0);
	G.addEdge(1,1);

	METISGraphWriter writer;
	writer.write(G, true, path);
    bool exists = false;
	std::ifstream file(path);
	if (file) {
		exists = true;
	}
	EXPECT_TRUE(exists) << "A file should have been created : " << path;

}

TEST_F(IOGTest, testClusteringWriterAndReader) {
	// write clustering first
	std::string path = "output/example.clust";

	GraphGenerator graphGen;
	count n = 100;
	count k = 3;
	Graph G = graphGen.makeCompleteGraph(n);

	ClusteringGenerator clusteringGen;
	Clustering zeta = clusteringGen.makeRandomClustering(G, k);

	ClusteringWriter writer;
	writer.write(zeta, path);

	// check if file exists
	bool exists = false;
	std::ifstream file(path);
	if (file) {
		exists = true;
	}
	EXPECT_TRUE(exists) << "clustering file should have been written to: " << path;

	ClusteringReader reader;
	Clustering read = reader.read(path);

	EXPECT_EQ(n, read.numberOfNodes()) << "read clustering should contain n nodes";
	EXPECT_TRUE(read.isProper(G)) << "read clustering should be proper clustering of G";
	EXPECT_TRUE(read.equals(zeta, G)) << "read clustering should be identical to created clustering";
}

TEST_F(IOGTest, testDotGraphWriter) {
	GraphGenerator graphGen;
	Graph G = graphGen.makeCompleteGraph(42);

	std::string path = "output/example.dot";

	DotGraphWriter writer;
	writer.write(G, path);

	// check if file exists
	bool exists = false;
	std::ifstream file(path);
	if (file) {
		exists = true;
	}
	EXPECT_TRUE(exists) << "graph file should have been written to: " << path;
}

TEST_F(IOGTest, tryDGSReaderOnBigFile) {
	// read example graph
	DGSReader reader;
	Graph G;
	GraphEventProxy Gproxy(G);
	reader.read("/Users/forigem/KIT/NetworKit-CommunityDetection/input/AuthorsGraph.dgs", Gproxy);
}

TEST_F(IOGTest, tryDGSReader) {
	// read example graph
	DGSReader reader;
	Graph G;
	GraphEventProxy Gproxy(G);
	reader.read("input/example2.dgs", Gproxy);

	// get input parameters
	count nodeCount = G.numberOfNodes();
	DEBUG("Number of nodes " << nodeCount);
	EXPECT_EQ(3, nodeCount);
	count edgeCount = G.numberOfEdges();
	DEBUG("Number of edges " << edgeCount);
	EXPECT_EQ(2, edgeCount);

	G.forNodes([&](node n) {
		DEBUG("DEGREE OF NODE: " << G.degree(n) << std::endl);
	});

}

TEST_F(IOGTest, testEdgeListReader) {
	EdgeListReader reader;

	Graph G = reader.read("input/LFR-generator-example/network.dat");
	EXPECT_EQ(10, G.numberOfNodes());
	EXPECT_EQ(10, G.numberOfEdges());
	EXPECT_TRUE(G.hasEdge(0, 5));
	EXPECT_TRUE(G.hasEdge(2, 9));
	EXPECT_TRUE(G.hasEdge(1, 7));

}

TEST_F(IOGTest, testEdgeListClusteringReader) {
	EdgeListClusteringReader reader(1);

	Clustering zeta = reader.read("input/LFR-generator-example/community.dat");
	//EXPECT_EQ(10, zeta.size());
	EXPECT_EQ(1, zeta[0]);
	EXPECT_EQ(3, zeta[1]);
	EXPECT_EQ(2, zeta[2]);
	EXPECT_EQ(10, zeta.numberOfEntries());

}

TEST_F(IOGTest, testMETISGraphReaderForNodeExistence2) {
	METISGraphReader reader;
	Graph G = reader.read("input/jazz.graph");
	EXPECT_TRUE(G.hasNode(0));
	EXPECT_EQ(198, G.numberOfNodes());
	EXPECT_EQ(2742, G.numberOfEdges());
}

TEST_F(IOGTest, tryMETISGraphReaderWithIsolatedNodes) {
	METISGraphReader reader;
	Graph G = reader.read("input/example.graph");
	EXPECT_EQ(4, G.numberOfNodes());
	EXPECT_EQ(1, G.numberOfEdges());
	EXPECT_TRUE(G.hasNode(0));
	EXPECT_TRUE(G.hasNode(1));
	EXPECT_TRUE(G.hasNode(2));
	EXPECT_TRUE(G.hasNode(3));
}

TEST_F(IOGTest, tryReadingLFR) {
	std::string graphPath;
	std::string clustPath;

	std::cout << "[INPUT] LFR graph file path >" << std::endl;
	std::getline(std::cin, graphPath);

	std::cout << "[INPUT] clustering file path >" << std::endl;
	std::getline(std::cin, clustPath);

	EdgeListReader graphReader;
	EdgeListClusteringReader clusteringReader;

	Graph G = graphReader.read(graphPath);
	Clustering truth = clusteringReader.read(clustPath);

	LabelPropagation PLP;
	Clustering zeta = PLP.run(G);

	Modularity mod;
	INFO("static clustering quality: " << mod.getQuality(zeta, G));
	INFO("static clustering number of clusters: " << zeta.numberOfClusters());
	INFO("ground truth quality: " << mod.getQuality(truth, G));
	INFO("ground truth number of clusters: " << truth.numberOfClusters());

}

TEST_F(IOGTest, tryReadingSNAP) {
	std::string graphPath;

	std::cout << "[INPUT] SNAP graph file path >" << std::endl;
	std::getline(std::cin, graphPath);

	EdgeListReader graphReader;

	Graph G = graphReader.read(graphPath);

	INFO("n = " << G.numberOfNodes());
	INFO("m = " << G.numberOfEdges());

}

} /* namespace NetworKit */

#endif /* NOGTEST */
<|endoftext|>


<commit_before>/*-
 * Copyright 2012 Matthew Endsley
 * All rights reserved
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted providing 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.
 *
 * 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.
 */

/*
Compiling example:
$ g++ -o example example.cpp
*/

#include <string>
#include <vector>

#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netdb.h>

#include "http.h"

// directly embed the source here
extern "C" {
	#include "http.c"
	#include "header.c"
	#include "chunk.c"
}

// return a socket connected to a hostname, or -1
int connectsocket(const char* host, int port)
{

    addrinfo* result = NULL;
    sockaddr_in addr = {0};
    int s;

    if (getaddrinfo(host, NULL, NULL, &result))
        goto error;

    addr.sin_family = AF_INET;
    addr.sin_port = htons(port);
    addr.sin_addr.s_addr = INADDR_ANY;
    for (addrinfo* ai = result; ai != NULL; ai = ai->ai_next) {
        if (ai->ai_family != AF_INET)
            continue;

        const sockaddr_in *ai_in = (const sockaddr_in*)ai->ai_addr;
        addr.sin_addr = ai_in->sin_addr;
        break;
    }

    if (addr.sin_addr.s_addr == INADDR_ANY)
        goto error;

    s = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
    if (s == -1)
        goto error;

    if (connect(s, (const sockaddr*)&addr, sizeof(addr)))
        goto error;

    return s;

error:
    if (s != -1)
        close(s);
    if (result)
        freeaddrinfo(result);
    return -1;
}

// Response data/funcs
struct HttpResponse {
	std::vector<char> body;
    int code;
};

static void* response_realloc(void* opaque, void* ptr, int size)
{
    return realloc(ptr, size);
}

static void response_body(void* opaque, const char* data, int size)
{
    HttpResponse* response = (HttpResponse*)opaque;
    response->body.insert(response->body.end(), data, data + size);
}

static void response_header(void* opaque, const char* ckey, int nkey, const char* cvalue, int nvalue)
{ /* example doesn't care about headers */ }

static void response_code(void* opaque, int code)
{
    HttpResponse* response = (HttpResponse*)opaque;
    response->code = code;
}

static const http_funcs responseFuncs = {
    response_realloc,
    response_body,
    response_header,
    response_code,
};

int main()
{

    int conn = connectsocket("nothings.org", 80);
    if (conn < 0) {
        fprintf(stderr, "Failed to connect socket\n");
        return -1;
    }

    const char request[] = "GET / HTTP/1.0\r\nContent-Length: 0\r\n\r\n";
    int len = send(conn, request, sizeof(request) - 1, 0);
    if (len != sizeof(request) - 1) {
        fprintf(stderr, "Failed to send request\n");
        close(conn);
        return -1;
    }

    HttpResponse response;
    response.code = 0;

    http_roundtripper rt;
    http_init(&rt, responseFuncs, &response);

    bool needmore = true;
    char buffer[1024];
    while (needmore) {
        const char* data = buffer;
        int ndata = recv(conn, buffer, sizeof(buffer), 0);
        if (ndata <= 0) {
            fprintf(stderr, "Error receiving data\n");
            http_free(&rt);
            close(conn);
            return -1;
        }

        while (needmore && ndata) {
            int read;
            needmore = http_data(&rt, data, ndata, &read);
            ndata -= read;
            data += read;
        }
    }

    if (http_iserror(&rt)) {
        fprintf(stderr, "Error parsing data\n");
        http_free(&rt);
        close(conn);
        return -1;
    }

    http_free(&rt);
    close(conn);

    printf("Response: %d\n", response.code);
    if (!response.body.empty()) {
        printf("%s\n", &response.body[0]);
    }

    return 0;
}
<commit_msg>close depends on unistd.h - explicitly include it<commit_after>/*-
 * Copyright 2012 Matthew Endsley
 * All rights reserved
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted providing 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.
 *
 * 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.
 */

/*
Compiling example:
$ g++ -o example example.cpp
*/

#include <string>
#include <vector>

#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netdb.h>
#include <unistd.h>

#include "http.h"

// directly embed the source here
extern "C" {
	#include "http.c"
	#include "header.c"
	#include "chunk.c"
}

// return a socket connected to a hostname, or -1
int connectsocket(const char* host, int port)
{

    addrinfo* result = NULL;
    sockaddr_in addr = {0};
    int s;

    if (getaddrinfo(host, NULL, NULL, &result))
        goto error;

    addr.sin_family = AF_INET;
    addr.sin_port = htons(port);
    addr.sin_addr.s_addr = INADDR_ANY;
    for (addrinfo* ai = result; ai != NULL; ai = ai->ai_next) {
        if (ai->ai_family != AF_INET)
            continue;

        const sockaddr_in *ai_in = (const sockaddr_in*)ai->ai_addr;
        addr.sin_addr = ai_in->sin_addr;
        break;
    }

    if (addr.sin_addr.s_addr == INADDR_ANY)
        goto error;

    s = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
    if (s == -1)
        goto error;

    if (connect(s, (const sockaddr*)&addr, sizeof(addr)))
        goto error;

    return s;

error:
    if (s != -1)
        close(s);
    if (result)
        freeaddrinfo(result);
    return -1;
}

// Response data/funcs
struct HttpResponse {
	std::vector<char> body;
    int code;
};

static void* response_realloc(void* opaque, void* ptr, int size)
{
    return realloc(ptr, size);
}

static void response_body(void* opaque, const char* data, int size)
{
    HttpResponse* response = (HttpResponse*)opaque;
    response->body.insert(response->body.end(), data, data + size);
}

static void response_header(void* opaque, const char* ckey, int nkey, const char* cvalue, int nvalue)
{ /* example doesn't care about headers */ }

static void response_code(void* opaque, int code)
{
    HttpResponse* response = (HttpResponse*)opaque;
    response->code = code;
}

static const http_funcs responseFuncs = {
    response_realloc,
    response_body,
    response_header,
    response_code,
};

int main()
{

    int conn = connectsocket("nothings.org", 80);
    if (conn < 0) {
        fprintf(stderr, "Failed to connect socket\n");
        return -1;
    }

    const char request[] = "GET / HTTP/1.0\r\nContent-Length: 0\r\n\r\n";
    int len = send(conn, request, sizeof(request) - 1, 0);
    if (len != sizeof(request) - 1) {
        fprintf(stderr, "Failed to send request\n");
        close(conn);
        return -1;
    }

    HttpResponse response;
    response.code = 0;

    http_roundtripper rt;
    http_init(&rt, responseFuncs, &response);

    bool needmore = true;
    char buffer[1024];
    while (needmore) {
        const char* data = buffer;
        int ndata = recv(conn, buffer, sizeof(buffer), 0);
        if (ndata <= 0) {
            fprintf(stderr, "Error receiving data\n");
            http_free(&rt);
            close(conn);
            return -1;
        }

        while (needmore && ndata) {
            int read;
            needmore = http_data(&rt, data, ndata, &read);
            ndata -= read;
            data += read;
        }
    }

    if (http_iserror(&rt)) {
        fprintf(stderr, "Error parsing data\n");
        http_free(&rt);
        close(conn);
        return -1;
    }

    http_free(&rt);
    close(conn);

    printf("Response: %d\n", response.code);
    if (!response.body.empty()) {
        printf("%s\n", &response.body[0]);
    }

    return 0;
}
<|endoftext|>


<commit_before>/*
 * author: Max Kellermann <mk@cm4all.com>
 */

#include "istream_deflate.hxx"
#include "istream_internal.hxx"
#include "pool.hxx"
#include "util/Cast.hxx"
#include "util/ConstBuffer.hxx"
#include "util/WritableBuffer.hxx"
#include "util/StaticFifoBuffer.hxx"

#include <daemon/log.h>

#include <zlib.h>

#include <assert.h>

struct DeflateIstream {
    struct istream output;
    struct istream *input;
    bool z_initialized, z_stream_end;
    z_stream z;
    bool had_input, had_output;
    StaticFifoBuffer<uint8_t, 4096> buffer;

    DeflateIstream(struct pool &pool, struct istream &_input);
};

gcc_const
static GQuark
zlib_quark(void)
{
    return g_quark_from_static_string("zlib");
}

static void
deflate_close(DeflateIstream *defl)
{
    if (defl->z_initialized) {
        defl->z_initialized = false;
        deflateEnd(&defl->z);
    }
}

static void
deflate_abort(DeflateIstream *defl, GError *error)
{
    deflate_close(defl);

    if (defl->input != nullptr)
        istream_free_handler(&defl->input);

    istream_deinit_abort(&defl->output, error);
}

static voidpf z_alloc
(voidpf opaque, uInt items, uInt size)
{
    struct pool *pool = (struct pool *)opaque;

    return p_malloc(pool, items * size);
}

static void
z_free(voidpf opaque, voidpf address)
{
    (void)opaque;
    (void)address;
}

static int
deflate_initialize_z(DeflateIstream *defl)
{
    if (defl->z_initialized)
        return Z_OK;

    defl->z.zalloc = z_alloc;
    defl->z.zfree = z_free;
    defl->z.opaque = defl->output.pool;

    int err = deflateInit(&defl->z, Z_DEFAULT_COMPRESSION);
    if (err != Z_OK) {
        GError *error =
            g_error_new(zlib_quark(), err,
                        "deflateInit(Z_FINISH) failed: %d", err);
        deflate_abort(defl, error);
        return err;
    }

    defl->z_initialized = true;
    return Z_OK;
}

/**
 * Submit data from the buffer to our istream handler.
 *
 * @return the number of bytes which were handled, or 0 if the stream
 * was closed
 */
static size_t
deflate_try_write(DeflateIstream *defl)
{
    auto r = defl->buffer.Read();
    assert(!r.IsEmpty());

    size_t nbytes = istream_invoke_data(&defl->output, r.data, r.size);
    if (nbytes == 0)
        return 0;

    defl->buffer.Consume(nbytes);

    if (nbytes == r.size && defl->input == nullptr && defl->z_stream_end) {
        deflate_close(defl);
        istream_deinit_eof(&defl->output);
        return 0;
    }

    return nbytes;
}

/**
 * Starts to write to the buffer.
 *
 * @return a pointer to the writable buffer, or nullptr if there is no
 * room (our istream handler blocks) or if the stream was closed
 */
static WritableBuffer<void>
deflate_buffer_write(DeflateIstream *defl)
{
    auto w = defl->buffer.Write();
    if (w.IsEmpty() && deflate_try_write(defl) > 0)
        w = defl->buffer.Write();

    return w.ToVoid();
}

static void
deflate_try_flush(DeflateIstream *defl)
{
    assert(!defl->z_stream_end);

    auto w = deflate_buffer_write(defl);
    if (w.IsEmpty())
        return;

    defl->z.next_out = (Bytef *)w.data;
    defl->z.avail_out = (uInt)w.size;

    defl->z.next_in = nullptr;
    defl->z.avail_in = 0;

    int err = deflate(&defl->z, Z_SYNC_FLUSH);
    if (err != Z_OK) {
        GError *error =
            g_error_new(zlib_quark(), err,
                        "deflate(Z_SYNC_FLUSH) failed: %d", err);
        deflate_abort(defl, error);
        return;
    }

    defl->buffer.Append(w.size - (size_t)defl->z.avail_out);

    if (!defl->buffer.IsEmpty())
        deflate_try_write(defl);
}

/**
 * Read from our input until we have submitted some bytes to our
 * istream handler.
 */
static void
istream_deflate_force_read(DeflateIstream *defl)
{
    bool had_input = false;

    defl->had_output = false;

    pool_ref(defl->output.pool);

    while (1) {
        defl->had_input = false;
        istream_read(defl->input);
        if (defl->input == nullptr || defl->had_output) {
            pool_unref(defl->output.pool);
            return;
        }

        if (!defl->had_input)
            break;

        had_input = true;
    }

    pool_unref(defl->output.pool);

    if (had_input)
        deflate_try_flush(defl);
}

static void
deflate_try_finish(DeflateIstream *defl)
{
    assert(!defl->z_stream_end);

    auto w = deflate_buffer_write(defl);
    if (w.IsEmpty())
        return;

    defl->z.next_out = (Bytef *)w.data;
    defl->z.avail_out = (uInt)w.size;

    defl->z.next_in = nullptr;
    defl->z.avail_in = 0;

    int err = deflate(&defl->z, Z_FINISH);
    if (err == Z_STREAM_END)
        defl->z_stream_end = true;
    else if (err != Z_OK) {
        GError *error =
            g_error_new(zlib_quark(), err,
                        "deflate(Z_FINISH) failed: %d", err);
        deflate_abort(defl, error);
        return;
    }

    defl->buffer.Append(w.size - (size_t)defl->z.avail_out);

    if (defl->z_stream_end && defl->buffer.IsEmpty()) {
        deflate_close(defl);
        istream_deinit_eof(&defl->output);
    } else
        deflate_try_write(defl);
}

/*
 * istream handler
 *
 */

static size_t
deflate_input_data(const void *data, size_t length, void *ctx)
{
    DeflateIstream *defl = (DeflateIstream *)ctx;

    assert(defl->input != nullptr);

    auto w = deflate_buffer_write(defl);
    if (w.size < 64) /* reserve space for end-of-stream marker */
        return 0;

    int err = deflate_initialize_z(defl);
    if (err != Z_OK)
        return 0;

    defl->had_input = true;

    defl->z.next_out = (Bytef *)w.data;
    defl->z.avail_out = (uInt)w.size;

    defl->z.next_in = (Bytef *)const_cast<void *>(data);
    defl->z.avail_in = (uInt)length;

    do {
        err = deflate(&defl->z, Z_NO_FLUSH);
        if (err != Z_OK) {
            GError *error =
                g_error_new(zlib_quark(), err,
                            "deflate() failed: %d", err);
            deflate_abort(defl, error);
            return 0;
        }

        size_t nbytes = w.size - (size_t)defl->z.avail_out;
        if (nbytes > 0) {
            defl->had_output = true;
            defl->buffer.Append(nbytes);

            pool_ref(defl->output.pool);
            deflate_try_write(defl);

            if (!defl->z_initialized) {
                pool_unref(defl->output.pool);
                return 0;
            }

            pool_unref(defl->output.pool);
        } else
            break;

        w = deflate_buffer_write(defl);
        if (w.size < 64) /* reserve space for end-of-stream marker */
            break;

        defl->z.next_out = (Bytef *)w.data;
        defl->z.avail_out = (uInt)w.size;
    } while (defl->z.avail_in > 0);

    return length - (size_t)defl->z.avail_in;
}

static void
deflate_input_eof(void *ctx)
{
    DeflateIstream *defl = (DeflateIstream *)ctx;

    assert(defl->input != nullptr);
    defl->input = nullptr;

    int err = deflate_initialize_z(defl);
    if (err != Z_OK)
        return;

    deflate_try_finish(defl);
}

static void
deflate_input_abort(GError *error, void *ctx)
{
    DeflateIstream *defl = (DeflateIstream *)ctx;

    assert(defl->input != nullptr);
    defl->input = nullptr;

    deflate_close(defl);

    istream_deinit_abort(&defl->output, error);
}

static const struct istream_handler deflate_input_handler = {
    .data = deflate_input_data,
    .eof = deflate_input_eof,
    .abort = deflate_input_abort,
};

/*
 * istream implementation
 *
 */

static inline DeflateIstream *
istream_to_deflate(struct istream *istream)
{
    return &ContainerCast2(*istream, &DeflateIstream::output);
}

static void
istream_deflate_read(struct istream *istream)
{
    DeflateIstream *defl = istream_to_deflate(istream);

    if (!defl->buffer.IsEmpty())
        deflate_try_write(defl);
    else if (defl->input == nullptr)
        deflate_try_finish(defl);
    else
        istream_deflate_force_read(defl);
}

static void
istream_deflate_close(struct istream *istream)
{
    DeflateIstream *defl = istream_to_deflate(istream);

    deflate_close(defl);

    if (defl->input != nullptr)
        istream_close_handler(defl->input);

    istream_deinit(&defl->output);
}

static const struct istream_class istream_deflate = {
    .read = istream_deflate_read,
    .close = istream_deflate_close,
};

/*
 * constructor
 *
 */

inline
DeflateIstream::DeflateIstream(struct pool &pool, struct istream &_input)
    :z_initialized(false), z_stream_end(false)
{
    istream_init(&output, &istream_deflate, &pool);

    buffer.Clear();

    istream_assign_handler(&input, &_input,
                           &deflate_input_handler, this,
                           0);
}

struct istream *
istream_deflate_new(struct pool *pool, struct istream *input)
{
    assert(input != nullptr);
    assert(!istream_has_handler(input));

    auto *defl = NewFromPool<DeflateIstream>(*pool, *pool, *input);
    return &defl->output;
}
<commit_msg>istream_deflate: move code into the struct<commit_after>/*
 * author: Max Kellermann <mk@cm4all.com>
 */

#include "istream_deflate.hxx"
#include "istream_internal.hxx"
#include "pool.hxx"
#include "util/Cast.hxx"
#include "util/ConstBuffer.hxx"
#include "util/WritableBuffer.hxx"
#include "util/StaticFifoBuffer.hxx"

#include <daemon/log.h>

#include <zlib.h>

#include <assert.h>

struct DeflateIstream {
    struct istream output;
    struct istream *input;
    bool z_initialized, z_stream_end;
    z_stream z;
    bool had_input, had_output;
    StaticFifoBuffer<uint8_t, 4096> buffer;

    DeflateIstream(struct pool &pool, struct istream &_input);

    bool InitZlib();

    void DeinitZlib() {
        if (z_initialized) {
            z_initialized = false;
            deflateEnd(&z);
        }
    }

    void Abort(GError *error) {
        DeinitZlib();

        if (input != nullptr)
            istream_free_handler(&input);

        istream_deinit_abort(&output, error);
    }

    /**
     * Submit data from the buffer to our istream handler.
     *
     * @return the number of bytes which were handled, or 0 if the
     * stream was closed
     */
    size_t TryWrite();

    /**
     * Starts to write to the buffer.
     *
     * @return a pointer to the writable buffer, or nullptr if there is no
     * room (our istream handler blocks) or if the stream was closed
     */
    WritableBuffer<void> BufferWrite() {
        auto w = buffer.Write();
        if (w.IsEmpty() && TryWrite() > 0)
            w = buffer.Write();

        return w.ToVoid();
    }

    void TryFlush();

    /**
     * Read from our input until we have submitted some bytes to our
     * istream handler.
     */
    void ForceRead();

    void TryFinish();
};

gcc_const
static GQuark
zlib_quark(void)
{
    return g_quark_from_static_string("zlib");
}

static voidpf z_alloc
(voidpf opaque, uInt items, uInt size)
{
    struct pool *pool = (struct pool *)opaque;

    return p_malloc(pool, items * size);
}

static void
z_free(voidpf opaque, voidpf address)
{
    (void)opaque;
    (void)address;
}

bool
DeflateIstream::InitZlib()
{
    if (z_initialized)
        return true;

    z.zalloc = z_alloc;
    z.zfree = z_free;
    z.opaque = output.pool;

    int err = deflateInit(&z, Z_DEFAULT_COMPRESSION);
    if (err != Z_OK) {
        GError *error =
            g_error_new(zlib_quark(), err,
                        "deflateInit(Z_FINISH) failed: %d", err);
        Abort(error);
        return false;
    }

    z_initialized = true;
    return true;
}

size_t
DeflateIstream::TryWrite()
{
    auto r = buffer.Read();
    assert(!r.IsEmpty());

    size_t nbytes = istream_invoke_data(&output, r.data, r.size);
    if (nbytes == 0)
        return 0;

    buffer.Consume(nbytes);

    if (nbytes == r.size && input == nullptr && z_stream_end) {
        DeinitZlib();
        istream_deinit_eof(&output);
        return 0;
    }

    return nbytes;
}

inline void
DeflateIstream::TryFlush()
{
    assert(!z_stream_end);

    auto w = BufferWrite();
    if (w.IsEmpty())
        return;

    z.next_out = (Bytef *)w.data;
    z.avail_out = (uInt)w.size;

    z.next_in = nullptr;
    z.avail_in = 0;

    int err = deflate(&z, Z_SYNC_FLUSH);
    if (err != Z_OK) {
        GError *error =
            g_error_new(zlib_quark(), err,
                        "deflate(Z_SYNC_FLUSH) failed: %d", err);
        Abort(error);
        return;
    }

    buffer.Append(w.size - (size_t)z.avail_out);

    if (!buffer.IsEmpty())
        TryWrite();
}

inline
void
DeflateIstream::ForceRead()
{
    bool had_input2 = false;
    had_output = false;

    pool_ref(output.pool);

    while (1) {
        had_input = false;
        istream_read(input);
        if (input == nullptr || had_output) {
            pool_unref(output.pool);
            return;
        }

        if (!had_input)
            break;

        had_input2 = true;
    }

    pool_unref(output.pool);

    if (had_input2)
        TryFlush();
}

void
DeflateIstream::TryFinish()
{
    assert(!z_stream_end);

    auto w = BufferWrite();
    if (w.IsEmpty())
        return;

    z.next_out = (Bytef *)w.data;
    z.avail_out = (uInt)w.size;

    z.next_in = nullptr;
    z.avail_in = 0;

    int err = deflate(&z, Z_FINISH);
    if (err == Z_STREAM_END)
        z_stream_end = true;
    else if (err != Z_OK) {
        GError *error =
            g_error_new(zlib_quark(), err,
                        "deflate(Z_FINISH) failed: %d", err);
        Abort(error);
        return;
    }

    buffer.Append(w.size - (size_t)z.avail_out);

    if (z_stream_end && buffer.IsEmpty()) {
        DeinitZlib();
        istream_deinit_eof(&output);
    } else
        TryWrite();
}

/*
 * istream handler
 *
 */

static size_t
deflate_input_data(const void *data, size_t length, void *ctx)
{
    DeflateIstream *defl = (DeflateIstream *)ctx;

    assert(defl->input != nullptr);

    auto w = defl->BufferWrite();
    if (w.size < 64) /* reserve space for end-of-stream marker */
        return 0;

    if (!defl->InitZlib())
        return 0;

    defl->had_input = true;

    defl->z.next_out = (Bytef *)w.data;
    defl->z.avail_out = (uInt)w.size;

    defl->z.next_in = (Bytef *)const_cast<void *>(data);
    defl->z.avail_in = (uInt)length;

    do {
        auto err = deflate(&defl->z, Z_NO_FLUSH);
        if (err != Z_OK) {
            GError *error =
                g_error_new(zlib_quark(), err,
                            "deflate() failed: %d", err);
            defl->Abort(error);
            return 0;
        }

        size_t nbytes = w.size - (size_t)defl->z.avail_out;
        if (nbytes > 0) {
            defl->had_output = true;
            defl->buffer.Append(nbytes);

            pool_ref(defl->output.pool);
            defl->TryWrite();

            if (!defl->z_initialized) {
                pool_unref(defl->output.pool);
                return 0;
            }

            pool_unref(defl->output.pool);
        } else
            break;

        w = defl->BufferWrite();
        if (w.size < 64) /* reserve space for end-of-stream marker */
            break;

        defl->z.next_out = (Bytef *)w.data;
        defl->z.avail_out = (uInt)w.size;
    } while (defl->z.avail_in > 0);

    return length - (size_t)defl->z.avail_in;
}

static void
deflate_input_eof(void *ctx)
{
    DeflateIstream *defl = (DeflateIstream *)ctx;

    assert(defl->input != nullptr);
    defl->input = nullptr;

    if (!defl->InitZlib())
        return;

    defl->TryFinish();
}

static void
deflate_input_abort(GError *error, void *ctx)
{
    DeflateIstream *defl = (DeflateIstream *)ctx;

    assert(defl->input != nullptr);
    defl->input = nullptr;

    defl->DeinitZlib();

    istream_deinit_abort(&defl->output, error);
}

static const struct istream_handler deflate_input_handler = {
    .data = deflate_input_data,
    .eof = deflate_input_eof,
    .abort = deflate_input_abort,
};

/*
 * istream implementation
 *
 */

static inline DeflateIstream *
istream_to_deflate(struct istream *istream)
{
    return &ContainerCast2(*istream, &DeflateIstream::output);
}

static void
istream_deflate_read(struct istream *istream)
{
    DeflateIstream *defl = istream_to_deflate(istream);

    if (!defl->buffer.IsEmpty())
        defl->TryWrite();
    else if (defl->input == nullptr)
        defl->TryFinish();
    else
        defl->ForceRead();
}

static void
istream_deflate_close(struct istream *istream)
{
    DeflateIstream *defl = istream_to_deflate(istream);

    defl->DeinitZlib();

    if (defl->input != nullptr)
        istream_close_handler(defl->input);

    istream_deinit(&defl->output);
}

static const struct istream_class istream_deflate = {
    .read = istream_deflate_read,
    .close = istream_deflate_close,
};

/*
 * constructor
 *
 */

inline
DeflateIstream::DeflateIstream(struct pool &pool, struct istream &_input)
    :z_initialized(false), z_stream_end(false)
{
    istream_init(&output, &istream_deflate, &pool);

    buffer.Clear();

    istream_assign_handler(&input, &_input,
                           &deflate_input_handler, this,
                           0);
}

struct istream *
istream_deflate_new(struct pool *pool, struct istream *input)
{
    assert(input != nullptr);
    assert(!istream_has_handler(input));

    auto *defl = NewFromPool<DeflateIstream>(*pool, *pool, *input);
    return &defl->output;
}
<|endoftext|>


<commit_before>#include <stinkee_device.h>
#include <stinkee_signal.h>

#include <portaudio.h>

#include <cassert>
#include <iostream>

namespace {

static const int            NUM_CHANNELS = 1;
static const PaSampleFormat SAMPLE_TYPE  = paFloat32;

struct CbUserData
{
    std::size_t            processed;
    const stinkee::Signal& signal;
};

int paCallback(const void                     *input,
               void                           *output,
               unsigned long                   frameCount,
               const PaStreamCallbackTimeInfo *timeInfo,
               PaStreamCallbackFlags           statusFlags,
               void                           *userData);

}  // anonymous namespace

namespace stinkee {

Device::~Device()
{
    Pa_Terminate();
}

int Device::init() const
{
    PaError rc = Pa_Initialize();
    if (rc != paNoError) {
        std::cerr << "Failed to initialize portaudio: "
                  << Pa_GetErrorText(rc)
                  << std::endl;
    }

    return rc;
}

int Device::process(const Signal& signal) const
{
    PaError rc;
    CbUserData userData = { 0, signal };

    PaStream *audioStream;
    rc = Pa_OpenDefaultStream(
            &audioStream,
            0,
            NUM_CHANNELS,
            SAMPLE_TYPE,
            Signal::SAMPLING_RATE,
            paFramesPerBufferUnspecified,
            paCallback,
            &userData);

    if (rc != paNoError) {
        std::cerr << "Failed to open output stream: "
                  << Pa_GetErrorText(rc)
                  << std::endl;
        return rc;
    }

    rc = Pa_StartStream(audioStream);
    if (rc != paNoError) {
        std::cerr << "Failed to start stream: "
                  << Pa_GetErrorText(rc)
                  << std::endl;
        return rc;
    }

    Pa_Sleep(1000);

    rc = Pa_StopStream(audioStream);
    if (rc != paNoError) {
        std::cerr << "Failed to stop stream: "
                  << Pa_GetErrorText(rc)
                  << std::endl;
        return rc;
    }

    rc = Pa_CloseStream(audioStream);
    if (rc != paNoError) {
        std::cerr << "Failed to close stream: "
                  << Pa_GetErrorText(rc)
                  << std::endl;
        return rc;
    }

    assert(userData.processed == signal.frames().size());

    return 0;
}

}  // library namespace

namespace {

int paCallback(const void                     *input,
               void                           *output,
               unsigned long                   frameCount,
               const PaStreamCallbackTimeInfo *timeInfo,
               PaStreamCallbackFlags           statusFlags,
               void                           *userData)
{
    CbUserData *data = (CbUserData *)userData;
    const std::vector<float>& frames = data->signal.frames();
    float *out = (float *)output;

    for (std::size_t i = 0; i < frameCount; ++i) {
        if (data->processed < frames.size()) {
            *out = frames[data->processed++];
        }
        else {
            *out = 0.0;
        }
        ++out;
    }

    return data->processed < frames.size() ? paContinue : paComplete;
}

}  // anonymous namespace
<commit_msg>Set output stream parameter to default low latency<commit_after>#include <stinkee_device.h>
#include <stinkee_signal.h>

#include <portaudio.h>

#include <cassert>
#include <iostream>

namespace {

static const int            NUM_CHANNELS = 1;
static const PaSampleFormat SAMPLE_TYPE  = paFloat32;

struct CbUserData
{
    std::size_t            processed;
    const stinkee::Signal& signal;
};

int paCallback(const void                     *input,
               void                           *output,
               unsigned long                   frameCount,
               const PaStreamCallbackTimeInfo *timeInfo,
               PaStreamCallbackFlags           statusFlags,
               void                           *userData);

}  // anonymous namespace

namespace stinkee {

Device::~Device()
{
    Pa_Terminate();
}

int Device::init() const
{
    PaError rc = Pa_Initialize();
    if (rc != paNoError) {
        std::cerr << "Failed to initialize portaudio: "
                  << Pa_GetErrorText(rc)
                  << std::endl;
    }

    return rc;
}

int Device::process(const Signal& signal) const
{
    PaError rc;
    CbUserData userData = { 0, signal };

    PaStreamParameters outputParams;
    outputParams.device = Pa_GetDefaultOutputDevice();
    if (outputParams.device == paNoDevice) {
        std::cerr << "No audio output device available" << std::endl;
        return paNoDevice;
    }

    const PaDeviceInfo *deviceInfo = Pa_GetDeviceInfo(outputParams.device);
    outputParams.channelCount = NUM_CHANNELS;
    outputParams.sampleFormat = SAMPLE_TYPE;
    outputParams.suggestedLatency = deviceInfo->defaultLowOutputLatency;
    outputParams.hostApiSpecificStreamInfo = NULL;

    PaStream *audioStream;
    rc = Pa_OpenStream(
            &audioStream,
            NULL,
            &outputParams,
            Signal::SAMPLING_RATE,
            paFramesPerBufferUnspecified,
            paClipOff | paDitherOff,
            paCallback,
            &userData);

    if (rc != paNoError) {
        std::cerr << "Failed to open output stream: "
                  << Pa_GetErrorText(rc)
                  << std::endl;
        return rc;
    }

    rc = Pa_StartStream(audioStream);
    if (rc != paNoError) {
        std::cerr << "Failed to start stream: "
                  << Pa_GetErrorText(rc)
                  << std::endl;
        return rc;
    }

    Pa_Sleep(1000);

    rc = Pa_StopStream(audioStream);
    if (rc != paNoError) {
        std::cerr << "Failed to stop stream: "
                  << Pa_GetErrorText(rc)
                  << std::endl;
        return rc;
    }

    rc = Pa_CloseStream(audioStream);
    if (rc != paNoError) {
        std::cerr << "Failed to close stream: "
                  << Pa_GetErrorText(rc)
                  << std::endl;
        return rc;
    }

    assert(userData.processed == signal.frames().size());

    return 0;
}

}  // library namespace

namespace {

int paCallback(const void                     *input,
               void                           *output,
               unsigned long                   frameCount,
               const PaStreamCallbackTimeInfo *timeInfo,
               PaStreamCallbackFlags           statusFlags,
               void                           *userData)
{
    CbUserData *data = (CbUserData *)userData;
    const std::vector<float>& frames = data->signal.frames();
    float *out = (float *)output;

    for (std::size_t i = 0; i < frameCount; ++i) {
        if (data->processed < frames.size()) {
            *out = frames[data->processed++];
        }
        else {
            *out = 0.0;
        }
        ++out;
    }

    return data->processed < frames.size() ? paContinue : paComplete;
}

}  // anonymous namespace
<|endoftext|>


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

#include <fstream>
#include <stdexcept>
#ifndef _WIN32
#include <fcntl.h>
#include <sys/stat.h>
#include <sys/mman.h>
#include <sys/types.h>
#include <unistd.h>
#endif
#include "FileMapping.h"

/*! namespace for all things pbrt parser, both syntactical *and* semantical parser */
namespace pbrt {
  /*! namespace for syntactic-only parser - this allows to distringuish
    high-level objects such as shapes from objects or transforms,
    but does *not* make any difference between what types of
    shapes, what their parameters mean, etc. Basically, at this
    level a triangle mesh is nothing but a geometry that has a string
    with a given name, and parameters of given names and types */
  namespace syntactic {

    FileMapping::FileMapping(const std::string &fname) : mapping(nullptr), num_bytes(0) {
#ifdef _WIN32
	  file = CreateFile(fname.c_str(), GENERIC_READ,
	  		FILE_SHARE_READ, nullptr, OPEN_EXISTING,
	  		FILE_ATTRIBUTE_NORMAL, nullptr);
	  if (file == INVALID_HANDLE_VALUE) {
	  	throw std::runtime_error("Failed to open file " + fname);
	  }

	  LARGE_INTEGER file_size;
	  GetFileSizeEx(file, &file_size);
	  if (file_size.QuadPart == 0) {
	  	throw std::runtime_error("Cannot map 0 size file");
	  }

	  mapping_handle = CreateFileMapping(file, nullptr, PAGE_READONLY, 0, 0, nullptr);
	  if (mapping_handle == INVALID_HANDLE_VALUE) {
	  	throw std::runtime_error("Failed to create file mapping for " + fname);
	  }

	  num_bytes = file_size.QuadPart;
	  mapping = MapViewOfFile(mapping_handle, FILE_MAP_READ, 0, 0, num_bytes);
	  if (!mapping) {
	  	throw std::runtime_error("Failed to create mapped view of file " + fname);
	  }
#else
	  file = open(fname.c_str(), O_RDONLY);
	  if (file == -1) {
	  	perror("failed opening file");
	  	fflush(0);
	  	throw std::runtime_error("Failed to open file " + fname);
	  }

	  struct stat stat_buf;
	  fstat(file, &stat_buf);
	  num_bytes = stat_buf.st_size;

	  mapping = mmap(NULL, num_bytes, PROT_READ, MAP_SHARED, file, 0);
	  if (!mapping) {
	  	throw std::runtime_error("Failed to map file!");
	  }
#endif
}
    FileMapping::FileMapping(FileMapping &&fm)
	  : mapping(fm.mapping), num_bytes(fm.num_bytes), file(fm.file)
#ifdef _WIN32
	  , mapping_handle(fm.mapping_handle)
#endif
    {
	  fm.mapping = nullptr;
	  fm.num_bytes = 0;
#ifdef _WIN32
	  fm.file = INVALID_HANDLE_VALUE;
	  fm.mapping_handle = INVALID_HANDLE_VALUE;
#else
	  fm.file = -1;
#endif
    }
    FileMapping::~FileMapping() {
	  if (mapping) {
#ifdef _WIN32
		UnmapViewOfFile(mapping);
		CloseHandle(mapping_handle);
		CloseHandle(file);
#else
		munmap(mapping, num_bytes);
		close(file);
#endif
	  }
    }
    FileMapping& FileMapping::operator=(FileMapping &&fm) {
	  mapping = fm.mapping;
	  num_bytes = fm.num_bytes;
	  file = fm.file;
#ifdef _WIN32
	  mapping_handle = fm.mapping_handle;
#endif

	  fm.mapping = nullptr;
	  fm.num_bytes = 0;
#ifdef _WIN32
	  fm.file = INVALID_HANDLE_VALUE;
	  fm.mapping_handle = INVALID_HANDLE_VALUE;
#else
	  fm.file = -1;
#endif

	  return *this;
    }
    const uint8_t* FileMapping::data() const {
      return static_cast<uint8_t*>(mapping);
    }
    size_t FileMapping::nbytes() const {
      return num_bytes;
    }
  } // ::syntactic
} // ::pbrt
<commit_msg>fix compilation error on win32 (CreateFile)<commit_after>// ======================================================================== //
// Copyright 2015-2019 Ingo Wald                                            //
//                                                                          //
// Licensed under the Apache License, Version 2.0 (the "License");          //
// you may not use this file except in compliance with the License.         //
// You may obtain a copy of the License at                                  //
//                                                                          //
//     http://www.apache.org/licenses/LICENSE-2.0                           //
//                                                                          //
// Unless required by applicable law or agreed to in writing, software      //
// distributed under the License is distributed on an "AS IS" BASIS,        //
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. //
// See the License for the specific language governing permissions and      //
// limitations under the License.                                           //
// ======================================================================== //

#include <fstream>
#include <stdexcept>
#ifndef _WIN32
#include <fcntl.h>
#include <sys/stat.h>
#include <sys/mman.h>
#include <sys/types.h>
#include <unistd.h>
#endif
#include "FileMapping.h"

/*! namespace for all things pbrt parser, both syntactical *and* semantical parser */
namespace pbrt {
  /*! namespace for syntactic-only parser - this allows to distringuish
    high-level objects such as shapes from objects or transforms,
    but does *not* make any difference between what types of
    shapes, what their parameters mean, etc. Basically, at this
    level a triangle mesh is nothing but a geometry that has a string
    with a given name, and parameters of given names and types */
  namespace syntactic {

    FileMapping::FileMapping(const std::string &fname) : mapping(nullptr), num_bytes(0) {
#ifdef _WIN32
	  file = CreateFileA(fname.c_str(), GENERIC_READ,
	  		FILE_SHARE_READ, nullptr, OPEN_EXISTING,
	  		FILE_ATTRIBUTE_NORMAL, nullptr);
	  if (file == INVALID_HANDLE_VALUE) {
	  	throw std::runtime_error("Failed to open file " + fname);
	  }

	  LARGE_INTEGER file_size;
	  GetFileSizeEx(file, &file_size);
	  if (file_size.QuadPart == 0) {
	  	throw std::runtime_error("Cannot map 0 size file");
	  }

	  mapping_handle = CreateFileMapping(file, nullptr, PAGE_READONLY, 0, 0, nullptr);
	  if (mapping_handle == INVALID_HANDLE_VALUE) {
	  	throw std::runtime_error("Failed to create file mapping for " + fname);
	  }

	  num_bytes = file_size.QuadPart;
	  mapping = MapViewOfFile(mapping_handle, FILE_MAP_READ, 0, 0, num_bytes);
	  if (!mapping) {
	  	throw std::runtime_error("Failed to create mapped view of file " + fname);
	  }
#else
	  file = open(fname.c_str(), O_RDONLY);
	  if (file == -1) {
	  	perror("failed opening file");
	  	fflush(0);
	  	throw std::runtime_error("Failed to open file " + fname);
	  }

	  struct stat stat_buf;
	  fstat(file, &stat_buf);
	  num_bytes = stat_buf.st_size;

	  mapping = mmap(NULL, num_bytes, PROT_READ, MAP_SHARED, file, 0);
	  if (!mapping) {
	  	throw std::runtime_error("Failed to map file!");
	  }
#endif
}
    FileMapping::FileMapping(FileMapping &&fm)
	  : mapping(fm.mapping), num_bytes(fm.num_bytes), file(fm.file)
#ifdef _WIN32
	  , mapping_handle(fm.mapping_handle)
#endif
    {
	  fm.mapping = nullptr;
	  fm.num_bytes = 0;
#ifdef _WIN32
	  fm.file = INVALID_HANDLE_VALUE;
	  fm.mapping_handle = INVALID_HANDLE_VALUE;
#else
	  fm.file = -1;
#endif
    }
    FileMapping::~FileMapping() {
	  if (mapping) {
#ifdef _WIN32
		UnmapViewOfFile(mapping);
		CloseHandle(mapping_handle);
		CloseHandle(file);
#else
		munmap(mapping, num_bytes);
		close(file);
#endif
	  }
    }
    FileMapping& FileMapping::operator=(FileMapping &&fm) {
	  mapping = fm.mapping;
	  num_bytes = fm.num_bytes;
	  file = fm.file;
#ifdef _WIN32
	  mapping_handle = fm.mapping_handle;
#endif

	  fm.mapping = nullptr;
	  fm.num_bytes = 0;
#ifdef _WIN32
	  fm.file = INVALID_HANDLE_VALUE;
	  fm.mapping_handle = INVALID_HANDLE_VALUE;
#else
	  fm.file = -1;
#endif

	  return *this;
    }
    const uint8_t* FileMapping::data() const {
      return static_cast<uint8_t*>(mapping);
    }
    size_t FileMapping::nbytes() const {
      return num_bytes;
    }
  } // ::syntactic
} // ::pbrt
<|endoftext|>


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

#ifndef _SFXPOOLITEM_HXX //autogen
#include <svtools/poolitem.hxx>
#endif

#ifndef INCLUDED_SWDLLAPI_H
#include "swdllapi.h"
#endif
#ifndef _HINTIDS_HXX
#include <hintids.hxx>
#endif
#ifndef _FORMAT_HXX //autogen
#include <format.hxx>
#endif
#ifndef _CALBCK_HXX //autogen
#include <calbck.hxx>
#endif

class SwPageDesc;
class SwHistory;
class SwPaM;
class IntlWrapper;

//Pagedescriptor
//Client vom SwPageDesc der durch das Attribut "beschrieben" wird.

#define IVER_FMTPAGEDESC_NOAUTO ((USHORT)0x0001)
#define IVER_FMTPAGEDESC_LONGPAGE   ((USHORT)0x0002)

class SW_DLLPUBLIC SwFmtPageDesc : public SfxPoolItem, public SwClient
{
    // diese "Doc"-Funktion ist friend, um nach dem kopieren das
    // Auto-Flag setzen zu koennen !!
    friend BOOL InsAttr( SwDoc*, const SwPaM &, const SfxItemSet&, USHORT,
                        SwHistory* );
    USHORT nNumOffset;          // Seitennummer Offset
    USHORT nDescNameIdx;        // SW3-Reader: Stringpool-Index des Vorlagennamens
    SwModify* pDefinedIn;       // Verweis auf das Objekt, in dem das
                                // Attribut gesetzt wurde (CntntNode/Format)

public:
    SwFmtPageDesc( const SwPageDesc *pDesc = 0 );
    SwFmtPageDesc( const SwFmtPageDesc &rCpy );
    SwFmtPageDesc &operator=( const SwFmtPageDesc &rCpy );
    ~SwFmtPageDesc();

    TYPEINFO();

    // "pure virtual Methoden" vom SfxPoolItem
    virtual int             operator==( const SfxPoolItem& ) const;
    virtual SfxPoolItem*    Clone( SfxItemPool* pPool = 0 ) const;
    virtual SfxPoolItem*    Create(SvStream &, USHORT nVer) const;
    virtual SvStream&       Store(SvStream &, USHORT nIVer) const;
    virtual SfxItemPresentation GetPresentation( SfxItemPresentation ePres,
                                    SfxMapUnit eCoreMetric,
                                    SfxMapUnit ePresMetric,
                                    String &rText,
                                    const IntlWrapper*    pIntl = 0 ) const;
    virtual USHORT          GetVersion( USHORT nFFVer ) const;
    virtual BOOL             QueryValue( com::sun::star::uno::Any& rVal, BYTE nMemberId = 0 ) const;
    virtual BOOL             PutValue( const com::sun::star::uno::Any& rVal, BYTE nMemberId = 0 );

    virtual void Modify( SfxPoolItem *pOld, SfxPoolItem *pNew );

          SwPageDesc *GetPageDesc() { return (SwPageDesc*)GetRegisteredIn(); }
    const SwPageDesc *GetPageDesc() const { return (SwPageDesc*)GetRegisteredIn(); }

    USHORT  GetNumOffset() const        { return nNumOffset; }
    void    SetNumOffset( USHORT nNum ) { nNumOffset = nNum; }

    // erfrage/setze, wo drin das Attribut verankert ist
    inline const SwModify* GetDefinedIn() const { return pDefinedIn; }
    void ChgDefinedIn( const SwModify* pNew ) { pDefinedIn = (SwModify*)pNew; }

    // fuer den SW3-Reader:
    USHORT GetDescNameIdx() const { return nDescNameIdx; }
    void SetDescNameIdx( USHORT n ) { nDescNameIdx = n;  }
};

inline const SwFmtPageDesc &SwAttrSet::GetPageDesc(BOOL bInP) const
    { return (const SwFmtPageDesc&)Get( RES_PAGEDESC,bInP); }

inline const SwFmtPageDesc &SwFmt::GetPageDesc(BOOL bInP) const
    { return aSet.GetPageDesc(bInP); }

#endif

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

#ifndef _SFXPOOLITEM_HXX //autogen
#include <svtools/poolitem.hxx>
#endif

#ifndef INCLUDED_SWDLLAPI_H
#include "swdllapi.h"
#endif
#ifndef _HINTIDS_HXX
#include <hintids.hxx>
#endif
#ifndef _FORMAT_HXX //autogen
#include <format.hxx>
#endif
#ifndef _CALBCK_HXX //autogen
#include <calbck.hxx>
#endif

class SwPageDesc;
class SwHistory;
class SwPaM;
class IntlWrapper;

//Pagedescriptor
//Client vom SwPageDesc der durch das Attribut "beschrieben" wird.

#define IVER_FMTPAGEDESC_NOAUTO ((USHORT)0x0001)
#define IVER_FMTPAGEDESC_LONGPAGE   ((USHORT)0x0002)

class SW_DLLPUBLIC SwFmtPageDesc : public SfxPoolItem, public SwClient
{
    // diese "Doc"-Funktion ist friend, um nach dem kopieren das
    // Auto-Flag setzen zu koennen !!
    friend BOOL InsAttr( SwDoc*, const SwPaM &, const SfxItemSet&, USHORT,
                        SwHistory* );
    USHORT nNumOffset;          // Seitennummer Offset
    USHORT nDescNameIdx;        // SW3-Reader: Stringpool-Index des Vorlagennamens
    SwModify* pDefinedIn;       // Verweis auf das Objekt, in dem das
                                // Attribut gesetzt wurde (CntntNode/Format)

public:
    SwFmtPageDesc( const SwPageDesc *pDesc = 0 );
    SwFmtPageDesc( const SwFmtPageDesc &rCpy );
    SwFmtPageDesc &operator=( const SwFmtPageDesc &rCpy );
    ~SwFmtPageDesc();

    TYPEINFO();

    // "pure virtual Methoden" vom SfxPoolItem
    virtual int             operator==( const SfxPoolItem& ) const;
    virtual SfxPoolItem*    Clone( SfxItemPool* pPool = 0 ) const;
    virtual SfxItemPresentation GetPresentation( SfxItemPresentation ePres,
                                    SfxMapUnit eCoreMetric,
                                    SfxMapUnit ePresMetric,
                                    String &rText,
                                    const IntlWrapper*    pIntl = 0 ) const;
    virtual BOOL             QueryValue( com::sun::star::uno::Any& rVal, BYTE nMemberId = 0 ) const;
    virtual BOOL             PutValue( const com::sun::star::uno::Any& rVal, BYTE nMemberId = 0 );

    virtual void Modify( SfxPoolItem *pOld, SfxPoolItem *pNew );

          SwPageDesc *GetPageDesc() { return (SwPageDesc*)GetRegisteredIn(); }
    const SwPageDesc *GetPageDesc() const { return (SwPageDesc*)GetRegisteredIn(); }

    USHORT  GetNumOffset() const        { return nNumOffset; }
    void    SetNumOffset( USHORT nNum ) { nNumOffset = nNum; }

    // erfrage/setze, wo drin das Attribut verankert ist
    inline const SwModify* GetDefinedIn() const { return pDefinedIn; }
    void ChgDefinedIn( const SwModify* pNew ) { pDefinedIn = (SwModify*)pNew; }

    // fuer den SW3-Reader:
    USHORT GetDescNameIdx() const { return nDescNameIdx; }
    void SetDescNameIdx( USHORT n ) { nDescNameIdx = n;  }
};

inline const SwFmtPageDesc &SwAttrSet::GetPageDesc(BOOL bInP) const
    { return (const SwFmtPageDesc&)Get( RES_PAGEDESC,bInP); }

inline const SwFmtPageDesc &SwFmt::GetPageDesc(BOOL bInP) const
    { return aSet.GetPageDesc(bInP); }

#endif

<|endoftext|>