<commit_before>// Copyright (c) 2013 Intel Corporation. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

// On Tizen installing applications requires super-user powers primarily because
// some pieces of information of the application are put on globally accessible
// locations. This helper will run with super-user powers (via suid) and will
// be called by Crosswalk (now running as a normal user) so all the activities
// that required 'root' access are done by a small code base.

#if defined(OS_TIZEN_MOBILE)
#include <pkgmgr/pkgmgr_parser.h>
#else
// So we can compile this on Linux Desktop
static int pkgmgr_parser_parse_manifest_for_installation(
    const char* path, char *const tagv[]) {
  return 0;
}

static int pkgmgr_parser_parse_manifest_for_uninstallation(
    const char* path, char *const tagv[]) {
  return 0;
}

#endif

#include "base/files/file_path.h"
#include "base/file_util.h"

namespace {

const base::FilePath kIconDir("/opt/share/icons/default/small/");
const base::FilePath kXmlDir("/opt/share/packages/");
const base::FilePath kXWalkLauncherBinary("/usr/bin/xwalk-launcher");

class FileDeleter {
 public:
  FileDeleter(const base::FilePath& path, bool recursive)
      : path_(path),
        recursive_(recursive) {}

  ~FileDeleter() {
    if (path_.empty())
      return;

    base::DeleteFile(path_, recursive_);
  }

  void Dismiss() {
    path_.clear();
  }

 private:
  base::FilePath path_;
  bool recursive_;
};

bool InstallApplication(const char* appid, const char* xmlpath,
                        const char* iconpath) {
  base::FilePath icon_src(iconpath);
  // icon_dst == /opt/share/icons/default/small/<appid>.png
  // FIXME(vcgomes): Add support for more icon types
  base::FilePath icon_dst = kIconDir.Append(std::string(appid) + ".png");
  if (!base::CopyFile(icon_src, icon_dst)) {
    fprintf(stdout, "Couldn't copy application icon to '%s'\n",
            icon_dst.value().c_str());
    return false;
  }

  FileDeleter icon_cleaner(icon_dst, false);

  base::FilePath xml_src(xmlpath);
  base::FilePath xml_dst = kXmlDir.Append(std::string(appid) + ".xml");
  if (!base::CopyFile(xml_src, xml_dst)) {
    fprintf(stdout, "Couldn't copy application XML metadata to '%s'\n",
            xml_dst.value().c_str());
    return false;
  }

  FileDeleter xml_cleaner(xml_dst, false);

  if (pkgmgr_parser_parse_manifest_for_installation(xmlpath, NULL)) {
    fprintf(stdout, "Couldn't parse manifest XML '%s'\n", xmlpath);
    return false;
  }

  icon_cleaner.Dismiss();
  xml_cleaner.Dismiss();

  return true;
}

bool UninstallApplication(const char* appid) {
  bool result = true;
  char iconname[PATH_MAX];

  // FIXME(vcgomes): Add support for more icon types
  base::FilePath icon_dst = kIconDir.Append(std::string(appid) + ".png");
  if (!base::DeleteFile(icon_dst, false)) {
    fprintf(stdout, "Couldn't delete '%s'\n", icon_dst.value().c_str());
    result = false;
  }

  base::FilePath xmlpath(kXmlDir);
  xmlpath = xmlpath.Append(std::string(appid) + ".xml");

  int ret = pkgmgr_parser_parse_manifest_for_uninstallation(
      xmlpath.value().c_str(), NULL);
  if (ret) {
    fprintf(stdout, "Couldn't parse manifest XML '%s'\n",
            xmlpath.value().c_str());
    result = false;
  }

  if (!base::DeleteFile(xmlpath, false)) {
    fprintf(stdout, "Couldn't delete '%s'\n", xmlpath.value().c_str());
    result = false;
  }

  return result;
}

int usage(const char* program) {
  fprintf(stdout, "%s - Crosswalk Tizen Application Installation helper\n\n",
          basename(program));
  fprintf(stdout, "Usage: \n"
          "\t%s --install <appid> <xml> <icon>\n"
          "\t%s --uninstall <appid>\n",
          program, program);
  return 1;
}

}  // namespace

int main(int argc, char *argv[]) {
  bool result = false;

  if (argc <= 2)
    return usage(argv[0]);

  if (!strcmp(argv[1], "--install")) {
    if (argc != 5)
      return usage(argv[0]);

    result = InstallApplication(argv[2], argv[3], argv[4]);
  } else if (!strcmp(argv[1], "--uninstall")) {
    if (argc != 3)
      return usage(argv[0]);

    result = UninstallApplication(argv[2]);
  } else {
    return usage(argv[0]);
  }

  // Convetion is to return 0 on success.
  return result ? 0 : 1;
}
<commit_msg>[Application][Tizen] Change the effective UID of the application to 'root'<commit_after>// Copyright (c) 2013 Intel Corporation. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

// On Tizen installing applications requires super-user powers primarily because
// some pieces of information of the application are put on globally accessible
// locations. This helper will run with super-user powers (via suid) and will
// be called by Crosswalk (now running as a normal user) so all the activities
// that required 'root' access are done by a small code base.

#if defined(OS_TIZEN_MOBILE)
#include <pkgmgr/pkgmgr_parser.h>
#else
// So we can compile this on Linux Desktop
static int pkgmgr_parser_parse_manifest_for_installation(
    const char* path, char *const tagv[]) {
  return 0;
}

static int pkgmgr_parser_parse_manifest_for_uninstallation(
    const char* path, char *const tagv[]) {
  return 0;
}

#endif

#include "base/files/file_path.h"
#include "base/file_util.h"

namespace {

const base::FilePath kIconDir("/opt/share/icons/default/small/");
const base::FilePath kXmlDir("/opt/share/packages/");
const base::FilePath kXWalkLauncherBinary("/usr/bin/xwalk-launcher");

class FileDeleter {
 public:
  FileDeleter(const base::FilePath& path, bool recursive)
      : path_(path),
        recursive_(recursive) {}

  ~FileDeleter() {
    if (path_.empty())
      return;

    base::DeleteFile(path_, recursive_);
  }

  void Dismiss() {
    path_.clear();
  }

 private:
  base::FilePath path_;
  bool recursive_;
};

bool InstallApplication(const char* appid, const char* xmlpath,
                        const char* iconpath) {
  base::FilePath icon_src(iconpath);
  // icon_dst == /opt/share/icons/default/small/<appid>.png
  // FIXME(vcgomes): Add support for more icon types
  base::FilePath icon_dst = kIconDir.Append(std::string(appid) + ".png");
  if (!base::CopyFile(icon_src, icon_dst)) {
    fprintf(stdout, "Couldn't copy application icon to '%s'\n",
            icon_dst.value().c_str());
    return false;
  }

  FileDeleter icon_cleaner(icon_dst, false);

  base::FilePath xml_src(xmlpath);
  base::FilePath xml_dst = kXmlDir.Append(std::string(appid) + ".xml");
  if (!base::CopyFile(xml_src, xml_dst)) {
    fprintf(stdout, "Couldn't copy application XML metadata to '%s'\n",
            xml_dst.value().c_str());
    return false;
  }

  FileDeleter xml_cleaner(xml_dst, false);

  if (pkgmgr_parser_parse_manifest_for_installation(xmlpath, NULL)) {
    fprintf(stdout, "Couldn't parse manifest XML '%s'\n", xmlpath);
    return false;
  }

  icon_cleaner.Dismiss();
  xml_cleaner.Dismiss();

  return true;
}

bool UninstallApplication(const char* appid) {
  bool result = true;
  char iconname[PATH_MAX];

  // FIXME(vcgomes): Add support for more icon types
  base::FilePath icon_dst = kIconDir.Append(std::string(appid) + ".png");
  if (!base::DeleteFile(icon_dst, false)) {
    fprintf(stdout, "Couldn't delete '%s'\n", icon_dst.value().c_str());
    result = false;
  }

  base::FilePath xmlpath(kXmlDir);
  xmlpath = xmlpath.Append(std::string(appid) + ".xml");

  int ret = pkgmgr_parser_parse_manifest_for_uninstallation(
      xmlpath.value().c_str(), NULL);
  if (ret) {
    fprintf(stdout, "Couldn't parse manifest XML '%s'\n",
            xmlpath.value().c_str());
    result = false;
  }

  if (!base::DeleteFile(xmlpath, false)) {
    fprintf(stdout, "Couldn't delete '%s'\n", xmlpath.value().c_str());
    result = false;
  }

  return result;
}

int usage(const char* program) {
  fprintf(stdout, "%s - Crosswalk Tizen Application Installation helper\n\n",
          basename(program));
  fprintf(stdout, "Usage: \n"
          "\t%s --install <appid> <xml> <icon>\n"
          "\t%s --uninstall <appid>\n",
          program, program);
  return 1;
}

}  // namespace

int main(int argc, char *argv[]) {
  bool result = false;

  if (argc <= 2)
    return usage(argv[0]);

  // When installing an application on Tizen, the libraries used require
  // some steps to be run as root (UID 0) and fail otherwise, so we force
  // this tool to assume the root UID.
  if (setuid(0)) {
    fprintf(stderr, "Make sure '%s' is set-user-ID-root\n", argv[0]);
    return 1;;
  }

  if (!strcmp(argv[1], "--install")) {
    if (argc != 5)
      return usage(argv[0]);

    result = InstallApplication(argv[2], argv[3], argv[4]);
  } else if (!strcmp(argv[1], "--uninstall")) {
    if (argc != 3)
      return usage(argv[0]);

    result = UninstallApplication(argv[2]);
  } else {
    return usage(argv[0]);
  }

  // Convetion is to return 0 on success.
  return result ? 0 : 1;
}
<|endoftext|>


<commit_before>#include "palabos3D.h"
#include "palabos3D.hh"
#include <vector>
#include <cmath>

using namespace plb;
using namespace plb::descriptors;
using namespace std;

typedef double T;
typedef Array<T,3> Velocity;
//#define DESCRIPTOR descriptors::D3Q27Descriptor
#define DESCRIPTOR MRTD3Q19Descriptor
 typedef MRTdynamics<T,DESCRIPTOR> BackgroundDynamics;
 typedef AnechoicMRTdynamics<T,DESCRIPTOR> AnechoicBackgroundDynamics;

// ---------------------------------------------
// Includes of acoustics resources
#include "acoustics/acoustics3D.h"
using namespace plb_acoustics_3D;
// ---------------------------------------------

const T rho0 = 1;
const T drho = rho0/10;

void writeGifs(MultiBlockLattice3D<T,DESCRIPTOR>& lattice, plint iter){
    const plint nx = lattice.getNx();
    const plint ny = lattice.getNy();
    const plint nz = lattice.getNz();

    const plint imSize = 600;
    ImageWriter<T> imageWriter("leeloo");

    Box3D slice(0, nx-1, 0, ny-1, nz/2, nz/2);
    //imageWriter.writeGif(createFileName("u", iT, 6),
     //*computeDensity(lattice), );

    imageWriter.writeGif( createFileName("rho", iter, 6),
    *computeDensity(lattice, slice),
    (T) rho0 - drho/1000000, (T) rho0 + drho/1000000, imSize, imSize);
}

void writeVTK(MultiBlockLattice3D<T,DESCRIPTOR>& lattice, plint iter){
        VtkImageOutput3D<T> vtkOut(createFileName("vtk", iter, 6), 1.);
        vtkOut.writeData<float>(*computeDensity(lattice), "density", 1.);
        vtkOut.writeData<3,float>(*computeVelocity(lattice), "velocity", 1.);
}

int main(int argc, char **argv){
    plbInit(&argc, &argv);
    std::string fNameOut = "tmp";

    const plint nx = 150;
    const plint ny = 100;
    const plint nz = 100;
    const T lattice_speed_sound = 1/sqrt(3);

    const T omega = 1.985;
    const plint maxT = 120000;

    Array<T,3> u0(0, 0, 0);

    global::directories().setOutputDir(fNameOut+"/");

    // Setting anechoic dynamics like this way
    MultiBlockLattice3D<T, DESCRIPTOR> lattice(nx, ny, nz,  new AnechoicBackgroundDynamics(omega));
    defineDynamics(lattice, lattice.getBoundingBox(), new BackgroundDynamics(omega));

    pcout << "Creation of the lattice." << endl;

    // Switch off periodicity.
    lattice.periodicity().toggleAll(false);

    pcout << "Initilization of rho and u." << endl;
    initializeAtEquilibrium( lattice, lattice.getBoundingBox(), rho0 , u0 );

    T rhoBar_target = 0;
    const T mach_number = 0.2;
    const T velocity_flow = mach_number*lattice_speed_sound;
    Array<T,3> j_target(velocity_flow, 0, 0);
    T size_anechoic_buffer = 20;
    defineAnechoicMRTBoards(nx, ny, nz, lattice, size_anechoic_buffer,
      omega, j_target, j_target, j_target, j_target, j_target, j_target,
      rhoBar_target);

    lattice.initialize();

    pcout << std::endl << "Voxelizing the domain." << std::endl;

    pcout << "Simulation begins" << endl;

    plb_ofstream history_pressures("tmp/history_pressures.dat");
    plb_ofstream history_velocities_x("tmp/history_velocities_x.dat");
    plb_ofstream history_velocities_y("tmp/history_velocities_y.dat");
    plb_ofstream history_velocities_z("tmp/history_velocities_z.dat");
    for (plint iT=0; iT<maxT; ++iT){
        if (iT == 0){
            //T lattice_speed_sound = 1/sqrt(3);
            //T rho_changing = 1. + drho*sin(2*M_PI*(lattice_speed_sound/20)*iT);
            Box3D impulse(nx/2, nx/2, ny/2, ny/2, nz/2, nz/2);
            initializeAtEquilibrium( lattice, impulse, rho0 + drho, u0);
        }

        if (iT % 10 == 0 && iT>0) {
            pcout << "Iteration " << iT << endl;
            //writeGifs(lattice,iT);
            writeVTK(lattice, iT);
        }

        history_pressures << setprecision(10) << lattice.get(nx/2+30, ny/2+30, nz/2+30).computeDensity() - rho0 << endl;
        Array<T,3> velocities;
        lattice.get(nx/2+30, ny/2+30, nz/2+30).computeVelocity(velocities);
        history_velocities_x << setprecision(10) << velocities[0]/lattice_speed_sound << endl;
        history_velocities_y << setprecision(10) << velocities[1]/lattice_speed_sound << endl;
        history_velocities_z << setprecision(10) << velocities[2]/lattice_speed_sound << endl;
        lattice.collideAndStream();

    }

    pcout << "End of simulation at iteration " << endl;
}
<commit_msg>update duct radiation<commit_after>#include "palabos3D.h"
#include "palabos3D.hh"
#include <vector>
#include <cmath>

using namespace plb;
using namespace plb::descriptors;
using namespace std;

typedef double T;
typedef Array<T,3> Velocity;
//#define DESCRIPTOR descriptors::D3Q27Descriptor
#define DESCRIPTOR MRTD3Q19Descriptor
 typedef MRTdynamics<T,DESCRIPTOR> BackgroundDynamics;
 typedef AnechoicMRTdynamics<T,DESCRIPTOR> AnechoicBackgroundDynamics;

// ---------------------------------------------
// Includes of acoustics resources
#include "acoustics/acoustics3D.h"
using namespace plb_acoustics_3D;
// ---------------------------------------------

const T rho0 = 1;
const T drho = rho0/10;

void writeGifs(MultiBlockLattice3D<T,DESCRIPTOR>& lattice, plint iter){
    const plint nx = lattice.getNx();
    const plint ny = lattice.getNy();
    const plint nz = lattice.getNz();

    const plint imSize = 600;
    ImageWriter<T> imageWriter("leeloo");

    Box3D slice(0, nx-1, 0, ny-1, nz/2, nz/2);
    //imageWriter.writeGif(createFileName("u", iT, 6),
     //*computeDensity(lattice), );

    imageWriter.writeGif( createFileName("rho", iter, 6),
    *computeDensity(lattice, slice),
    (T) rho0 - drho/1000000, (T) rho0 + drho/1000000, imSize, imSize);
}

void writeVTK(MultiBlockLattice3D<T,DESCRIPTOR>& lattice, plint iter){
        VtkImageOutput3D<T> vtkOut(createFileName("vtk", iter, 6), 1.);
        vtkOut.writeData<float>(*computeDensity(lattice), "density", 1.);
        vtkOut.writeData<3,float>(*computeVelocity(lattice), "velocity", 1.);
}

int main(int argc, char **argv){
    plbInit(&argc, &argv);
    std::string fNameOut = "tmp";

    const plint nx = 150;
    const plint ny = 100;
    const plint nz = 100;
    const T lattice_speed_sound = 1/sqrt(3);

    const T omega = 1.985;
    const plint maxT = 120000;

    Array<T,3> u0(0, 0, 0);

    global::directories().setOutputDir(fNameOut+"/");

    //Build geometry
    // Create the cylinder surface as a set of triangles.
    T radius = 20.;
    Array<T,3> originalCenter(0, 0, 0);
    TriangleSet<T> triangleSet;
    triangleSet = constructSphere<T>(originalCenter, radius, (plint)40);

    //   tube to more efficient data structures that are internally used by palabos.
    //   The TriangleBoundary3D structure will be later used to assign proper boundary conditions.
    plint borderWidth = 1;  // Because the Guo boundary condition acts in a one-cell layer.
                        // Requirement: margin>=borderWidth.
    plint margin      = 1 + borderWidth;  // Extra margin of allocated cells around the obstacle.
    plint extraLayer  = 0;  // Make the bounding box larger; for visualization purposes
                        //   only. For the simulation, it is OK to have extraLayer=0.
    DEFscaledMesh<T> defMesh(triangleSet, 40, 1, margin, extraLayer);
    pcout << "Valor do Dx: " << defMesh.getDx() << std::endl;
    Array<T, 3> physical_position = defMesh.getPhysicalLocation();
    pcout << "posicao fisica em x: " << physical_position[0] << std::endl;
    pcout << "posicao fisica em y: " << physical_position[1] << std::endl;
    pcout << "posicao fisica em z: " << physical_position[2] << std::endl;
    Array< T, 3 > position_lattice(50, ny/2, nz/2);
    defMesh.setPhysicalLocation(position_lattice);
    Array<T, 3> physical_position_c = defMesh.getPhysicalLocation();
    pcout << "posicao fisica em x_c: " << physical_position_c[0] << std::endl;
    pcout << "posicao fisica em y_c: " << physical_position_c[1] << std::endl;
    pcout << "posicao fisica em z_c: " << physical_position_c[2] << std::endl;
    defMesh.getMesh().inflate();
    TriangleBoundary3D<T> boundary(defMesh);

    boundary.getMesh().writeBinarySTL("cylinder.stl");
    pcout << "Number of triangles: " << boundary.getMesh().getNumTriangles() << std::endl;
    //   handled by the following voxelization process.
    pcout << std::endl << "Voxelizing the domain." << std::endl;
    const int flowType = voxelFlag::outside;
    const plint extendedEnvelopeWidth = 2;
    const plint blockSize = 20; // Zero means: no sparse representation.
     // Because the Guo boundary condition needs 2-cell neighbor access.
    VoxelizedDomain3D<T> voxelizedDomain (
            boundary, flowType, extraLayer, borderWidth, extendedEnvelopeWidth, blockSize);
    pcout << getMultiBlockInfo(voxelizedDomain.getVoxelMatrix()) << std::endl;
    //-------------------------------------

    //Set geometry in lattice
     // The Guo off *lattice boundary condition is set up.
    pcout << "Creating boundary condition." << std::endl;
    BoundaryProfiles3D<T,Velocity> profiles;

    bool useAllDirections = true; // Extrapolation scheme for the off *lattice boundary condition.
    GuoOffLatticeModel3D<T,DESCRIPTOR>* model =
            new GuoOffLatticeModel3D<T,DESCRIPTOR> (
                new TriangleFlowShape3D<T,Array<T,3> > (
                    voxelizedDomain.getBoundary(), profiles),
                flowType, useAllDirections );
    bool useRegularized = true;
    // Use an off *lattice boundary condition which is closer in spirit to
    //   regularized boundary conditions.
    model->selectUseRegularizedModel(useRegularized);
    // Setting anechoic dynamics like this way
    MultiBlockLattice3D<T, DESCRIPTOR> lattice(nx, ny, nz,  new AnechoicBackgroundDynamics(omega));
    defineDynamics(lattice, lattice.getBoundingBox(), new BackgroundDynamics(omega));

    OffLatticeBoundaryCondition3D<T,DESCRIPTOR,Velocity> boundaryCondition (
            model, voxelizedDomain, lattice);
    boundaryCondition.insert();
    defineDynamics(lattice, voxelizedDomain.getVoxelMatrix(),
     lattice.getBoundingBox(), new NoDynamics<T,DESCRIPTOR>(), voxelFlag::inside);

    pcout << "Creation of the lattice." << endl;

    // Switch off periodicity.
    lattice.periodicity().toggleAll(false);

    pcout << "Initilization of rho and u." << endl;
    initializeAtEquilibrium( lattice, lattice.getBoundingBox(), rho0 , u0 );

    T rhoBar_target = 0;
    const T mach_number = 0.2;
    const T velocity_flow = mach_number*lattice_speed_sound;
    Array<T,3> j_target(velocity_flow, 0, 0);
    T size_anechoic_buffer = 20;
    /*defineAnechoicMRTBoards(nx, ny, nz, lattice, size_anechoic_buffer,
      omega, j_target, j_target, j_target, j_target, j_target, j_target,
      rhoBar_target);*/

    lattice.initialize();

    pcout << std::endl << "Voxelizing the domain." << std::endl;

    pcout << "Simulation begins" << endl;

    plb_ofstream history_pressures("tmp/history_pressures.dat");
    plb_ofstream history_velocities_x("tmp/history_velocities_x.dat");
    plb_ofstream history_velocities_y("tmp/history_velocities_y.dat");
    plb_ofstream history_velocities_z("tmp/history_velocities_z.dat");
    for (plint iT=0; iT<maxT; ++iT){
        if (iT == 0){
            //T lattice_speed_sound = 1/sqrt(3);
            //T rho_changing = 1. + drho*sin(2*M_PI*(lattice_speed_sound/20)*iT);
            Box3D impulse(nx/2, nx/2, ny/2, ny/2, nz/2, nz/2);
            initializeAtEquilibrium( lattice, impulse, rho0 + drho, u0);
        }

        if (iT % 10 == 0 && iT>0) {
            pcout << "Iteration " << iT << endl;
            //writeGifs(lattice,iT);
            writeVTK(lattice, iT);
        }

        history_pressures << setprecision(10) << lattice.get(nx/2+30, ny/2+30, nz/2+30).computeDensity() - rho0 << endl;
        Array<T,3> velocities;
        lattice.get(nx/2+30, ny/2+30, nz/2+30).computeVelocity(velocities);
        history_velocities_x << setprecision(10) << velocities[0]/lattice_speed_sound << endl;
        history_velocities_y << setprecision(10) << velocities[1]/lattice_speed_sound << endl;
        history_velocities_z << setprecision(10) << velocities[2]/lattice_speed_sound << endl;
        lattice.collideAndStream();

    }

    pcout << "End of simulation at iteration " << endl;
}
<|endoftext|>


<commit_before>#include "palabos3D.h"
#include "palabos3D.hh"
#include <vector>
#include <cmath>

using namespace plb;
using namespace plb::descriptors;
using namespace std;

typedef double T;
typedef Array<T,3> Velocity;
//#define DESCRIPTOR descriptors::D3Q27Descriptor
#define DESCRIPTOR MRTD3Q19Descriptor
 typedef MRTdynamics<T,DESCRIPTOR> BackgroundDynamics;
 typedef AnechoicMRTdynamics<T,DESCRIPTOR> AnechoicBackgroundDynamics;

// ---------------------------------------------
// Includes of acoustics resources
#include "acoustics/acoustics3D.h"
using namespace plb_acoustics_3D;
// ---------------------------------------------

const T rho0 = 1;
const T drho = rho0/10;

void writeGifs(MultiBlockLattice3D<T,DESCRIPTOR>& lattice, plint iter){
    const plint nx = lattice.getNx();
    const plint ny = lattice.getNy();
    const plint nz = lattice.getNz();

    const plint imSize = 600;
    ImageWriter<T> imageWriter("leeloo");

    Box3D slice(0, nx-1, 0, ny-1, nz/2, nz/2);
    //imageWriter.writeGif(createFileName("u", iT, 6),
     //*computeDensity(lattice), );

    imageWriter.writeGif( createFileName("rho", iter, 6),
    *computeDensity(lattice, slice),
    (T) rho0 - drho/1000000, (T) rho0 + drho/1000000, imSize, imSize);
}

void writeVTK(MultiBlockLattice3D<T,DESCRIPTOR>& lattice, plint iter){
        VtkImageOutput3D<T> vtkOut(createFileName("vtk", iter, 6), 1.);
        vtkOut.writeData<float>(*computeDensity(lattice), "density", 1.);
        vtkOut.writeData<3,float>(*computeVelocity(lattice), "velocity", 1.);
}

int main(int argc, char **argv){
    plbInit(&argc, &argv);
    std::string fNameOut = "tmp";

    const plint nx = 350;
    const plint ny = 160;
    const plint nz = 160;
    const T lattice_speed_sound = 1/sqrt(3);
    const T cs2 = lattice_speed_sound*lattice_speed_sound;

    const T omega = 1.985;
    const plint maxT = 10000;
    const plint maxT_final_source = maxT - 1000;
    const T ka_max = 1.82;
    const T ka_min = 0;

    Array<T,3> u0(0, 0, 0);

    global::directories().setOutputDir(fNameOut+"/");

    //Build geometry
    Array<T,3> centerLB(30, ny/2, nz/2);
    //TriangleSet<T> triangleSet("Duto_Fechado.STL");
    //Array<T,3> center(param.cx, param.cy, param.cz);
    TriangleSet<T> triangleSet;
    pcout << "construindo o duto" << std::endl;
    /*
    (Array<T,3> const& inletCenter, T externRadius, T internRadius,
                                 T length, plint nAxial, plint nCirc)
                                 */
    T thickness_duct = 4;
    T radius = 20;
    triangleSet = constructDuct(centerLB, radius + thickness_duct, radius
    , (T) 250, (plint) 10, (plint) 50);

    //triangleSet = constructSphere<T>(centerLB, (T) 10, (plint)40);
    /*TriangleSet<T> triangleSet("duto_fechado.STL");
    triangleSet.translate(centerLB);*/
    // rotate: Z, X, Y in radians
    //triangleSet.rotate((T) 0, (T) 0, (T) 0);
    //triangleSet.scale((T) 3.95253e+2);

    //   tube to more efficient data structures that are internally used by palabos.
    //   The TriangleBoundary3D structure will be later used to assign proper boundary conditions.
    plint borderWidth = 1;  // Because the Guo boundary condition acts in a one-cell layer.
                        // Requirement: margin>=borderWidth.
    plint margin      = 1;  // Extra margin of allocated cells around the obstacle.
    plint extraLayer  = 0;  // Make the bounding box larger; for visualization purposes
                        //   only. For the simulation, it is OK to have extraLayer=0.
    plint xDirection = 0;
    DEFscaledMesh<T> defMesh(triangleSet, 0, xDirection, margin, Dot3D(0, 0, 0));
    defMesh.setDx((T) 1.);

    pcout << "Valor do Dx: " << defMesh.getDx() << std::endl;
    Array<T, 3> physical_position = defMesh.getPhysicalLocation();
    pcout << "posicao fisica em x: " << physical_position[0] << std::endl;
    pcout << "posicao fisica em y: " << physical_position[1] << std::endl;
    pcout << "posicao fisica em z: " << physical_position[2] << std::endl;
    //Array< T, 3 > position_lattice(50, ny/2, nz/2);
    //defMesh.setPhysicalLocation(position_lattice);
    Array<T, 3> physical_position_c = defMesh.getPhysicalLocation();
    pcout << "posicao fisica em x_c: " << physical_position_c[0] << std::endl;
    pcout << "posicao fisica em y_c: " << physical_position_c[1] << std::endl;
    pcout << "posicao fisica em z_c: " << physical_position_c[2] << std::endl;
    defMesh.getMesh().inflate();
    TriangleBoundary3D<T> boundary(defMesh);

    boundary.getMesh().writeBinarySTL("duct.stl");
    pcout << "Number of triangles: " << boundary.getMesh().getNumTriangles() << std::endl;
    //   handled by the following voxelization process.
    pcout << std::endl << "Voxelizing the domain." << std::endl;
    const int flowType = voxelFlag::outside;
    const plint extendedEnvelopeWidth = 2;
    const plint blockSize = 0; // Zero means: no sparse representation.
     // Because the Guo boundary condition needs 2-cell neighbor access.
    Box3D full_domain(0, nx-1, 0, ny-1, 0, nz-1);
    VoxelizedDomain3D<T> voxelizedDomain (
            boundary, flowType, full_domain, borderWidth, extendedEnvelopeWidth, blockSize);
    pcout << getMultiBlockInfo(voxelizedDomain.getVoxelMatrix()) << std::endl;

    // Build lattice and set default dynamics
    //-------------------------------------
    MultiBlockLattice3D<T,DESCRIPTOR> *lattice =
    new MultiBlockLattice3D<T,DESCRIPTOR>(voxelizedDomain.getVoxelMatrix());

    // Setting anechoic dynamics like this way
    defineDynamics(*lattice, lattice->getBoundingBox(),
                new AnechoicBackgroundDynamics(omega));
    defineDynamics(*lattice, lattice->getBoundingBox(),
                new BackgroundDynamics(omega));
    //-------------------------------------

    //Set geometry in lattice
     // The Guo off *lattice boundary condition is set up.
    pcout << "Creating boundary condition." << std::endl;
    BoundaryProfiles3D<T,Velocity> profiles;
    //profiles.setWallProfile(new NoSlipProfile3D<T>);

    bool useAllDirections = true; // Extrapolation scheme for the off *lattice boundary condition.
    GuoOffLatticeModel3D<T,DESCRIPTOR>* model =
            new GuoOffLatticeModel3D<T,DESCRIPTOR> (
                new TriangleFlowShape3D<T,Array<T,3> > (
                    voxelizedDomain.getBoundary(), profiles),
                flowType, useAllDirections );
    bool useRegularized = true;
    // Use an off *lattice boundary condition which is closer in spirit to
    //   regularized boundary conditions.
    model->selectUseRegularizedModel(useRegularized);
    // ---
    OffLatticeBoundaryCondition3D<T,DESCRIPTOR,Velocity> boundaryCondition (
            model, voxelizedDomain, *lattice);
    boundaryCondition.insert();
    defineDynamics(*lattice, voxelizedDomain.getVoxelMatrix(),
     lattice->getBoundingBox(), new NoDynamics<T,DESCRIPTOR>(-999), voxelFlag::inside);

    pcout << "Creation of the lattice." << endl;

    // Switch off periodicity.
    lattice->periodicity().toggleAll(false);

    pcout << "Initilization of rho and u." << endl;
    initializeAtEquilibrium( *lattice, lattice->getBoundingBox(), rho0 , u0 );

    // Set anechoic condition on boundaries
    T rhoBar_target = 0;
    const T mach_number = 0.2;
    const T velocity_flow = mach_number*lattice_speed_sound;
    Array<T,3> j_target(0, 0, 0);
    T size_anechoic_buffer = 30;
    defineAnechoicMRTBoards(nx, ny, nz, *lattice, size_anechoic_buffer,
      omega, j_target, j_target, j_target, j_target, j_target, j_target,
      rhoBar_target);

    lattice->initialize();

    pcout << std::endl << "Voxelizing the domain." << std::endl;

    pcout << "Simulation begins" << endl;

    plb_ofstream history_pressures("tmp/history_pressures.dat");
    plb_ofstream history_velocities_x("tmp/history_velocities_x.dat");
    plb_ofstream history_velocities_y("tmp/history_velocities_y.dat");
    plb_ofstream history_velocities_z("tmp/history_velocities_z.dat");
    for (plint iT=0; iT<maxT; ++iT){

          if (iT <= maxT_final_source){
            //drho*sin(2*M_PI*(lattice_speed_sound/20)*iT);
            //drho*cos((lattice_speed_sound/radius)*(ka_max*((maxT-iT)/maxT)));

            T initial_frequency = ka_min*lattice_speed_sound/(2*M_PI*radius);
            T frequency_max_lattice = ka_max*lattice_speed_sound/(2*M_PI*radius);
            T variation_frequency = (frequency_max_lattice - initial_frequency)/maxT_final_source;
            T frequency_function = initial_frequency*iT + (variation_frequency*iT*iT)/2;
            T phase = 2*M_PI*frequency_function;
            T chirp_hand = 1. + drho*sin(phase);

            T rho_changing = 1. + drho*sin(2*M_PI*(lattice_speed_sound/20)*iT);
            //Box3D impulse(nx/2 + 50, nx/2 + 50, ny/2 + 50, ny/2 + 50, nz/2 + 50, nz/2 + 50);
            plint source_radius = radius;
             Box3D test_source(centerLB[0] + 10, centerLB[0] + 15,
                ny/2 - source_radius/sqrt(2),
                ny/2 + source_radius/sqrt(2),
                nz/2 - source_radius/sqrt(2),
                nz/2 + source_radius/sqrt(2));
            //Box3D impulse(centerLB[0] + 10, centerLB[0] + 10, ny/2, ny/2, nz/2, nz/2);
            initializeAtEquilibrium( *lattice, test_source, chirp_hand, u0);
        }else{
            plint source_radius = radius;
             Box3D test_source(centerLB[0] + 10, centerLB[0] + 15,
                ny/2 - source_radius/sqrt(2),
                ny/2 + source_radius/sqrt(2),
                nz/2 - source_radius/sqrt(2),
                nz/2 + source_radius/sqrt(2));
            initializeAtEquilibrium( *lattice, test_source, rho0, u0);
        }

        if (iT % 10 == 0 && iT>0) {
            pcout << "Iteration " << iT << endl;
            //writeGifs(lattice,iT);
            //writeVTK(*lattice, iT);
        }

        // extract values of pressure and velocities
        Box3D surface_probe(6*radius, 6*radius, ny/2 - radius/sqrt(2),
                ny/2 + radius/sqrt(2),
                nz/2 - radius/sqrt(2),
                nz/2 + radius/sqrt(2));

        history_pressures << setprecision(10) << (computeAverageDensity(*lattice, surface_probe) - rho0)*cs2 << endl;

        history_velocities_x << setprecision(10) <<
        boundaryCondition.computeAverageVelocityComponent(surface_probe, 0)/lattice_speed_sound << endl;

        history_velocities_y << setprecision(10) <<
        boundaryCondition.computeAverageVelocityComponent(surface_probe, 1)/lattice_speed_sound << endl;

        history_velocities_z << setprecision(10) <<
        boundaryCondition.computeAverageVelocityComponent(surface_probe, 2)/lattice_speed_sound << endl;

        lattice->collideAndStream();

    }

    pcout << "End of simulation at iteration " << endl;
}
<commit_msg>Duct size done<commit_after>#include "palabos3D.h"
#include "palabos3D.hh"
#include <vector>
#include <cmath>

using namespace plb;
using namespace plb::descriptors;
using namespace std;

typedef double T;
typedef Array<T,3> Velocity;
//#define DESCRIPTOR descriptors::D3Q27Descriptor
#define DESCRIPTOR MRTD3Q19Descriptor
 typedef MRTdynamics<T,DESCRIPTOR> BackgroundDynamics;
 typedef AnechoicMRTdynamics<T,DESCRIPTOR> AnechoicBackgroundDynamics;

// ---------------------------------------------
// Includes of acoustics resources
#include "acoustics/acoustics3D.h"
using namespace plb_acoustics_3D;
// ---------------------------------------------

const T rho0 = 1;
const T drho = rho0/10;

void writeGifs(MultiBlockLattice3D<T,DESCRIPTOR>& lattice, plint iter){
    const plint nx = lattice.getNx();
    const plint ny = lattice.getNy();
    const plint nz = lattice.getNz();

    const plint imSize = 600;
    ImageWriter<T> imageWriter("leeloo");

    Box3D slice(0, nx-1, 0, ny-1, nz/2, nz/2);
    //imageWriter.writeGif(createFileName("u", iT, 6),
     //*computeDensity(lattice), );

    imageWriter.writeGif( createFileName("rho", iter, 6),
    *computeDensity(lattice, slice),
    (T) rho0 - drho/1000000, (T) rho0 + drho/1000000, imSize, imSize);
}

void writeVTK(MultiBlockLattice3D<T,DESCRIPTOR>& lattice, plint iter){
        VtkImageOutput3D<T> vtkOut(createFileName("vtk", iter, 6), 1.);
        vtkOut.writeData<float>(*computeDensity(lattice), "density", 1.);
        vtkOut.writeData<3,float>(*computeVelocity(lattice), "velocity", 1.);
}

int main(int argc, char **argv){
    plbInit(&argc, &argv);
    std::string fNameOut = "tmp";

    const T radius = 11;
    const T diameter = 2*radius;

    const plint nx = 23*diameter;
    const plint ny = 20*diameter;
    const plint nz = 20*diameter;
    const T lattice_speed_sound = 1/sqrt(3);
    const T cs2 = lattice_speed_sound*lattice_speed_sound;

    const T omega = 1.985;
    const plint maxT = 10000;
    const plint maxT_final_source = maxT - 1000;
    const T ka_max = 1.82;
    const T ka_min = 0;

    Array<T,3> u0(0, 0, 0);

    global::directories().setOutputDir(fNameOut+"/");

    //Build geometry
    Array<T,3> centerLB(30, ny/2, nz/2);
    //TriangleSet<T> triangleSet("Duto_Fechado.STL");
    //Array<T,3> center(param.cx, param.cy, param.cz);
    TriangleSet<T> triangleSet;
    pcout << "construindo o duto" << std::endl;
    /*
    (Array<T,3> const& inletCenter, T externRadius, T internRadius,
                                 T length, plint nAxial, plint nCirc)
                                 */
    T thickness_duct = 4;
    T size_duct = 11*diameter;
    triangleSet = constructDuct(centerLB, radius + thickness_duct, radius
    , (T) size_duct, (plint) 10, (plint) 50);

    //triangleSet = constructSphere<T>(centerLB, (T) 10, (plint)40);
    /*TriangleSet<T> triangleSet("duto_fechado.STL");
    triangleSet.translate(centerLB);*/
    // rotate: Z, X, Y in radians
    //triangleSet.rotate((T) 0, (T) 0, (T) 0);
    //triangleSet.scale((T) 3.95253e+2);

    //   tube to more efficient data structures that are internally used by palabos.
    //   The TriangleBoundary3D structure will be later used to assign proper boundary conditions.
    plint borderWidth = 1;  // Because the Guo boundary condition acts in a one-cell layer.
                        // Requirement: margin>=borderWidth.
    plint margin      = 1;  // Extra margin of allocated cells around the obstacle.
    plint extraLayer  = 0;  // Make the bounding box larger; for visualization purposes
                        //   only. For the simulation, it is OK to have extraLayer=0.
    plint xDirection = 0;
    DEFscaledMesh<T> defMesh(triangleSet, 0, xDirection, margin, Dot3D(0, 0, 0));
    defMesh.setDx((T) 1.);

    pcout << "Valor do Dx: " << defMesh.getDx() << std::endl;
    Array<T, 3> physical_position = defMesh.getPhysicalLocation();
    pcout << "posicao fisica em x: " << physical_position[0] << std::endl;
    pcout << "posicao fisica em y: " << physical_position[1] << std::endl;
    pcout << "posicao fisica em z: " << physical_position[2] << std::endl;
    //Array< T, 3 > position_lattice(50, ny/2, nz/2);
    //defMesh.setPhysicalLocation(position_lattice);
    Array<T, 3> physical_position_c = defMesh.getPhysicalLocation();
    pcout << "posicao fisica em x_c: " << physical_position_c[0] << std::endl;
    pcout << "posicao fisica em y_c: " << physical_position_c[1] << std::endl;
    pcout << "posicao fisica em z_c: " << physical_position_c[2] << std::endl;
    defMesh.getMesh().inflate();
    TriangleBoundary3D<T> boundary(defMesh);

    boundary.getMesh().writeBinarySTL("duct.stl");
    pcout << "Number of triangles: " << boundary.getMesh().getNumTriangles() << std::endl;
    //   handled by the following voxelization process.
    pcout << std::endl << "Voxelizing the domain." << std::endl;
    const int flowType = voxelFlag::outside;
    const plint extendedEnvelopeWidth = 2;
    const plint blockSize = 0; // Zero means: no sparse representation.
     // Because the Guo boundary condition needs 2-cell neighbor access.
    Box3D full_domain(0, nx-1, 0, ny-1, 0, nz-1);
    VoxelizedDomain3D<T> voxelizedDomain (
            boundary, flowType, full_domain, borderWidth, extendedEnvelopeWidth, blockSize);
    pcout << getMultiBlockInfo(voxelizedDomain.getVoxelMatrix()) << std::endl;

    // Build lattice and set default dynamics
    //-------------------------------------
    MultiBlockLattice3D<T,DESCRIPTOR> *lattice =
    new MultiBlockLattice3D<T,DESCRIPTOR>(voxelizedDomain.getVoxelMatrix());

    // Setting anechoic dynamics like this way
    defineDynamics(*lattice, lattice->getBoundingBox(),
                new AnechoicBackgroundDynamics(omega));
    defineDynamics(*lattice, lattice->getBoundingBox(),
                new BackgroundDynamics(omega));
    //-------------------------------------

    //Set geometry in lattice
     // The Guo off *lattice boundary condition is set up.
    pcout << "Creating boundary condition." << std::endl;
    BoundaryProfiles3D<T,Velocity> profiles;
    //profiles.setWallProfile(new NoSlipProfile3D<T>);

    bool useAllDirections = true; // Extrapolation scheme for the off *lattice boundary condition.
    GuoOffLatticeModel3D<T,DESCRIPTOR>* model =
            new GuoOffLatticeModel3D<T,DESCRIPTOR> (
                new TriangleFlowShape3D<T,Array<T,3> > (
                    voxelizedDomain.getBoundary(), profiles),
                flowType, useAllDirections );
    bool useRegularized = true;
    // Use an off *lattice boundary condition which is closer in spirit to
    //   regularized boundary conditions.
    model->selectUseRegularizedModel(useRegularized);
    // ---
    OffLatticeBoundaryCondition3D<T,DESCRIPTOR,Velocity> boundaryCondition (
            model, voxelizedDomain, *lattice);
    boundaryCondition.insert();
    defineDynamics(*lattice, voxelizedDomain.getVoxelMatrix(),
     lattice->getBoundingBox(), new NoDynamics<T,DESCRIPTOR>(-999), voxelFlag::inside);

    pcout << "Creation of the lattice." << endl;

    // Switch off periodicity.
    lattice->periodicity().toggleAll(false);

    pcout << "Initilization of rho and u." << endl;
    initializeAtEquilibrium( *lattice, lattice->getBoundingBox(), rho0 , u0 );

    // Set anechoic condition on boundaries
    T rhoBar_target = 0;
    const T mach_number = 0.2;
    const T velocity_flow = mach_number*lattice_speed_sound;
    Array<T,3> j_target(0, 0, 0);
    T size_anechoic_buffer = 30;
    defineAnechoicMRTBoards(nx, ny, nz, *lattice, size_anechoic_buffer,
      omega, j_target, j_target, j_target, j_target, j_target, j_target,
      rhoBar_target);

    lattice->initialize();

    pcout << std::endl << "Voxelizing the domain." << std::endl;

    pcout << "Simulation begins" << endl;

    // Setting probes
    plint position_x_3r = centerLB[0] + size_duct - 3*radius;
    Box3D surface_probe_3r(position_x_3r, position_x_3r, ny/2 - radius/sqrt(2),
            ny/2 + radius/sqrt(2),
            nz/2 - radius/sqrt(2),
            nz/2 + radius/sqrt(2));

    plint position_x_4r = centerLB[0] + size_duct - 4*radius;
    Box3D surface_probe_4r(position_x_4r, position_x_4r, ny/2 - radius/sqrt(2),
            ny/2 + radius/sqrt(2),
            nz/2 - radius/sqrt(2),
            nz/2 + radius/sqrt(2));

    plint position_x_6r = centerLB[0] + size_duct - 6*radius;
    Box3D surface_probe_6r(position_x_6r, position_x_6r, ny/2 - radius/sqrt(2),
            ny/2 + radius/sqrt(2),
            nz/2 - radius/sqrt(2),
            nz/2 + radius/sqrt(2));
    plb_ofstream history_pressures_3r("tmp/history_pressures_3r.dat");
    plb_ofstream history_pressures_4r("tmp/history_pressures_4r.dat");
    plb_ofstream history_pressures_6r("tmp/history_pressures_6r.dat");
    plb_ofstream history_velocities_3r("tmp/history_velocities_3r.dat");
    plb_ofstream history_velocities_4r("tmp/history_velocities_4r.dat");
    plb_ofstream history_velocities_6r("tmp/history_velocities_6r.dat");
    for (plint iT=0; iT<maxT; ++iT){

          if (iT <= maxT_final_source){
            //drho*sin(2*M_PI*(lattice_speed_sound/20)*iT);
            //drho*cos((lattice_speed_sound/radius)*(ka_max*((maxT-iT)/maxT)));

            T initial_frequency = ka_min*lattice_speed_sound/(2*M_PI*radius);
            T frequency_max_lattice = ka_max*lattice_speed_sound/(2*M_PI*radius);
            T variation_frequency = (frequency_max_lattice - initial_frequency)/maxT_final_source;
            T frequency_function = initial_frequency*iT + (variation_frequency*iT*iT)/2;
            T phase = 2*M_PI*frequency_function;
            T chirp_hand = 1. + drho*sin(phase);

            T rho_changing = 1. + drho*sin(2*M_PI*(lattice_speed_sound/20)*iT);
            //Box3D impulse(nx/2 + 50, nx/2 + 50, ny/2 + 50, ny/2 + 50, nz/2 + 50, nz/2 + 50);
            plint source_radius = radius;
             Box3D test_source(centerLB[0] + 10, centerLB[0] + 15,
                ny/2 - source_radius/sqrt(2),
                ny/2 + source_radius/sqrt(2),
                nz/2 - source_radius/sqrt(2),
                nz/2 + source_radius/sqrt(2));
            //Box3D impulse(centerLB[0] + 10, centerLB[0] + 10, ny/2, ny/2, nz/2, nz/2);
            initializeAtEquilibrium( *lattice, test_source, chirp_hand, u0);
        }else{
            plint source_radius = radius;
             Box3D test_source(centerLB[0] + 10, centerLB[0] + 15,
                ny/2 - source_radius/sqrt(2),
                ny/2 + source_radius/sqrt(2),
                nz/2 - source_radius/sqrt(2),
                nz/2 + source_radius/sqrt(2));
            initializeAtEquilibrium( *lattice, test_source, rho0, u0);
        }

        if (iT % 10 == 0 && iT>0) {
            pcout << "Iteration " << iT << endl;
            //writeGifs(lattice,iT);
            writeVTK(*lattice, iT);
        }

        // extract values of pressure and velocities
        history_pressures_3r << setprecision(10) << (computeAverageDensity(*lattice, surface_probe_3r) - rho0)*cs2 << endl;
        history_pressures_4r << setprecision(10) << (computeAverageDensity(*lattice, surface_probe_4r) - rho0)*cs2 << endl;
        history_pressures_6r << setprecision(10) << (computeAverageDensity(*lattice, surface_probe_6r) - rho0)*cs2 << endl;

        history_velocities_3r << setprecision(10) <<
        boundaryCondition.computeAverageVelocityComponent(surface_probe_3r, 0)/lattice_speed_sound << endl;

        history_velocities_4r << setprecision(10) <<
        boundaryCondition.computeAverageVelocityComponent(surface_probe_4r, 1)/lattice_speed_sound << endl;

        history_velocities_6r << setprecision(10) <<
        boundaryCondition.computeAverageVelocityComponent(surface_probe_6r, 2)/lattice_speed_sound << endl;

        lattice->collideAndStream();

    }

    pcout << "End of simulation at iteration " << endl;
}
<|endoftext|>


<commit_before>/*
* mod_dup - duplicates apache requests
*
* Copyright (C) 2013 Orange
*
* 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 "mod_dup.hh"
#include "Utils.hh"

#include <boost/shared_ptr.hpp>
#include <http_config.h>

namespace DupModule {

/*
 * Callback to iterate over the headers tables
 * Pushes a copy of key => value in a list passed without typing as the first argument
 */
static int iterateOverHeadersCallBack(void *d, const char *key, const char *value) {
    RequestInfo::tHeaders *headers = reinterpret_cast<RequestInfo::tHeaders *>(d);
    headers->push_back(std::pair<std::string, std::string>(key, value));
    return 1;
}

static void
prepareRequestInfo(DupConf *tConf, request_rec *pRequest, RequestInfo &r) {
    // Copy headers in
    apr_table_do(&iterateOverHeadersCallBack, &r.mHeadersIn, pRequest->headers_in, NULL);

    // Add the elapsed time header
    r.mHeadersOut.push_back(std::make_pair(std::string("ELAPSED_TIME_BY_DUP"), boost::lexical_cast<std::string>(r.getElapsedTimeMS())));

    // Basic
    r.mPoison = false;
    r.mConfPath = tConf->dirName;
    r.mPath = pRequest->uri;
    r.mArgs = pRequest->args ? pRequest->args : "";
}

static void
printRequest(request_rec *pRequest, RequestInfo *pBH, DupConf *tConf) {
    const char *reqId = apr_table_get(pRequest->headers_in, CommonModule::c_UNIQUE_ID);
    Log::debug("### Pushing a request with ID: %s, body size:%ld", reqId, pBH->mBody.size());
    Log::debug("### Uri:%s, dir name:%s", pRequest->uri, tConf->dirName);
    Log::debug("### Request args: %s", pRequest->args);
}

apr_status_t
inputFilterHandler(ap_filter_t *pFilter, apr_bucket_brigade *pB, ap_input_mode_t pMode, apr_read_type_e pBlock, apr_off_t pReadbytes) {
    request_rec *pRequest = pFilter->r;
    if (!pRequest || !pRequest->per_dir_config) {
        return ap_get_brigade(pFilter->next, pB, pMode, pBlock, pReadbytes);
    }
    struct DupConf *conf = reinterpret_cast<DupConf *>(ap_get_module_config(pRequest->per_dir_config, &dup_module));
    if (!conf || !conf->dirName) {
        // Not a location that we treat, we decline the request
        return ap_get_brigade(pFilter->next, pB, pMode, pBlock, pReadbytes);
    }

    RequestInfo *info;
    if (!pFilter->ctx) {

        // Unique request id
        std::string uid = CommonModule::getOrSetUniqueID(pRequest);
        info = new RequestInfo(uid);

        // Allocation on a shared pointer on the request pool
        // We guarantee that whatever happens, the RequestInfo will be deleted
        void *space = apr_palloc(pRequest->pool, sizeof(boost::shared_ptr<RequestInfo>));
        new (space) boost::shared_ptr<RequestInfo>(info);
        // Registering of the shared pointer destructor on the pool
        apr_pool_cleanup_register(pRequest->pool, space, cleaner<boost::shared_ptr<RequestInfo> >,
                                  apr_pool_cleanup_null);
        // Backup in request context
        ap_set_module_config(pRequest->request_config, &dup_module, (void *)space);
        // Backup in filter context
        pFilter->ctx = info;

        info->mConfPath = conf->dirName;
        info->mArgs = pRequest->args ? pRequest->args : "";
    }
    if (pFilter->ctx != (void *) -1) {
        // Request not read yet
        info = reinterpret_cast<RequestInfo *>(pFilter->ctx);
        apr_status_t st = ap_get_brigade(pFilter->next, pB, pMode, pBlock, pReadbytes);
        if (st != APR_SUCCESS) {
            pFilter->ctx = (void *) -1;
            return st;
        }
        // Concats the brigade content to the reqinfo
        for (apr_bucket *b = APR_BRIGADE_FIRST(pB);
             b != APR_BRIGADE_SENTINEL(pB);
             b = APR_BUCKET_NEXT(b) ) {
            // Metadata end of stream
            if (APR_BUCKET_IS_EOS(b)) {
                return APR_SUCCESS;
            }
            if (APR_BUCKET_IS_METADATA(b))
                continue;
            const char *data = 0;
            apr_size_t len = 0;
            apr_status_t rv = apr_bucket_read(b, &data, &len, APR_BLOCK_READ);
            if (rv != APR_SUCCESS) {
                Log::error(42, "Bucket read failed, skipping the rest of the body");
                return rv;
            }
            if (len) {
                info->mBody.append(data, len);
            }
        }
    }
    // Data is read
    return APR_SUCCESS;
}

/**
 * Output Body filter handler
 * Writes the response body to the RequestInfo
 * Unless not needed because we only duplicate request and no reponses
 */
apr_status_t
outputBodyFilterHandler(ap_filter_t *pFilter, apr_bucket_brigade *pBrigade) {

    request_rec *pRequest = pFilter->r;
    apr_status_t rv;
    // Reject requests that do not meet our requirements
    if ((pFilter->ctx == (void *) -1) || !pRequest || !pRequest->per_dir_config) {
        rv = ap_pass_brigade(pFilter->next, pBrigade);
        apr_brigade_cleanup(pBrigade);
        return rv;
    }
    struct DupConf *tConf = reinterpret_cast<DupConf *>(ap_get_module_config(pRequest->per_dir_config, &dup_module));
    if ((!tConf) || (!tConf->dirName) || (tConf->getHighestDuplicationType() == DuplicationType::NONE)) {
        rv = ap_pass_brigade(pFilter->next, pBrigade);
        apr_brigade_cleanup(pBrigade);
        return rv;
    }

    boost::shared_ptr<RequestInfo> * reqInfo(reinterpret_cast<boost::shared_ptr<RequestInfo> *>(ap_get_module_config(pFilter->r->request_config, &dup_module)));
    if (!reqInfo || !reqInfo->get()) {
        pFilter->ctx = (void *) -1;
        rv = ap_pass_brigade(pFilter->next, pBrigade);
        apr_brigade_cleanup(pBrigade);
        return rv;
    }
    RequestInfo * ri = reqInfo->get();

    // Write the response body to the RequestInfo if found
    apr_bucket *currentBucket;
    for ( currentBucket = APR_BRIGADE_FIRST(pBrigade);
          currentBucket != APR_BRIGADE_SENTINEL(pBrigade);
          currentBucket = APR_BUCKET_NEXT(currentBucket) ) {

        if (APR_BUCKET_IS_EOS(currentBucket)) {
            ri->eos_seen(true);
            pFilter->ctx = (void *) -1;
            rv = ap_pass_brigade(pFilter->next, pBrigade);
            apr_brigade_cleanup(pBrigade);
            return rv;
        }

        if (APR_BUCKET_IS_METADATA(currentBucket))
            continue;

        // We need to get the highest one as we haven't matched which rule it is yet
        if (tConf->getHighestDuplicationType() == DuplicationType::REQUEST_WITH_ANSWER) {

            const char *data;
            apr_size_t len;
            rv = apr_bucket_read(currentBucket, &data, &len, APR_BLOCK_READ);

            if ((rv == APR_SUCCESS) && data) {
                // Appends the part read to the answer
                ri->mAnswer.append(data, len);
            }
        }
    }
    rv = ap_pass_brigade(pFilter->next, pBrigade);
    apr_brigade_cleanup(pBrigade);
    return rv;
}

/**
 * Output filter handler
 * Retrieves in/out headers
 * Pushes the RequestInfo object to the RequestProcessor
 */
apr_status_t
outputHeadersFilterHandler(ap_filter_t *pFilter, apr_bucket_brigade *pBrigade) {

    apr_status_t rv;
    if ( pFilter->ctx == (void *) -1 ) {
        rv = ap_pass_brigade(pFilter->next, pBrigade);
        apr_brigade_cleanup(pBrigade);
        return rv;
    }

    request_rec *pRequest = pFilter->r;
    // Reject requests that do not meet our requirements
    if (!pRequest || !pRequest->per_dir_config) {
        pFilter->ctx = (void *) -1;
        rv = ap_pass_brigade(pFilter->next, pBrigade);
        apr_brigade_cleanup(pBrigade);
        return rv;
    }

    struct DupConf *tConf = reinterpret_cast<DupConf *>(ap_get_module_config(pRequest->per_dir_config, &dup_module));
    if ((!tConf) || (!tConf->dirName) || (tConf->getHighestDuplicationType() == DuplicationType::NONE)) {
        pFilter->ctx = (void *) -1;
        rv = ap_pass_brigade(pFilter->next, pBrigade);
        apr_brigade_cleanup(pBrigade);
        return rv;
    }

    boost::shared_ptr<RequestInfo> * reqInfo(reinterpret_cast<boost::shared_ptr<RequestInfo> *>(ap_get_module_config(pFilter->r->request_config, &dup_module)));

    if (!reqInfo || !reqInfo->get()) {
        pFilter->ctx = (void *) -1;
        rv = ap_pass_brigade(pFilter->next, pBrigade);
        apr_brigade_cleanup(pBrigade);
        return rv;
    }
    RequestInfo *ri = reqInfo->get();

    // Copy headers out
    apr_table_do(&iterateOverHeadersCallBack, &ri->mHeadersOut, pRequest->headers_out, NULL);

    if (!ri->eos_seen()) {
        rv = ap_pass_brigade(pFilter->next, pBrigade);
        apr_brigade_cleanup(pBrigade);
        return rv;
    }

    // Pushing the answer to the processor
    prepareRequestInfo(tConf, pRequest, *ri);

    if ( tConf->synchronous ) {
        static __thread CURL * lCurl = NULL;
        if ( ! lCurl ) {
            lCurl = gProcessor->initCurl();
        }
        gProcessor->runOne(*ri, lCurl);
    }
    else {
        gThreadPool->push(*reqInfo);
    }
    pFilter->ctx = (void *) -1;
    printRequest(pRequest, ri, tConf);
    rv = ap_pass_brigade(pFilter->next, pBrigade);
    apr_brigade_cleanup(pBrigade);
    return rv;
}

};
<commit_msg>fix for when outputFilter is called before inputFilter, which happens when response body is large (>=8k)<commit_after>/*
* mod_dup - duplicates apache requests
*
* Copyright (C) 2013 Orange
*
* 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 "mod_dup.hh"
#include "Utils.hh"

#include <boost/shared_ptr.hpp>
#include <http_config.h>

namespace DupModule {

/*
 * Callback to iterate over the headers tables
 * Pushes a copy of key => value in a list passed without typing as the first argument
 */
static int iterateOverHeadersCallBack(void *d, const char *key, const char *value) {
    RequestInfo::tHeaders *headers = reinterpret_cast<RequestInfo::tHeaders *>(d);
    headers->push_back(std::pair<std::string, std::string>(key, value));
    return 1;
}

static void
prepareRequestInfo(DupConf *tConf, request_rec *pRequest, RequestInfo &r) {
    // Copy headers in
    apr_table_do(&iterateOverHeadersCallBack, &r.mHeadersIn, pRequest->headers_in, NULL);

    // Add the elapsed time header
    r.mHeadersOut.push_back(std::make_pair(std::string("ELAPSED_TIME_BY_DUP"), boost::lexical_cast<std::string>(r.getElapsedTimeMS())));

    // Basic
    r.mPoison = false;
    r.mConfPath = tConf->dirName;
    r.mPath = pRequest->uri;
    r.mArgs = pRequest->args ? pRequest->args : "";
}

static void
printRequest(request_rec *pRequest, RequestInfo *pBH, DupConf *tConf) {
    const char *reqId = apr_table_get(pRequest->headers_in, CommonModule::c_UNIQUE_ID);
    Log::debug("### Pushing a request with ID: %s, body size:%ld", reqId, pBH->mBody.size());
    Log::debug("### Uri:%s, dir name:%s", pRequest->uri, tConf->dirName);
    Log::debug("### Request args: %s", pRequest->args);
}

apr_status_t
inputFilterHandler(ap_filter_t *pFilter, apr_bucket_brigade *pB, ap_input_mode_t pMode, apr_read_type_e pBlock, apr_off_t pReadbytes) {
    request_rec *pRequest = pFilter->r;
    if (!pRequest || !pRequest->per_dir_config) {
        return ap_get_brigade(pFilter->next, pB, pMode, pBlock, pReadbytes);
    }
    struct DupConf *conf = reinterpret_cast<DupConf *>(ap_get_module_config(pRequest->per_dir_config, &dup_module));
    if (!conf || !conf->dirName) {
        // Not a location that we treat, we decline the request
        return ap_get_brigade(pFilter->next, pB, pMode, pBlock, pReadbytes);
    }

    RequestInfo *info = NULL;
    if (!pFilter->ctx) {
        boost::shared_ptr<RequestInfo> * reqInfo(reinterpret_cast<boost::shared_ptr<RequestInfo> *>(ap_get_module_config(pFilter->r->request_config, &dup_module)));
        if (!reqInfo || !reqInfo->get()) {
            // Unique request id
            std::string uid = CommonModule::getOrSetUniqueID(pRequest);
            info = new RequestInfo(uid);

            // Allocation on a shared pointer on the request pool
            // We guarantee that whatever happens, the RequestInfo will be deleted
            void *space = apr_palloc(pRequest->pool, sizeof(boost::shared_ptr<RequestInfo>));
            reqInfo = new (space) boost::shared_ptr<RequestInfo>(info);
            // Registering of the shared pointer destructor on the pool
            apr_pool_cleanup_register(pRequest->pool, space, cleaner<boost::shared_ptr<RequestInfo> >,
                                    apr_pool_cleanup_null);
            // Backup in request context
            ap_set_module_config(pRequest->request_config, &dup_module, (void *)space);
            // Backup in filter context

            info->mConfPath = conf->dirName;
            info->mArgs = pRequest->args ? pRequest->args : "";
        }
        pFilter->ctx = reqInfo->get();
    }
    if (pFilter->ctx != (void *) -1) {
        // Request not read yet
        info = reinterpret_cast<RequestInfo *>(pFilter->ctx);
        apr_status_t st = ap_get_brigade(pFilter->next, pB, pMode, pBlock, pReadbytes);
        if (st != APR_SUCCESS) {
            pFilter->ctx = (void *) -1;
            return st;
        }
        // Concats the brigade content to the reqinfo
        for (apr_bucket *b = APR_BRIGADE_FIRST(pB);
             b != APR_BRIGADE_SENTINEL(pB);
             b = APR_BUCKET_NEXT(b) ) {
            // Metadata end of stream
            if (APR_BUCKET_IS_EOS(b)) {
                return APR_SUCCESS;
            }
            if (APR_BUCKET_IS_METADATA(b))
                continue;
            const char *data = 0;
            apr_size_t len = 0;
            apr_status_t rv = apr_bucket_read(b, &data, &len, APR_BLOCK_READ);
            if (rv != APR_SUCCESS) {
                Log::error(42, "Bucket read failed, skipping the rest of the body");
                return rv;
            }
            if (len) {
                info->mBody.append(data, len);
            }
        }
    }
    // Data is read
    return APR_SUCCESS;
}

/**
 * Output Body filter handler
 * Writes the response body to the RequestInfo
 * Unless not needed because we only duplicate request and no reponses
 */
apr_status_t
outputBodyFilterHandler(ap_filter_t *pFilter, apr_bucket_brigade *pBrigade) {

    request_rec *pRequest = pFilter->r;
    apr_status_t rv;
    // Reject requests that do not meet our requirements
    if ((pFilter->ctx == (void *) -1) || !pRequest || !pRequest->per_dir_config) {
        rv = ap_pass_brigade(pFilter->next, pBrigade);
        apr_brigade_cleanup(pBrigade);
        return rv;
    }
    struct DupConf *tConf = reinterpret_cast<DupConf *>(ap_get_module_config(pRequest->per_dir_config, &dup_module));
    if ((!tConf) || (!tConf->dirName) || (tConf->getHighestDuplicationType() == DuplicationType::NONE)) {
        rv = ap_pass_brigade(pFilter->next, pBrigade);
        apr_brigade_cleanup(pBrigade);
        return rv;
    }

    RequestInfo * ri = NULL;
    boost::shared_ptr<RequestInfo> * reqInfo(reinterpret_cast<boost::shared_ptr<RequestInfo> *>(ap_get_module_config(pFilter->r->request_config, &dup_module)));
    if (!reqInfo || !reqInfo->get()) {
        if (!pFilter->ctx) {
            // Unique request id
            std::string uid = CommonModule::getOrSetUniqueID(pRequest);
            ri = new RequestInfo(uid);

            // Allocation on a shared pointer on the request pool
            // We guarantee that whatever happens, the RequestInfo will be deleted
            void *space = apr_palloc(pRequest->pool, sizeof(boost::shared_ptr<RequestInfo>));
            reqInfo = new (space) boost::shared_ptr<RequestInfo>(ri);
            // Registering of the shared pointer destructor on the pool
            apr_pool_cleanup_register(pRequest->pool, space, cleaner<boost::shared_ptr<RequestInfo> >,
                                    apr_pool_cleanup_null);
            // Backup in request context
            ap_set_module_config(pRequest->request_config, &dup_module, (void *)space);
            // Backup in filter context

            pFilter->ctx = ri;

            ri->mConfPath = tConf->dirName;
            ri->mArgs = pRequest->args ? pRequest->args : "";

        } else {
            // Should not happen
            pFilter->ctx = (void *) -1;
            rv = ap_pass_brigade(pFilter->next, pBrigade);
            apr_brigade_cleanup(pBrigade);
            return rv;
        }
    } else {
        ri = reqInfo->get();
    }

    // Write the response body to the RequestInfo if found
    apr_bucket *currentBucket;
    for ( currentBucket = APR_BRIGADE_FIRST(pBrigade);
          currentBucket != APR_BRIGADE_SENTINEL(pBrigade);
          currentBucket = APR_BUCKET_NEXT(currentBucket) ) {

        if (APR_BUCKET_IS_EOS(currentBucket)) {
            ri->eos_seen(true);
            pFilter->ctx = (void *) -1;
            rv = ap_pass_brigade(pFilter->next, pBrigade);
            apr_brigade_cleanup(pBrigade);
            return rv;
        }

        if (APR_BUCKET_IS_METADATA(currentBucket))
            continue;

        // We need to get the highest one as we haven't matched which rule it is yet
        if (tConf->getHighestDuplicationType() == DuplicationType::REQUEST_WITH_ANSWER) {

            const char *data;
            apr_size_t len;
            rv = apr_bucket_read(currentBucket, &data, &len, APR_BLOCK_READ);

            if ((rv == APR_SUCCESS) && data) {
                // Appends the part read to the answer
                ri->mAnswer.append(data, len);
            }
        }
    }
    rv = ap_pass_brigade(pFilter->next, pBrigade);
    apr_brigade_cleanup(pBrigade);
    return rv;
}

/**
 * Output filter handler
 * Retrieves in/out headers
 * Pushes the RequestInfo object to the RequestProcessor
 */
apr_status_t
outputHeadersFilterHandler(ap_filter_t *pFilter, apr_bucket_brigade *pBrigade) {

    apr_status_t rv;
    if ( pFilter->ctx == (void *) -1 ) {
        rv = ap_pass_brigade(pFilter->next, pBrigade);
        apr_brigade_cleanup(pBrigade);
        return rv;
    }

    request_rec *pRequest = pFilter->r;
    // Reject requests that do not meet our requirements
    if (!pRequest || !pRequest->per_dir_config) {
        pFilter->ctx = (void *) -1;
        rv = ap_pass_brigade(pFilter->next, pBrigade);
        apr_brigade_cleanup(pBrigade);
        return rv;
    }

    struct DupConf *tConf = reinterpret_cast<DupConf *>(ap_get_module_config(pRequest->per_dir_config, &dup_module));
    if ((!tConf) || (!tConf->dirName) || (tConf->getHighestDuplicationType() == DuplicationType::NONE)) {
        pFilter->ctx = (void *) -1;
        rv = ap_pass_brigade(pFilter->next, pBrigade);
        apr_brigade_cleanup(pBrigade);
        return rv;
    }

    RequestInfo * ri = NULL;
    boost::shared_ptr<RequestInfo> * reqInfo(reinterpret_cast<boost::shared_ptr<RequestInfo> *>(ap_get_module_config(pFilter->r->request_config, &dup_module)));
    if (!reqInfo || !reqInfo->get()) {
        if (!pFilter->ctx) {
            // Unique request id
            std::string uid = CommonModule::getOrSetUniqueID(pRequest);
            ri = new RequestInfo(uid);

            // Allocation on a shared pointer on the request pool
            // We guarantee that whatever happens, the RequestInfo will be deleted
            void *space = apr_palloc(pRequest->pool, sizeof(boost::shared_ptr<RequestInfo>));
            reqInfo = new (space) boost::shared_ptr<RequestInfo>(ri);
            // Registering of the shared pointer destructor on the pool
            apr_pool_cleanup_register(pRequest->pool, space, cleaner<boost::shared_ptr<RequestInfo> >,
                                      apr_pool_cleanup_null);
            // Backup in request context
            ap_set_module_config(pRequest->request_config, &dup_module, (void *)space);
            // Backup in filter context

            pFilter->ctx = ri;

            ri->mConfPath = tConf->dirName;
            ri->mArgs = pRequest->args ? pRequest->args : "";
        } else {
            // Should not happen
            pFilter->ctx = (void *) -1;
            rv = ap_pass_brigade(pFilter->next, pBrigade);
            apr_brigade_cleanup(pBrigade);
            return rv;
        }
    } else {
        ri = reqInfo->get();
    }

    // Copy headers out
    apr_table_do(&iterateOverHeadersCallBack, &ri->mHeadersOut, pRequest->headers_out, NULL);

    if (!ri->eos_seen()) {
        rv = ap_pass_brigade(pFilter->next, pBrigade);
        apr_brigade_cleanup(pBrigade);
        return rv;
    }

    // Pushing the answer to the processor
    prepareRequestInfo(tConf, pRequest, *ri);

    if ( tConf->synchronous ) {
        static __thread CURL * lCurl = NULL;
        if ( ! lCurl ) {
            lCurl = gProcessor->initCurl();
        }
        gProcessor->runOne(*ri, lCurl);
    }
    else {
        gThreadPool->push(*reqInfo);
    }
    pFilter->ctx = (void *) -1;
    printRequest(pRequest, ri, tConf);
    rv = ap_pass_brigade(pFilter->next, pBrigade);
    apr_brigade_cleanup(pBrigade);
    return rv;
}

};
<|endoftext|>


<commit_before>/*
 * Distributed under the OSI-approved Apache License, Version 2.0.  See
 * accompanying file Copyright.txt for details.
 *
 * helloADIOS1Writer_nompi.cpp : non mpi version of helloADIOS1Writer
 *
 *  Created on: Jan 9, 2017
 *      Author: Norbert Podhorszki pnorbert@ornl.gov
 */

#include <iostream>
#include <vector>

#include <adios2.h>

int main(int argc, char *argv[])
{
    /** Application variable */
    std::vector<float> myFloats = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9};
    const std::size_t Nx = myFloats.size();

    try
    {
        /** ADIOS class factory of IO class objects, DebugON is recommended */
        adios::ADIOS adios(MPI_COMM_WORLD, adios::DebugON);

        /*** IO class object: settings and factory of Settings: Variables,
         * Parameters, Transports, and Execution: Engines */
        adios::IO &adios1IO = adios.DeclareIO("ADIOS1IO");
        adios1IO.SetEngine("ADIOS1Writer");
        adios1IO.AddTransport("file");

        /** global array : name, { shape (total) }, { start (local) }, { count
         * (local) }, all are constant dimensions */
        adios::Variable<float> &bpFloats = adios1IO.DefineVariable<float>(
            "bpFloats", {}, {}, {Nx}, adios::ConstantDims);

        /** Engine derived class, spawned to start IO operations */
        auto adios1Writer =
            adios1IO.Open("myVector.bp", adios::OpenMode::Write);

        if (!adios1Writer)
        {
            throw std::ios_base::failure(
                "ERROR: hdf5Writer not created at Open\n");
        }

        /** Write variable for buffering */
        adios1Writer->Write<float>(bpFloats, myFloats.data());

        /** Create bp file, engine becomes unreachable after this*/
        adios1Writer->Close();
    }
    catch (std::invalid_argument &e)
    {
        std::cout << "Invalid argument exception, STOPPING PROGRAM\n";
        std::cout << e.what() << "\n";
    }
    catch (std::ios_base::failure &e)
    {
        std::cout << "System exception, STOPPING PROGRAM\n";
        std::cout << e.what() << "\n";
    }
    catch (std::exception &e)
    {
        std::cout << "Exception, STOPPING PROGRAM\n";
        std::cout << e.what() << "\n";
    }

    return 0;
}
<commit_msg>Williamfgc refactor examples basics (#10)<commit_after>/*
 * Distributed under the OSI-approved Apache License, Version 2.0.  See
 * accompanying file Copyright.txt for details.
 *
 * helloADIOS1Writer_nompi.cpp : non mpi version of helloADIOS1Writer
 *
 *  Created on: Jan 9, 2017
 *      Author: Norbert Podhorszki pnorbert@ornl.gov
 */

#include <iostream>
#include <vector>

#include <adios2.h>

int main(int argc, char *argv[])
{
    /** Application variable */
    std::vector<float> myFloats = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9};
    const std::size_t Nx = myFloats.size();

    try
    {
        /** ADIOS class factory of IO class objects, DebugON is recommended */
        adios::ADIOS adios(adios::DebugON);

        /*** IO class object: settings and factory of Settings: Variables,
         * Parameters, Transports, and Execution: Engines */
        adios::IO &adios1IO = adios.DeclareIO("ADIOS1IO");
        adios1IO.SetEngine("ADIOS1Writer");
        adios1IO.AddTransport("file");

        /** global array : name, { shape (total) }, { start (local) }, { count
         * (local) }, all are constant dimensions */
        adios::Variable<float> &bpFloats = adios1IO.DefineVariable<float>(
            "bpFloats", {}, {}, {Nx}, adios::ConstantDims);

        /** Engine derived class, spawned to start IO operations */
        auto adios1Writer =
            adios1IO.Open("myVector.bp", adios::OpenMode::Write);

        if (!adios1Writer)
        {
            throw std::ios_base::failure(
                "ERROR: hdf5Writer not created at Open\n");
        }

        /** Write variable for buffering */
        adios1Writer->Write<float>(bpFloats, myFloats.data());

        /** Create bp file, engine becomes unreachable after this*/
        adios1Writer->Close();
    }
    catch (std::invalid_argument &e)
    {
        std::cout << "Invalid argument exception, STOPPING PROGRAM\n";
        std::cout << e.what() << "\n";
    }
    catch (std::ios_base::failure &e)
    {
        std::cout << "System exception, STOPPING PROGRAM\n";
        std::cout << e.what() << "\n";
    }
    catch (std::exception &e)
    {
        std::cout << "Exception, STOPPING PROGRAM\n";
        std::cout << e.what() << "\n";
    }

    return 0;
}
<|endoftext|>


<commit_before>/*
  Copyright (c) 2012 Carsten Burstedde, Donna Calhoun
  All rights reserved.

  Redistribution and use in source and binary forms, with or without
  modification, are permitted provided that the following conditions are met:

  * Redistributions of source code must retain the above copyright notice, this
  list of conditions and the following disclaimer.
  * Redistributions in binary form must reproduce the above copyright notice,
  this list of conditions and the following disclaimer in the documentation
  and/or other materials provided with the distribution.

  THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
  ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
  WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
  DISCLAIMED.  IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
  FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
  DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
  SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
  CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
  OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/

#include <amr_single_step.h>
#include <fclaw2d_map.h>
#include <p4est_connectivity.h>

#include <amr_forestclaw.H>
#include <amr_utils.H>
#include <fclaw_options.h>

#include <fclaw2d_map_query.h>

#include <fc2d_clawpack46.H>

#include "sphere_user.H"

typedef struct user_options
{
    int example;
    int is_registered;

} user_options_t;

static void *
options_register_user (fclaw_app_t * app, void *package, sc_options_t * opt)
{
    user_options_t* user = (user_options_t*) package;

    sc_options_add_int (opt, 0, "example", &user->example, 0,
                        "[user] 1 for pillow grid, "    \
                        "2 for cubed sphere ");
    user->is_registered = 1;
    return NULL;
}

static fclaw_exit_type_t
options_check_user (fclaw_app_t * app, void *package, void *registered)
{
    user_options_t* user = (user_options_t*) package;
    if (user->example < 1 || user->example > 2) {
        fclaw_global_essentialf ("Option --user:example must be 1 or 2\n");
        return FCLAW_EXIT_ERROR;
    }
    return FCLAW_NOEXIT;
}

static const fclaw_app_options_vtable_t options_vtable_user = {
    options_register_user,
    NULL,      /* options_postprocess_user */
    options_check_user,
    NULL       /* options_destroy_user */
};

void static
register_user_options (fclaw_app_t * app,
                       const char *configfile,
                       user_options_t* user)
{
    FCLAW_ASSERT (app != NULL);

    fclaw_app_options_register (app,"user", configfile, &options_vtable_user,
                                user);
}

static
void run_program(fclaw_app_t* app, amr_options_t* gparms,
                 fc2d_clawpack46_options_t* clawpack_options,
                 user_options_t* user)
{
    sc_MPI_Comm            mpicomm;

    /* Mapped, multi-block domain */
    p4est_connectivity_t     *conn = NULL;
    fclaw2d_domain_t	     *domain;
    fclaw2d_map_context_t    *cont = NULL;

    /* Used locally */
    double pi = M_PI;
    double rotate[2];

    mpicomm = fclaw_app_get_mpi_size_rank (app, NULL, NULL);

    rotate[0] = pi*gparms->theta/180.0;
    rotate[1] = pi*gparms->phi/180.0;

    switch (user->example) {
    case 1:
        conn = p4est_connectivity_new_pillow();
        cont = fclaw2d_map_new_pillowsphere(gparms->scale,gparms->shift,rotate);
        break;
    case 2:
        conn = p4est_connectivity_new_cubed();
        cont = fclaw2d_map_new_cubedsphere(gparms->scale,gparms->shift,rotate);
        break;
    default:
        SC_ABORT_NOT_REACHED (); /* must be checked in torus_checkparms */
    }

    domain = fclaw2d_domain_new_conn_map (mpicomm, gparms->minlevel, conn, cont);

    fclaw2d_domain_list_levels(domain, FCLAW_VERBOSITY_ESSENTIAL);
    fclaw2d_domain_list_neighbors(domain, FCLAW_VERBOSITY_DEBUG);

    /* ---------------------------------------------------------------
       Set domain data.
       --------------------------------------------------------------- */
    init_domain_data(domain);

    /* Store parameters */
    set_domain_parms(domain,gparms);
    fc2d_clawpack46_set_options (domain,clawpack_options);

    /* Link solvers to the domain */
    link_problem_setup(domain,sphere_problem_setup);

    sphere_link_solvers(domain);

    /* --------------------------------------------------
       Initialize and run the simulation
       -------------------------------------------------- */
    amrinit(&domain);
    amrrun(&domain);
    amrreset(&domain);

    /* --------------------------------------------------
       Clean up the mapping context.
       -------------------------------------------------- */
    fclaw2d_map_destroy (cont);
}

int main (int argc, char **argv)
{
  fclaw_app_t *app;
  int first_arg;
  fclaw_exit_type_t vexit;

  /* Options */
  sc_options_t             *options;
  amr_options_t            samr_options,      *gparms = &samr_options;
  fc2d_clawpack46_options_t     sclawpack_options, *clawpack_options = &sclawpack_options;
  user_options_t           suser_options,     *user = &suser_options;

  int retval;

  /* Initialize application */
  app = fclaw_app_new (&argc, &argv, user);
  options = fclaw_app_get_options (app);

  /*  Register options for each package */
  fclaw_options_register_general (app, "fclaw_options.ini", gparms);
  fc2d_clawpack46_options_register (app, "fclaw_options.ini", clawpack_options);

  register_user_options (app, "fclaw_options.ini", user);

  /* Read configuration file(s) and command line, and process options */
  retval = fclaw_options_read_from_file(options);
  vexit =  fclaw_app_options_parse (app, &first_arg,"fclaw_options.ini.used");

  /* -------------------------------------------------------------
     - Run program
     ------------------------------------------------------------- */
    if (!retval & !vexit)
    {
        run_program(app, gparms, clawpack_options, user);
    }

    fclaw_app_destroy (app);

    return 0;
}
<commit_msg>(sphere) Add new package handling features<commit_after>/*
  Copyright (c) 2012 Carsten Burstedde, Donna Calhoun
  All rights reserved.

  Redistribution and use in source and binary forms, with or without
  modification, are permitted provided that the following conditions are met:

  * Redistributions of source code must retain the above copyright notice, this
  list of conditions and the following disclaimer.
  * Redistributions in binary form must reproduce the above copyright notice,
  this list of conditions and the following disclaimer in the documentation
  and/or other materials provided with the distribution.

  THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
  ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
  WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
  DISCLAIMED.  IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
  FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
  DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
  SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
  CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
  OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/

#include <amr_single_step.h>
#include <fclaw2d_map.h>
#include <p4est_connectivity.h>

#include <amr_forestclaw.H>
#include <amr_utils.H>
#include <fclaw_options.h>

#include <fclaw2d_map_query.h>

#include <fclaw_package.h>
#include <fc2d_clawpack46.H>

#include "sphere_user.H"

typedef struct user_options
{
    int example;
    int is_registered;

} user_options_t;

static void *
options_register_user (fclaw_app_t * app, void *package, sc_options_t * opt)
{
    user_options_t* user = (user_options_t*) package;

    sc_options_add_int (opt, 0, "example", &user->example, 0,
                        "[user] 1 for pillow grid, "    \
                        "2 for cubed sphere ");
    user->is_registered = 1;
    return NULL;
}

static fclaw_exit_type_t
options_check_user (fclaw_app_t * app, void *package, void *registered)
{
    user_options_t* user = (user_options_t*) package;
    if (user->example < 1 || user->example > 2) {
        fclaw_global_essentialf ("Option --user:example must be 1 or 2\n");
        return FCLAW_EXIT_ERROR;
    }
    return FCLAW_NOEXIT;
}

static const fclaw_app_options_vtable_t options_vtable_user = {
    options_register_user,
    NULL,      /* options_postprocess_user */
    options_check_user,
    NULL       /* options_destroy_user */
};

void static
register_user_options (fclaw_app_t * app,
                       const char *configfile,
                       user_options_t* user)
{
    FCLAW_ASSERT (app != NULL);

    fclaw_app_options_register (app,"user", configfile, &options_vtable_user,
                                user);
}

static
void run_program(fclaw_app_t* app, amr_options_t* gparms,
                 fc2d_clawpack46_options_t* clawpack_options,
                 user_options_t* user)
{
    sc_MPI_Comm            mpicomm;

    /* Mapped, multi-block domain */
    p4est_connectivity_t     *conn = NULL;
    fclaw2d_domain_t	     *domain;
    fclaw2d_map_context_t    *cont = NULL;

    /* Used locally */
    double pi = M_PI;
    double rotate[2];

    mpicomm = fclaw_app_get_mpi_size_rank (app, NULL, NULL);

    rotate[0] = pi*gparms->theta/180.0;
    rotate[1] = pi*gparms->phi/180.0;

    switch (user->example) {
    case 1:
        conn = p4est_connectivity_new_pillow();
        cont = fclaw2d_map_new_pillowsphere(gparms->scale,gparms->shift,rotate);
        break;
    case 2:
        conn = p4est_connectivity_new_cubed();
        cont = fclaw2d_map_new_cubedsphere(gparms->scale,gparms->shift,rotate);
        break;
    default:
        SC_ABORT_NOT_REACHED (); /* must be checked in torus_checkparms */
    }

    domain = fclaw2d_domain_new_conn_map (mpicomm, gparms->minlevel, conn, cont);

    fclaw2d_domain_list_levels(domain, FCLAW_VERBOSITY_ESSENTIAL);
    fclaw2d_domain_list_neighbors(domain, FCLAW_VERBOSITY_DEBUG);

    /* ---------------------------------------------------------------
       Set domain data.
       --------------------------------------------------------------- */
    init_domain_data(domain);

    /* Store parameters */
    set_domain_parms(domain,gparms);
    fc2d_clawpack46_set_options (domain,clawpack_options);

    /* Link solvers to the domain */
    link_problem_setup(domain,sphere_problem_setup);

    sphere_link_solvers(domain);

    /* --------------------------------------------------
       Initialize and run the simulation
       -------------------------------------------------- */
    amrinit(&domain);
    amrrun(&domain);
    amrreset(&domain);

    /* --------------------------------------------------
       Clean up the mapping context.
       -------------------------------------------------- */
    fclaw2d_map_destroy (cont);
}

int main (int argc, char **argv)
{
  fclaw_app_t *app;
  int first_arg;
  fclaw_exit_type_t vexit;

  /* Options */
  sc_options_t             *options;
  amr_options_t            samr_options,      *gparms = &samr_options;
  fc2d_clawpack46_options_t     sclawpack_options, *clawpack_options = &sclawpack_options;
  user_options_t           suser_options,     *user = &suser_options;

  int clawpack46_id;
  fclaw_package_container_t* pkgs;

  int retval;

  /* Initialize application */
  app = fclaw_app_new (&argc, &argv, user);
  options = fclaw_app_get_options (app);

  /*  Register options for each package */
  fclaw_options_register_general (app, "fclaw_options.ini", gparms);
  fc2d_clawpack46_options_register (app, "fclaw_options.ini", clawpack_options);

  register_user_options (app, "fclaw_options.ini", user);

  /* Read configuration file(s) and command line, and process options */
  retval = fclaw_options_read_from_file(options);
  vexit =  fclaw_app_options_parse (app, &first_arg,"fclaw_options.ini.used");

  pkgs = fclaw_package_collection_init();
  clawpack46_id = fc2d_clawpack46_package_register(pkgs,clawpack_options);

  ClawPatch::package_container = *pkgs;

  /* -------------------------------------------------------------
     - Run program
     ------------------------------------------------------------- */
    if (!retval & !vexit)
    {
        run_program(app, gparms, clawpack_options, user);
    }

    fclaw_package_collection_destroy(pkgs);
    fclaw_app_destroy (app);

    return 0;
}
<|endoftext|>


<commit_before>////////////////////////////////////////////////////////////////////////
// This file is part of Grappa, a system for scaling irregular
// applications on commodity clusters.

// Copyright (C) 2010-2014 University of Washington and Battelle
// Memorial Institute. University of Washington authorizes use of this
// Grappa software.

// Grappa is free software: you can redistribute it and/or modify it
// under the terms of the Affero General Public License as published
// by Affero, Inc., either version 1 of the License, or (at your
// option) any later version.

// Grappa 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
// Affero General Public License for more details.

// You should have received a copy of the Affero General Public
// License along with this program. If not, you may obtain one from
// http://www.affero.org/oagpl.html.
////////////////////////////////////////////////////////////////////////

#include <Grappa.hpp>

using namespace Grappa;
using namespace std;

DEFINE_int64( n, 8, "Board size" );

GRAPPA_DEFINE_METRIC( SimpleMetric<double>, nqueens_runtime, 0.0 );

/*
 * Each core maintains the number of solutions it has found + the board size
 */
int64_t nqSolutions;
int nqBoardSize;
GlobalCompletionEvent gce;      // tasks synchronization

/*
 * Checks whether it is safe to put a queen in row 'row' in the current
 * column. Vector 'cols' has the row position for the queens in the previous
 * columns.
 */
bool nqIsSafe(int row, vector<int> &cols)
{
  int n = cols.size();

  /* we check if putting a queen on row 'row' will cause any of the previous
   * queens (in 'cols') to capture it.
   */
  for (auto i=0; i<n; i++) {
    if (row == cols[i] || abs(n-i) == abs(row-cols[i]))
      return false;  // captured - not safe
  }

  return true;
}

/*
 * This is basically a brute force solution using recursion.
 *
 * Vector 'cols' stores, for each column, the row number of a queen. We start
 * with an empty vector (i.e., placing queens on the first column), check if
 * it is safe to place a queen on a specific row and recursively call nqSearch
 * to check for the next column.
 */
void nqSearch(GlobalAddress< vector<int> > cols)
{

  /* get the size of the vector */
  int vsize = delegate::call(cols, [](vector<int> &v) { return v.size(); });

  /* are we done yet? */
  if (vsize == nqBoardSize) {
    nqSolutions++;
    return;
  }

  /* check whether it is safe to consider a queen for the next column */
  for (int i=0; i<nqBoardSize; i++) {

    /* safe? code is executed at the core that owns the vector */
    bool safe = delegate::call(cols, [i](vector<int> &v) {
      bool safe = nqIsSafe(i, v);
      return safe;
      });

    /* if not safe we are done - otherwise create a new vector and do
     * a recursive call to nqSearch */
    if (safe) {

      vector<int> *mv = new vector<int>(0);

      /* copy the original vector to the new one we just created */
      for (auto k=0; k<vsize; k++) {
        mv->push_back(delegate::call(cols, [k](vector<int> &v) { return v[k]; }));
      }
      mv->push_back(i);

      GlobalAddress< vector<int> > g_mv = make_global(mv);

      /* spawn a recursive search */
      spawn<unbound,&gce>([g_mv] { nqSearch(g_mv); });
    }
  }

  /* delete original vector */
  delegate::call(cols, [](vector<int> &v) { delete &v; });

}

int main(int argc, char * argv[]) {
  init( &argc, &argv );

  const int expectedSolutions[] =
  {0, 1, 0, 0, 2, 10, 4, 40, 92, 352, 724, 2680, 14200, 73712, 365596, \
    2279184, 14772512};

  nqBoardSize = FLAGS_n;
  nqSolutions = 0;

  run([=]{

    double start = walltime();

    vector<int> *cols = new vector<int>(0);
    GlobalAddress< vector<int> > g_cols = make_global(cols);

    finish<&gce>([g_cols]{
      nqSearch(g_cols);
    });

    int64_t total = reduce<int64_t,collective_add<int64_t>>(&nqSolutions);

    nqueens_runtime = walltime() - start;

    if (nqBoardSize <= 16) {
      LOG(INFO) << "NQueens (" << nqBoardSize << ") = " << total << \
        " (solution is " << (total == expectedSolutions[nqBoardSize] ? "correct)" : "wrong)");
    }
    else
      LOG(INFO) << "NQueens (" << nqBoardSize << ") = " << total;

    LOG(INFO) << "Elapsed time: " << nqueens_runtime.value() << " seconds";

  });
  finalize();
}

<commit_msg>Deleting a wrongly-added file =P<commit_after><|endoftext|>


<commit_before>/*
	Copyright (C) 2016 Claude SIMON (http://zeusw.org/epeios/contact.html).

	This file is part of 'eSketch' software.

    'eSketch' is free software: you can redistribute it and/or modify it
    under the terms of the GNU Affero General Public License as published
    by the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    'eSketch' 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 Affero General Public License for more details.

    You should have received a copy of the GNU Affero General Public License
    along with 'eSketch'.  If not, see <http://www.gnu.org/licenses/>.
*/

#include "sclxdhtml.h"
#include "sclmisc.h"

#include "frdrgstry.h"

#include "core.h"

const char *sclmisc::SCLMISCTargetName = BASE_NAME;

void sclxdhtml::SCLXDHTMLInitialization( xdhcmn::mode__ Mode )
{
qRH
	sclfrntnd::rFeatures Features;
qRB
	core::Core.Init( Mode );

	if ( Mode == xdhcmn::mMultiUser ) {
		Features.Init();
		sclfrntnd::GuessBackendFeatures( Features );
		core::Kernel().Init( Features, plgn::EmptyAbstracts );
	}
qRR
qRT
qRE
}

xdhcmn::session_callback__ *sclxdhtml::SCLXDHTMLRetrieveCallback(
	const char *Language,
	xdhcmn::proxy_callback__ *ProxyCallback )
{
	core::rSession *Session = new core::rSession;

	if ( Session == NULL )
		qRGnr();

	Session->Init( core::Kernel(), Language, ProxyCallback );

	switch ( core::Core.Mode() ) {
	case xdhcmn::mMonoUser:
		switch ( sclfrntnd::HandleProject() ) {
		case sclfrntnd::phNone:
			::prolog::SetLayout( *Session );
			break;
		case sclfrntnd::phLoad:
			::login::SetLayout( *Session );
			break;
		case sclfrntnd::phLogin:
			Session->SetBackendVisibility( sclxdhtml::bvHide );
			::login::SetLayout( *Session );
			break;
		case sclfrntnd::phRun:
			::main::SetLayout( *Session );
			break;
		default:
			qRGnr();
			break;
		}
		break;
	case xdhcmn::mMultiUser:
//		login::SetLayout( *Session );
		break;
	default:
		qRGnr();
		break;
	}

	return Session;
}

void sclxdhtml::SCLXDHTMLReleaseCallback( xdhcmn::session_callback__ *Callback )
{
	if ( Callback == NULL )
		qRGnr();

	delete Callback;
}

<commit_msg>14/10/2016 11:03:12<commit_after>/*
	Copyright (C) 2016 Claude SIMON (http://zeusw.org/epeios/contact.html).

	This file is part of 'eSketch' software.

    'eSketch' is free software: you can redistribute it and/or modify it
    under the terms of the GNU Affero General Public License as published
    by the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    'eSketch' 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 Affero General Public License for more details.

    You should have received a copy of the GNU Affero General Public License
    along with 'eSketch'.  If not, see <http://www.gnu.org/licenses/>.
*/

#include "sclxdhtml.h"
#include "sclmisc.h"

#include "frdrgstry.h"

#include "core.h"

void sclxdhtml::SCLXDHTMLInitialization( xdhcmn::mode__ Mode )
{
qRH
	sclfrntnd::rFeatures Features;
qRB
	core::Core.Init( Mode );

	if ( Mode == xdhcmn::mMultiUser ) {
		Features.Init();
		sclfrntnd::GuessBackendFeatures( Features );
		core::Kernel().Init( Features, plgn::EmptyAbstracts );
	}
qRR
qRT
qRE
}

xdhcmn::session_callback__ *sclxdhtml::SCLXDHTMLRetrieveCallback(
	const char *Language,
	xdhcmn::proxy_callback__ *ProxyCallback )
{
	core::rSession *Session = new core::rSession;

	if ( Session == NULL )
		qRGnr();

	Session->Init( core::Kernel(), Language, ProxyCallback );

	switch ( core::Core.Mode() ) {
	case xdhcmn::mMonoUser:
		switch ( sclfrntnd::HandleProject() ) {
		case sclfrntnd::phNone:
			::prolog::SetLayout( *Session );
			break;
		case sclfrntnd::phLoad:
			::login::SetLayout( *Session );
			break;
		case sclfrntnd::phLogin:
			Session->SetBackendVisibility( sclxdhtml::bvHide );
			::login::SetLayout( *Session );
			break;
		case sclfrntnd::phRun:
			::main::SetLayout( *Session );
			break;
		default:
			qRGnr();
			break;
		}
		break;
	case xdhcmn::mMultiUser:
//		login::SetLayout( *Session );
		break;
	default:
		qRGnr();
		break;
	}

	return Session;
}

void sclxdhtml::SCLXDHTMLReleaseCallback( xdhcmn::session_callback__ *Callback )
{
	if ( Callback == NULL )
		qRGnr();

	delete Callback;
}

const char *sclmisc::SCLMISCTargetName = BASE_NAME;
const char *sclmisc::SCLMISCProductName = SKTINF_MC_AFFIX;
<|endoftext|>