<commit_before>//-----------------------------------------------------------------------bl-
//--------------------------------------------------------------------------
//
// GRINS - General Reacting Incompressible Navier-Stokes
//
// Copyright (C) 2014 Paul T. Bauman, Roy H. Stogner
// Copyright (C) 2010-2013 The PECOS Development Team
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the Version 2.1 GNU Lesser General
// Public License as published by the Free Software Foundation.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc. 51 Franklin Street, Fifth Floor,
// Boston, MA  02110-1301  USA
//
//-----------------------------------------------------------------------el-

// This class
#include "grins/elastic_membrane.h"

// GRINS
#include "grins_config.h"
#include "grins/assembly_context.h"

// libMesh
#include "libmesh/getpot.h"
#include "libmesh/quadrature.h"
#include "libmesh/boundary_info.h"
#include "libmesh/fem_system.h"

namespace GRINS
{
  template<typename ElasticityTensor>
  ElasticMembrane<ElasticityTensor>::ElasticMembrane( const GRINS::PhysicsName& physics_name, const GetPot& input )
    : Physics(physics_name,input),
      _disp_vars(input,physics_name),
      _C(input)
  {
    return;
  }

  template<typename ElasticityTensor>
  ElasticMembrane<ElasticityTensor>::~ElasticMembrane()
  {
    return;
  }

  template<typename ElasticityTensor>
  void ElasticMembrane<ElasticityTensor>::init_variables( libMesh::FEMSystem* system )
  {
    // is_2D = false, is_3D = true
    _disp_vars.init(system,false,true);

    return;
  }

  template<typename ElasticityTensor>
  void ElasticMembrane<ElasticityTensor>::set_time_evolving_vars( libMesh::FEMSystem* system )
  {
    // Tell the system to march temperature forward in time
    system->time_evolving(_disp_vars.u_var());
    system->time_evolving(_disp_vars.v_var());
    system->time_evolving(_disp_vars.w_var());

    return;
  }

  template<typename ElasticityTensor>
  void ElasticMembrane<ElasticityTensor>::init_context( AssemblyContext& context )
  {
    context.get_element_fe(_disp_vars.u_var())->get_JxW();
    context.get_element_fe(_disp_vars.u_var())->get_dphi();

    // Need for constructing metric tensors
    context.get_element_fe(_disp_vars.u_var())->get_dxyzdxi();
    context.get_element_fe(_disp_vars.u_var())->get_dxyzdeta();
    context.get_element_fe(_disp_vars.u_var())->get_dxidx();
    context.get_element_fe(_disp_vars.u_var())->get_dxidy();
    context.get_element_fe(_disp_vars.u_var())->get_dxidz();
    context.get_element_fe(_disp_vars.u_var())->get_detadx();
    context.get_element_fe(_disp_vars.u_var())->get_detady();
    context.get_element_fe(_disp_vars.u_var())->get_detadz();

    return;
  }

  template<typename ElasticityTensor>
  void ElasticMembrane<ElasticityTensor>::element_time_derivative( bool compute_jacobian,
                                                                   AssemblyContext& context,
                                                                   CachedValues& /*cache*/ )
  {
    const unsigned int n_u_dofs = context.get_dof_indices(_disp_vars.u_var()).size();

    const std::vector<libMesh::Real> &JxW =
      context.get_element_fe(_disp_vars.u_var())->get_JxW();

    const std::vector<std::vector<libMesh::RealGradient> >& u_gradphi =
      context.get_element_fe(_disp_vars.u_var())->get_dphi();

    libMesh::DenseSubVector<libMesh::Number> &Fu = context.get_elem_residual(_disp_vars.u_var());
    libMesh::DenseSubVector<libMesh::Number> &Fv = context.get_elem_residual(_disp_vars.v_var());
    libMesh::DenseSubVector<libMesh::Number> &Fw = context.get_elem_residual(_disp_vars.w_var());

    unsigned int n_qpoints = context.get_element_qrule().n_points();

    const std::vector<libMesh::RealGradient>& dxdxi  = context.get_element_fe(_disp_vars.u_var())->get_dxyzdxi();
    const std::vector<libMesh::RealGradient>& dxdeta = context.get_element_fe(_disp_vars.u_var())->get_dxyzdeta();

    const std::vector<libMesh::Real>& dxidx  = context.get_element_fe(_disp_vars.u_var())->get_dxidx();
    const std::vector<libMesh::Real>& dxidy  = context.get_element_fe(_disp_vars.u_var())->get_dxidy();
    const std::vector<libMesh::Real>& dxidz  = context.get_element_fe(_disp_vars.u_var())->get_dxidz();

    const std::vector<libMesh::Real>& detadx  = context.get_element_fe(_disp_vars.u_var())->get_detadx();
    const std::vector<libMesh::Real>& detady  = context.get_element_fe(_disp_vars.u_var())->get_detady();
    const std::vector<libMesh::Real>& detadz  = context.get_element_fe(_disp_vars.u_var())->get_detadz();

    for (unsigned int qp=0; qp != n_qpoints; qp++)
      {
        libMesh::Gradient grad_u = context.interior_gradient(_disp_vars.u_var(), qp);
        libMesh::Gradient grad_v = context.interior_gradient(_disp_vars.v_var(), qp);
        libMesh::Gradient grad_w = context.interior_gradient(_disp_vars.w_var(), qp);

        libMesh::RealGradient grad_x( dxdxi[qp](0), dxdeta[qp](0) );
        libMesh::RealGradient grad_y( dxdxi[qp](1), dxdeta[qp](1) );
        libMesh::RealGradient grad_z( dxdxi[qp](2), dxdeta[qp](2) );

        libMesh::RealGradient dudxi( grad_u(0), grad_v(0), grad_w(0) );
        libMesh::RealGradient dudeta( grad_u(1), grad_v(1), grad_w(1) );

        libMesh::RealGradient dxi( dxidx[qp], dxidy[qp], dxidz[qp] );
        libMesh::RealGradient deta( detadx[qp], detady[qp], detadz[qp] );

        // Covariant metric tensor of reference configuration
        libMesh::TensorValue<libMesh::Real> a_cov( dxdxi[qp]*dxdxi[qp], dxdxi[qp]*dxdeta[qp], 0.0,
                                                   dxdeta[qp]*dxdxi[qp], dxdeta[qp]*dxdeta[qp] );

        // Covariant metric tensor of current configuration
        libMesh::TensorValue<libMesh::Real> A_cov( (dxdxi[qp] + dudxi)*(dxdxi[qp] + dudxi),
                                                   (dxdxi[qp] + dudxi)*(dxdeta[qp] + dudeta), 0.0,
                                                   (dxdeta[qp] + dudeta)*(dxdxi[qp] + dudxi),
                                                   (dxdeta[qp] + dudeta)*(dxdeta[qp] + dudeta) );

        // Contravariant metric tensor of reference configuration
        libMesh::TensorValue<libMesh::Real> a_contra( dxi*dxi, dxi*deta, 0.0,
                                                      deta*dxi, deta*deta );

        // Strain tensor
        libMesh::TensorValue<libMesh::Real> strain = 0.5*(A_cov - a_cov);

        // Compute stress tensor
        libMesh::TensorValue<libMesh::Real> tau = this->compute_stress(a_contra,strain);

        libMesh::Real jac = JxW[qp];

        for (unsigned int i=0; i != n_u_dofs; i++)
	  {
            for( unsigned int alpha = 0; alpha < 2; alpha++ )
              {
                for( unsigned int beta = 0; beta < 2; beta++ )
                  {
                    Fu(i) -= 0.5*tau(alpha,beta)*( (grad_x(beta) + grad_u(beta))*u_gradphi[i][qp](alpha) +
                                                   (grad_x(alpha) + grad_u(alpha))*u_gradphi[i][qp](beta) )*jac;

                    Fv(i) -= 0.5*tau(alpha,beta)*( (grad_y(beta) + grad_v(beta))*u_gradphi[i][qp](alpha) +
                                                   (grad_y(alpha) + grad_v(alpha))*u_gradphi[i][qp](beta) )*jac;

                    Fw(i) -= 0.5*tau(alpha,beta)*( (grad_z(beta) + grad_w(beta))*u_gradphi[i][qp](alpha) +
                                                   (grad_z(alpha) + grad_w(alpha))*u_gradphi[i][qp](beta) )*jac;
                  }
              }
            if( compute_jacobian )
              {
                libmesh_not_implemented();
              }
          }

      }

    return;
  }

  template<typename ElasticityTensor>
  void ElasticMembrane<ElasticityTensor>::side_time_derivative( bool compute_jacobian,
                                                                AssemblyContext& context,
                                                                CachedValues& cache )
  {
    /*
      std::vector<BoundaryID> ids = context.side_boundary_ids();

      for( std::vector<BoundaryID>::const_iterator it = ids.begin();
      it != ids.end(); it++ )
      {
      libmesh_assert (*it != libMesh::BoundaryInfo::invalid_id);

      _bc_handler->apply_neumann_bcs( context, cache, compute_jacobian, *it );
      }
    */

    return;
  }

  template<typename ElasticityTensor>
  void ElasticMembrane<ElasticityTensor>::mass_residual( bool compute_jacobian,
                                                         AssemblyContext& context,
                                                         CachedValues& cache )
  {
    libmesh_not_implemented();
    return;
  }

  template<typename ElasticityTensor>
  libMesh::TensorValue<libMesh::Real> ElasticMembrane<ElasticityTensor>::compute_stress(libMesh::TensorValue<libMesh::Real>& a_contra,
                                                                                libMesh::TensorValue<libMesh::Real>& strain)
  {
    libMesh::TensorValue<libMesh::Real> tau;

    (this->_C).recompute_elasticity(a_contra);

    for( unsigned int alpha = 0; alpha < 2; alpha++ )
      {
        for( unsigned int beta = 0; beta < 2; beta++ )
          {
            for( unsigned int gamma = 0; gamma < 2; gamma++ )
              {
                for( unsigned int delta = 0; delta < 2; delta++ )
                  {
                    tau(alpha,beta) += (this->_C(alpha,beta,gamma,delta))*strain(gamma,delta);
                  }
              }
          }
      }

    return tau;
  }

} // end namespace GRINS
<commit_msg>Use SolidMechanicsBCHandling in ElasticMembrane<commit_after>//-----------------------------------------------------------------------bl-
//--------------------------------------------------------------------------
//
// GRINS - General Reacting Incompressible Navier-Stokes
//
// Copyright (C) 2014 Paul T. Bauman, Roy H. Stogner
// Copyright (C) 2010-2013 The PECOS Development Team
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the Version 2.1 GNU Lesser General
// Public License as published by the Free Software Foundation.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc. 51 Franklin Street, Fifth Floor,
// Boston, MA  02110-1301  USA
//
//-----------------------------------------------------------------------el-

// This class
#include "grins/elastic_membrane.h"

// GRINS
#include "grins_config.h"
#include "grins/assembly_context.h"
#include "grins/solid_mechanics_bc_handling.h"

// libMesh
#include "libmesh/getpot.h"
#include "libmesh/quadrature.h"
#include "libmesh/boundary_info.h"
#include "libmesh/fem_system.h"

namespace GRINS
{
  template<typename ElasticityTensor>
  ElasticMembrane<ElasticityTensor>::ElasticMembrane( const GRINS::PhysicsName& physics_name, const GetPot& input )
    : Physics(physics_name,input),
      _disp_vars(input,physics_name),
      _C(input)
  {
    this->_bc_handler = new SolidMechanicsBCHandling( physics_name, input );

    return;
  }

  template<typename ElasticityTensor>
  ElasticMembrane<ElasticityTensor>::~ElasticMembrane()
  {
    return;
  }

  template<typename ElasticityTensor>
  void ElasticMembrane<ElasticityTensor>::init_variables( libMesh::FEMSystem* system )
  {
    // is_2D = false, is_3D = true
    _disp_vars.init(system,false,true);

    return;
  }

  template<typename ElasticityTensor>
  void ElasticMembrane<ElasticityTensor>::set_time_evolving_vars( libMesh::FEMSystem* system )
  {
    // Tell the system to march temperature forward in time
    system->time_evolving(_disp_vars.u_var());
    system->time_evolving(_disp_vars.v_var());
    system->time_evolving(_disp_vars.w_var());

    return;
  }

  template<typename ElasticityTensor>
  void ElasticMembrane<ElasticityTensor>::init_context( AssemblyContext& context )
  {
    context.get_element_fe(_disp_vars.u_var())->get_JxW();
    context.get_element_fe(_disp_vars.u_var())->get_dphi();

    // Need for constructing metric tensors
    context.get_element_fe(_disp_vars.u_var())->get_dxyzdxi();
    context.get_element_fe(_disp_vars.u_var())->get_dxyzdeta();
    context.get_element_fe(_disp_vars.u_var())->get_dxidx();
    context.get_element_fe(_disp_vars.u_var())->get_dxidy();
    context.get_element_fe(_disp_vars.u_var())->get_dxidz();
    context.get_element_fe(_disp_vars.u_var())->get_detadx();
    context.get_element_fe(_disp_vars.u_var())->get_detady();
    context.get_element_fe(_disp_vars.u_var())->get_detadz();

    return;
  }

  template<typename ElasticityTensor>
  void ElasticMembrane<ElasticityTensor>::element_time_derivative( bool compute_jacobian,
                                                                   AssemblyContext& context,
                                                                   CachedValues& /*cache*/ )
  {
    const unsigned int n_u_dofs = context.get_dof_indices(_disp_vars.u_var()).size();

    const std::vector<libMesh::Real> &JxW =
      context.get_element_fe(_disp_vars.u_var())->get_JxW();

    const std::vector<std::vector<libMesh::RealGradient> >& u_gradphi =
      context.get_element_fe(_disp_vars.u_var())->get_dphi();

    libMesh::DenseSubVector<libMesh::Number> &Fu = context.get_elem_residual(_disp_vars.u_var());
    libMesh::DenseSubVector<libMesh::Number> &Fv = context.get_elem_residual(_disp_vars.v_var());
    libMesh::DenseSubVector<libMesh::Number> &Fw = context.get_elem_residual(_disp_vars.w_var());

    unsigned int n_qpoints = context.get_element_qrule().n_points();

    const std::vector<libMesh::RealGradient>& dxdxi  = context.get_element_fe(_disp_vars.u_var())->get_dxyzdxi();
    const std::vector<libMesh::RealGradient>& dxdeta = context.get_element_fe(_disp_vars.u_var())->get_dxyzdeta();

    const std::vector<libMesh::Real>& dxidx  = context.get_element_fe(_disp_vars.u_var())->get_dxidx();
    const std::vector<libMesh::Real>& dxidy  = context.get_element_fe(_disp_vars.u_var())->get_dxidy();
    const std::vector<libMesh::Real>& dxidz  = context.get_element_fe(_disp_vars.u_var())->get_dxidz();

    const std::vector<libMesh::Real>& detadx  = context.get_element_fe(_disp_vars.u_var())->get_detadx();
    const std::vector<libMesh::Real>& detady  = context.get_element_fe(_disp_vars.u_var())->get_detady();
    const std::vector<libMesh::Real>& detadz  = context.get_element_fe(_disp_vars.u_var())->get_detadz();

    for (unsigned int qp=0; qp != n_qpoints; qp++)
      {
        libMesh::Gradient grad_u = context.interior_gradient(_disp_vars.u_var(), qp);
        libMesh::Gradient grad_v = context.interior_gradient(_disp_vars.v_var(), qp);
        libMesh::Gradient grad_w = context.interior_gradient(_disp_vars.w_var(), qp);

        libMesh::RealGradient grad_x( dxdxi[qp](0), dxdeta[qp](0) );
        libMesh::RealGradient grad_y( dxdxi[qp](1), dxdeta[qp](1) );
        libMesh::RealGradient grad_z( dxdxi[qp](2), dxdeta[qp](2) );

        libMesh::RealGradient dudxi( grad_u(0), grad_v(0), grad_w(0) );
        libMesh::RealGradient dudeta( grad_u(1), grad_v(1), grad_w(1) );

        libMesh::RealGradient dxi( dxidx[qp], dxidy[qp], dxidz[qp] );
        libMesh::RealGradient deta( detadx[qp], detady[qp], detadz[qp] );

        // Covariant metric tensor of reference configuration
        libMesh::TensorValue<libMesh::Real> a_cov( dxdxi[qp]*dxdxi[qp], dxdxi[qp]*dxdeta[qp], 0.0,
                                                   dxdeta[qp]*dxdxi[qp], dxdeta[qp]*dxdeta[qp] );

        // Covariant metric tensor of current configuration
        libMesh::TensorValue<libMesh::Real> A_cov( (dxdxi[qp] + dudxi)*(dxdxi[qp] + dudxi),
                                                   (dxdxi[qp] + dudxi)*(dxdeta[qp] + dudeta), 0.0,
                                                   (dxdeta[qp] + dudeta)*(dxdxi[qp] + dudxi),
                                                   (dxdeta[qp] + dudeta)*(dxdeta[qp] + dudeta) );

        // Contravariant metric tensor of reference configuration
        libMesh::TensorValue<libMesh::Real> a_contra( dxi*dxi, dxi*deta, 0.0,
                                                      deta*dxi, deta*deta );

        // Strain tensor
        libMesh::TensorValue<libMesh::Real> strain = 0.5*(A_cov - a_cov);

        // Compute stress tensor
        libMesh::TensorValue<libMesh::Real> tau = this->compute_stress(a_contra,strain);

        libMesh::Real jac = JxW[qp];

        for (unsigned int i=0; i != n_u_dofs; i++)
	  {
            for( unsigned int alpha = 0; alpha < 2; alpha++ )
              {
                for( unsigned int beta = 0; beta < 2; beta++ )
                  {
                    Fu(i) -= 0.5*tau(alpha,beta)*( (grad_x(beta) + grad_u(beta))*u_gradphi[i][qp](alpha) +
                                                   (grad_x(alpha) + grad_u(alpha))*u_gradphi[i][qp](beta) )*jac;

                    Fv(i) -= 0.5*tau(alpha,beta)*( (grad_y(beta) + grad_v(beta))*u_gradphi[i][qp](alpha) +
                                                   (grad_y(alpha) + grad_v(alpha))*u_gradphi[i][qp](beta) )*jac;

                    Fw(i) -= 0.5*tau(alpha,beta)*( (grad_z(beta) + grad_w(beta))*u_gradphi[i][qp](alpha) +
                                                   (grad_z(alpha) + grad_w(alpha))*u_gradphi[i][qp](beta) )*jac;
                  }
              }
            if( compute_jacobian )
              {
                libmesh_not_implemented();
              }
          }

      }

    return;
  }

  template<typename ElasticityTensor>
  void ElasticMembrane<ElasticityTensor>::side_time_derivative( bool compute_jacobian,
                                                                AssemblyContext& context,
                                                                CachedValues& cache )
  {
    /*
      std::vector<BoundaryID> ids = context.side_boundary_ids();

      for( std::vector<BoundaryID>::const_iterator it = ids.begin();
      it != ids.end(); it++ )
      {
      libmesh_assert (*it != libMesh::BoundaryInfo::invalid_id);

      _bc_handler->apply_neumann_bcs( context, cache, compute_jacobian, *it );
      }
    */

    return;
  }

  template<typename ElasticityTensor>
  void ElasticMembrane<ElasticityTensor>::mass_residual( bool compute_jacobian,
                                                         AssemblyContext& context,
                                                         CachedValues& cache )
  {
    libmesh_not_implemented();
    return;
  }

  template<typename ElasticityTensor>
  libMesh::TensorValue<libMesh::Real> ElasticMembrane<ElasticityTensor>::compute_stress(libMesh::TensorValue<libMesh::Real>& a_contra,
                                                                                libMesh::TensorValue<libMesh::Real>& strain)
  {
    libMesh::TensorValue<libMesh::Real> tau;

    (this->_C).recompute_elasticity(a_contra);

    for( unsigned int alpha = 0; alpha < 2; alpha++ )
      {
        for( unsigned int beta = 0; beta < 2; beta++ )
          {
            for( unsigned int gamma = 0; gamma < 2; gamma++ )
              {
                for( unsigned int delta = 0; delta < 2; delta++ )
                  {
                    tau(alpha,beta) += (this->_C(alpha,beta,gamma,delta))*strain(gamma,delta);
                  }
              }
          }
      }

    return tau;
  }

} // end namespace GRINS
<|endoftext|>


<commit_before>// Copyright 2015 Las Venturas Playground. All rights reserved.
// Use of this source code is governed by the MIT license, a copy of which can
// be found in the LICENSE file.

#include "bindings/runtime.h"

#include <algorithm>
#include <fstream>
#include <sstream>
#include <streambuf>
#include <string.h>
#include <unordered_map>

#include <include/libplatform/libplatform.h>

#include "base/logging.h"
#include "base/time.h"
#include "bindings/allocator.h"
#include "bindings/exception_handler.h"
#include "bindings/frame_observer.h"
#include "bindings/global_scope.h"
#include "bindings/script_prologue.h"
#include "bindings/timer_queue.h"
#include "bindings/utilities.h"

using namespace v8;

namespace bindings {

namespace {

// Map of v8 Isolates to the associated Runtime instances (weak references).
std::unordered_map<v8::Isolate*, std::weak_ptr<Runtime>> g_runtime_instances_;

// String of the v8 flags that should apply to this virtual machine. See flag-definitions.h in
// the v8 source code for a list of all supported command line flags.
const char kRuntimeFlags[] =
    "--expose_gc "
    "--use_strict "
    "--harmony "
    "--harmony_do_expressions "
    "--harmony_function_sent "
    "--harmony_string_padding";

// Returns whether |character| represents a line break.
bool IsLineBreak(char character) {
  return character == '\n' || character == '\r';
}

// Returns a string with all line breaks removed from |line|.
std::string RemoveLineBreaks(std::string line) {
  line.erase(std::remove_if(line.begin(), line.end(), IsLineBreak), line.end());
  return line;
}

// Callback for the v8 message handler. Forward the call to the exception handler.
void MessageCallback(v8::Local<v8::Message> message, v8::Local<v8::Value> error) {
  std::shared_ptr<Runtime> runtime = Runtime::FromIsolate(v8::Isolate::GetCurrent());
  if (runtime)
    runtime->GetExceptionHandler()->OnMessage(
        message, error, ExceptionHandler::MessageSource::kScript);
}

// Callback for the v8 fatal error handler. Forward the call to the exception handler.
void FatalErrorCallback(const char* location, const char* message) {
  std::shared_ptr<Runtime> runtime = Runtime::FromIsolate(v8::Isolate::GetCurrent());
  if (runtime)
    runtime->GetExceptionHandler()->OnFatalError(location, message);
}

// Callback for uncaught promise rejection events. Output the exception message to the console
// after all, so that developers can pick up on the error and deal with it.
void PromiseRejectCallback(PromiseRejectMessage message) {
  // TODO(Russell): Should we ignore when message.GetEvent()==kPromiseHandlerAddedAfterReject?

  std::shared_ptr<Runtime> runtime = Runtime::FromIsolate(v8::Isolate::GetCurrent());
  if (!runtime)
    return;

  v8::Local<v8::Value> value = message.GetValue();
  if (value.IsEmpty() || !value->IsNativeError())
    return;

  v8::Local<v8::Message> error_message = v8::Exception::CreateMessage(value);
  if (error_message.IsEmpty())
    return;

  runtime->GetExceptionHandler()->OnMessage(
      error_message, value, ExceptionHandler::MessageSource::kRejectedPromise);
}

}  // namespace

// static
std::shared_ptr<Runtime> Runtime::FromIsolate(v8::Isolate* isolate) {
  const auto instance = g_runtime_instances_.find(isolate);
  if (instance == g_runtime_instances_.end())
    return nullptr;

  CHECK(!instance->second.expired());
  return instance->second.lock();
}

// static
std::shared_ptr<Runtime> Runtime::Create(Delegate* runtime_delegate,
                                         plugin::PluginController* plugin_controller) {
  auto instance = std::shared_ptr<Runtime>(
      new Runtime(runtime_delegate, plugin_controller));
  CHECK(instance->isolate());

  g_runtime_instances_[instance->isolate()] = instance;
  return instance;
}

Runtime::Runtime(Delegate* runtime_delegate,
                 plugin::PluginController* plugin_controller)
    : global_scope_(new GlobalScope(plugin_controller)),
      runtime_delegate_(runtime_delegate),
      frame_counter_start_(base::monotonicallyIncreasingTime()),
      frame_counter_(0) {
  V8::InitializeICU();

  platform_.reset(platform::CreateDefaultPlatform());
  V8::InitializePlatform(platform_.get());

  V8::SetFlagsFromString(kRuntimeFlags, sizeof(kRuntimeFlags));
  V8::Initialize();

  allocator_.reset(new SimpleArrayBufferAllocator());

  Isolate::CreateParams create_params;
  create_params.array_buffer_allocator = allocator_.get();

  isolate_ = Isolate::New(create_params);
  isolate_scope_.reset(new Isolate::Scope(isolate_));

  exception_handler_.reset(new ExceptionHandler(runtime_delegate_));
  isolate_->SetCaptureStackTraceForUncaughtExceptions(true, 15);
  isolate_->AddMessageListener(MessageCallback);
  isolate_->SetFatalErrorHandler(FatalErrorCallback);
  isolate_->SetPromiseRejectCallback(PromiseRejectCallback);

  timer_queue_.reset(new TimerQueue(this));

  // TODO: This should be set by some sort of Configuration object.
  script_directory_ = base::FilePath("javascript");
}

Runtime::~Runtime() {
  // TODO: Multiple instances would now break.
  //g_runtime_instances_.erase(isolate_);

  global_scope_.reset();

  isolate_scope_.reset();
  isolate_->Dispose();

  V8::Dispose();
  V8::ShutdownPlatform();
}

void Runtime::Initialize() {
  HandleScope handle_scope(isolate_);

  Local<ObjectTemplate> global = ObjectTemplate::New(isolate_);

  // The global scope is being applied in two steps. First we install all the prototypes (which
  // essentially are functions that may be instantiated), then we install objects, which may
  // include instantiations of previously installed prototypes (e.g. the console global).
  global_scope_->InstallPrototypes(global);

  Local<Context> context = Context::New(isolate_, nullptr, global);

  Context::Scope context_scope(context);
  global_scope_->InstallObjects(context->Global());

  context_.Reset(isolate_, context);

  // Make sure that the global script prologue is loaded in the virtual machine.
  ScriptSource global_prologue(kScriptPrologue);
  if (!Execute(global_prologue, nullptr /** result **/))
    LOG(ERROR) << "Unable to install the global script prologue in the virtual machine.";

  isolate_->SetMicrotasksPolicy(v8::MicrotasksPolicy::kExplicit);
}

void Runtime::GetAndResetFrameCounter(double* duration, double* average_fps) {
  DCHECK(duration && average_fps);

  double current = base::monotonicallyIncreasingTime();

  *duration = current - frame_counter_start_;
  *average_fps = frame_counter_ / (*duration / 1000);

  frame_counter_start_ = current;
  frame_counter_ = 0;
}

void Runtime::OnFrame() {
  ++frame_counter_;

  for (FrameObserver* observer : frame_observers_)
    observer->OnFrame();

  timer_queue_->Run();

  isolate_->RunMicrotasks();
}

void Runtime::AddFrameObserver(FrameObserver* observer) {
  frame_observers_.insert(observer);
}

void Runtime::RemoveFrameObserver(FrameObserver* observer) {
  frame_observers_.erase(observer);
}

bool Runtime::Execute(const ScriptSource& script_source,
                      v8::Local<v8::Value>* result) {
  EscapableHandleScope handle_scope(isolate());
  Context::Scope context_scope(context());

  MaybeLocal<String> script_string =
      String::NewFromUtf8(isolate_, script_source.source.c_str(), NewStringType::kNormal);
  MaybeLocal<String> filename_string =
      String::NewFromUtf8(isolate_, script_source.filename.c_str(), NewStringType::kNormal);

  if (script_string.IsEmpty() || filename_string.IsEmpty())
    return false;

  ScriptOrigin origin(filename_string.ToLocalChecked());
  Local<String> source = script_string.ToLocalChecked();

  TryCatch try_catch;

  MaybeLocal<Script> script = Script::Compile(context(), source, &origin);
  if (script.IsEmpty()) {
    DisplayException(try_catch);
    return false;
  }

  MaybeLocal<Value> script_result = script.ToLocalChecked()->Run(context());
  if (try_catch.HasCaught()) {
    DisplayException(try_catch);
    return false;
  }

  if (result)
    *result = handle_scope.Escape(script_result.ToLocalChecked());

  return true;
}

bool Runtime::ExecuteFile(const base::FilePath& file,
                          ExecutionType execution_type,
                          v8::Local<v8::Value>* result) {
  const base::FilePath script_path = script_directory_.Append(file);

  std::ifstream handle(script_path.value().c_str());
  if (!handle.is_open() || handle.fail())
    return false;

  ScriptSource script;
  script.filename = file.value();

  std::stringstream source_stream;

  // Prepend and append the module prologue and epilogue if the execution type is set to module
  // style. Otherwise just pass through the file's source to |source_stream|.
  if (execution_type == EXECUTION_TYPE_MODULE)
    source_stream << RemoveLineBreaks(kModulePrologue);

  std::copy(std::istreambuf_iterator<char>(handle),
            std::istreambuf_iterator<char>(),
            std::ostreambuf_iterator<char>(source_stream));

  if (execution_type == EXECUTION_TYPE_MODULE)
    source_stream << RemoveLineBreaks(kModuleEpilogue);

  script.source = source_stream.str();

  // Now execute |script| normally on the runtime.
  return Execute(script, result);
}

void Runtime::DisplayException(const TryCatch& try_catch) {
  if (!runtime_delegate_)
    return;

  // TODO: Exceptions ideally should have stack traces attached to them.

  Local<Message> message = try_catch.Message();

  // Extract the exception message from the try-catch block.
  String::Utf8Value exception(try_catch.Exception());
  std::string exception_string(*exception, exception.length());

  // Extract the filename of the script from the try-catch block.
  String::Utf8Value resource_name(message->GetScriptOrigin().ResourceName());
  std::string filename(*resource_name, resource_name.length());

  size_t line_number = message->GetLineNumber();

  runtime_delegate_->OnScriptError(filename, line_number, exception_string);
}

}  // namespace bindings
<commit_msg>Guard against empty v8::Message objects<commit_after>// Copyright 2015 Las Venturas Playground. All rights reserved.
// Use of this source code is governed by the MIT license, a copy of which can
// be found in the LICENSE file.

#include "bindings/runtime.h"

#include <algorithm>
#include <fstream>
#include <sstream>
#include <streambuf>
#include <string.h>
#include <unordered_map>

#include <include/libplatform/libplatform.h>

#include "base/logging.h"
#include "base/time.h"
#include "bindings/allocator.h"
#include "bindings/exception_handler.h"
#include "bindings/frame_observer.h"
#include "bindings/global_scope.h"
#include "bindings/script_prologue.h"
#include "bindings/timer_queue.h"
#include "bindings/utilities.h"

using namespace v8;

namespace bindings {

namespace {

// Map of v8 Isolates to the associated Runtime instances (weak references).
std::unordered_map<v8::Isolate*, std::weak_ptr<Runtime>> g_runtime_instances_;

// String of the v8 flags that should apply to this virtual machine. See flag-definitions.h in
// the v8 source code for a list of all supported command line flags.
const char kRuntimeFlags[] =
    "--expose_gc "
    "--use_strict "
    "--harmony "
    "--harmony_do_expressions "
    "--harmony_function_sent "
    "--harmony_string_padding";

// Returns whether |character| represents a line break.
bool IsLineBreak(char character) {
  return character == '\n' || character == '\r';
}

// Returns a string with all line breaks removed from |line|.
std::string RemoveLineBreaks(std::string line) {
  line.erase(std::remove_if(line.begin(), line.end(), IsLineBreak), line.end());
  return line;
}

// Callback for the v8 message handler. Forward the call to the exception handler.
void MessageCallback(v8::Local<v8::Message> message, v8::Local<v8::Value> error) {
  std::shared_ptr<Runtime> runtime = Runtime::FromIsolate(v8::Isolate::GetCurrent());
  if (runtime)
    runtime->GetExceptionHandler()->OnMessage(
        message, error, ExceptionHandler::MessageSource::kScript);
}

// Callback for the v8 fatal error handler. Forward the call to the exception handler.
void FatalErrorCallback(const char* location, const char* message) {
  std::shared_ptr<Runtime> runtime = Runtime::FromIsolate(v8::Isolate::GetCurrent());
  if (runtime)
    runtime->GetExceptionHandler()->OnFatalError(location, message);
}

// Callback for uncaught promise rejection events. Output the exception message to the console
// after all, so that developers can pick up on the error and deal with it.
void PromiseRejectCallback(PromiseRejectMessage message) {
  // TODO(Russell): Should we ignore when message.GetEvent()==kPromiseHandlerAddedAfterReject?

  std::shared_ptr<Runtime> runtime = Runtime::FromIsolate(v8::Isolate::GetCurrent());
  if (!runtime)
    return;

  v8::Local<v8::Value> value = message.GetValue();
  if (value.IsEmpty() || !value->IsNativeError())
    return;

  v8::Local<v8::Message> error_message = v8::Exception::CreateMessage(value);
  if (error_message.IsEmpty())
    return;

  runtime->GetExceptionHandler()->OnMessage(
      error_message, value, ExceptionHandler::MessageSource::kRejectedPromise);
}

}  // namespace

// static
std::shared_ptr<Runtime> Runtime::FromIsolate(v8::Isolate* isolate) {
  const auto instance = g_runtime_instances_.find(isolate);
  if (instance == g_runtime_instances_.end())
    return nullptr;

  CHECK(!instance->second.expired());
  return instance->second.lock();
}

// static
std::shared_ptr<Runtime> Runtime::Create(Delegate* runtime_delegate,
                                         plugin::PluginController* plugin_controller) {
  auto instance = std::shared_ptr<Runtime>(
      new Runtime(runtime_delegate, plugin_controller));
  CHECK(instance->isolate());

  g_runtime_instances_[instance->isolate()] = instance;
  return instance;
}

Runtime::Runtime(Delegate* runtime_delegate,
                 plugin::PluginController* plugin_controller)
    : global_scope_(new GlobalScope(plugin_controller)),
      runtime_delegate_(runtime_delegate),
      frame_counter_start_(base::monotonicallyIncreasingTime()),
      frame_counter_(0) {
  V8::InitializeICU();

  platform_.reset(platform::CreateDefaultPlatform());
  V8::InitializePlatform(platform_.get());

  V8::SetFlagsFromString(kRuntimeFlags, sizeof(kRuntimeFlags));
  V8::Initialize();

  allocator_.reset(new SimpleArrayBufferAllocator());

  Isolate::CreateParams create_params;
  create_params.array_buffer_allocator = allocator_.get();

  isolate_ = Isolate::New(create_params);
  isolate_scope_.reset(new Isolate::Scope(isolate_));

  exception_handler_.reset(new ExceptionHandler(runtime_delegate_));
  isolate_->SetCaptureStackTraceForUncaughtExceptions(true, 15);
  isolate_->AddMessageListener(MessageCallback);
  isolate_->SetFatalErrorHandler(FatalErrorCallback);
  isolate_->SetPromiseRejectCallback(PromiseRejectCallback);

  timer_queue_.reset(new TimerQueue(this));

  // TODO: This should be set by some sort of Configuration object.
  script_directory_ = base::FilePath("javascript");
}

Runtime::~Runtime() {
  // TODO: Multiple instances would now break.
  //g_runtime_instances_.erase(isolate_);

  global_scope_.reset();

  isolate_scope_.reset();
  isolate_->Dispose();

  V8::Dispose();
  V8::ShutdownPlatform();
}

void Runtime::Initialize() {
  HandleScope handle_scope(isolate_);

  Local<ObjectTemplate> global = ObjectTemplate::New(isolate_);

  // The global scope is being applied in two steps. First we install all the prototypes (which
  // essentially are functions that may be instantiated), then we install objects, which may
  // include instantiations of previously installed prototypes (e.g. the console global).
  global_scope_->InstallPrototypes(global);

  Local<Context> context = Context::New(isolate_, nullptr, global);

  Context::Scope context_scope(context);
  global_scope_->InstallObjects(context->Global());

  context_.Reset(isolate_, context);

  // Make sure that the global script prologue is loaded in the virtual machine.
  ScriptSource global_prologue(kScriptPrologue);
  if (!Execute(global_prologue, nullptr /** result **/))
    LOG(ERROR) << "Unable to install the global script prologue in the virtual machine.";

  isolate_->SetMicrotasksPolicy(v8::MicrotasksPolicy::kExplicit);
}

void Runtime::GetAndResetFrameCounter(double* duration, double* average_fps) {
  DCHECK(duration && average_fps);

  double current = base::monotonicallyIncreasingTime();

  *duration = current - frame_counter_start_;
  *average_fps = frame_counter_ / (*duration / 1000);

  frame_counter_start_ = current;
  frame_counter_ = 0;
}

void Runtime::OnFrame() {
  ++frame_counter_;

  for (FrameObserver* observer : frame_observers_)
    observer->OnFrame();

  timer_queue_->Run();

  isolate_->RunMicrotasks();
}

void Runtime::AddFrameObserver(FrameObserver* observer) {
  frame_observers_.insert(observer);
}

void Runtime::RemoveFrameObserver(FrameObserver* observer) {
  frame_observers_.erase(observer);
}

bool Runtime::Execute(const ScriptSource& script_source,
                      v8::Local<v8::Value>* result) {
  EscapableHandleScope handle_scope(isolate());
  Context::Scope context_scope(context());

  MaybeLocal<String> script_string =
      String::NewFromUtf8(isolate_, script_source.source.c_str(), NewStringType::kNormal);
  MaybeLocal<String> filename_string =
      String::NewFromUtf8(isolate_, script_source.filename.c_str(), NewStringType::kNormal);

  if (script_string.IsEmpty() || filename_string.IsEmpty())
    return false;

  ScriptOrigin origin(filename_string.ToLocalChecked());
  Local<String> source = script_string.ToLocalChecked();

  TryCatch try_catch;

  MaybeLocal<Script> script = Script::Compile(context(), source, &origin);
  if (script.IsEmpty()) {
    DisplayException(try_catch);
    return false;
  }

  MaybeLocal<Value> script_result = script.ToLocalChecked()->Run(context());
  if (try_catch.HasCaught()) {
    DisplayException(try_catch);
    return false;
  }

  if (result)
    *result = handle_scope.Escape(script_result.ToLocalChecked());

  return true;
}

bool Runtime::ExecuteFile(const base::FilePath& file,
                          ExecutionType execution_type,
                          v8::Local<v8::Value>* result) {
  const base::FilePath script_path = script_directory_.Append(file);

  std::ifstream handle(script_path.value().c_str());
  if (!handle.is_open() || handle.fail())
    return false;

  ScriptSource script;
  script.filename = file.value();

  std::stringstream source_stream;

  // Prepend and append the module prologue and epilogue if the execution type is set to module
  // style. Otherwise just pass through the file's source to |source_stream|.
  if (execution_type == EXECUTION_TYPE_MODULE)
    source_stream << RemoveLineBreaks(kModulePrologue);

  std::copy(std::istreambuf_iterator<char>(handle),
            std::istreambuf_iterator<char>(),
            std::ostreambuf_iterator<char>(source_stream));

  if (execution_type == EXECUTION_TYPE_MODULE)
    source_stream << RemoveLineBreaks(kModuleEpilogue);

  script.source = source_stream.str();

  // Now execute |script| normally on the runtime.
  return Execute(script, result);
}

void Runtime::DisplayException(const TryCatch& try_catch) {
  if (!runtime_delegate_)
    return;

  // TODO: Exceptions ideally should have stack traces attached to them.

  Local<Message> message = try_catch.Message();

  // Extract the exception message from the try-catch block.
  String::Utf8Value exception(try_catch.Exception());
  std::string exception_string(*exception, exception.length());

  std::string filename = "unknown";
  size_t line_number = 0;

  if (message.IsEmpty()) {
    LOG(WARNING) << "[v8] Empty message received in " << __FUNCTION__;
  } else {
    String::Utf8Value resource_name(message->GetScriptOrigin().ResourceName());
    filename.assign(*resource_name, resource_name.length());

    line_number = message->GetLineNumber();
  }

  runtime_delegate_->OnScriptError(filename, line_number, exception_string);
}

}  // namespace bindings
<|endoftext|>


<commit_before>#include <iostream>
#include <fstream>
#include <string>
#include <random>

#include "slitherlink/sl_dictionary.h"
#include "slitherlink/sl_generator.h"
#include "slitherlink/sl_generator_option.h"
#include "slitherlink/sl_clue_placement.h"
#include "slitherlink/sl_problem.h"

namespace
{
void ShowUsage(int argc, char** argv)
{
	std::cerr << "Usage: " << argv[0] << " [options] [file]" << std::endl;
	std::cerr << "Options:\n\
  -o <file>     Place the output into <file>\n\
  -a            Generate the clue placement automatically\n\
  -h <height>   Set the height of the problem <height>\n\
  -w <width>    Set the width of the problem <width>\n\
  -c <num>      Set the minimum number of the clues <num>\n\
  -C <num>      Set the maximum number of the clues <num>\n\
\n\
Options -h, -w, -c and -C are valid only if -a is specified.\n\
If -a is not specified, the input file should be specified for the clue placement." << std::endl;
}
bool GenerateWithCluePlacement(
	penciloid::slitherlink::CluePlacement &placement,
	penciloid::slitherlink::GeneratorOption &opt,
	std::mt19937 *rnd,
	penciloid::slitherlink::Problem *problem,
	int n_trial = -1)
{
	if (n_trial < 0) {
		while (!penciloid::slitherlink::GenerateByLocalSearch(placement, opt, rnd, problem));
		return true;
	}
	while (n_trial) {
		if (penciloid::slitherlink::GenerateByLocalSearch(placement, opt, rnd, problem)) {
			return true;
		}
		--n_trial;
	}
	return false;
}
void GenerateAuto(
	int height,
	int width,
	int n_clue_lo,
	int n_clue_hi,
	int symmetry,
	penciloid::slitherlink::GeneratorOption &opt,
	std::mt19937 *rnd,
	penciloid::slitherlink::Problem *problem)
{
	using namespace penciloid;
	using namespace slitherlink;
	for (;;) {
		int n_clues = std::uniform_int_distribution<int>(n_clue_lo, n_clue_hi)(*rnd);
		CluePlacement placement = GenerateCluePlacement(Y(height), X(width), n_clues, symmetry, rnd);
		if (GenerateWithCluePlacement(placement, opt, rnd, problem, 3)) {
			break;
		}
	}
}
}

int main(int argc, char** argv)
{
	if (argc < 2) {
		ShowUsage(argc, argv);
		return 0;
	}

	std::string in_filename = "", out_filename = "";
	int height = -1, width = -1, n_clue_lo = -1, n_clue_hi = -1;
	bool gen_clue_auto = false;

	// parse options
	int arg_idx = 1;
	for (; arg_idx < argc; ++arg_idx) {
		if (argv[arg_idx][0] != '-') {
			// option ended
			break;
		}
		char opt = argv[arg_idx][1];
		switch (opt)
		{
		case 'o':
			// specify the output file
			out_filename = argv[arg_idx + 1];
			++arg_idx;
			break;
		case 'a':
			// generate clue placement automatically
			gen_clue_auto = true;
			break;
		case 'h':
			// specify the height of the generated problem (enabled only if '-a' is specified)
			height = atoi(argv[arg_idx + 1]);
			++arg_idx;
			break;
		case 'w':
			// specify the width of the generated problem (enabled only if '-a' is specified)
			width = atoi(argv[arg_idx + 1]);
			++arg_idx;
			break;
		case 'c':
			// specify the minimum number of the clues
			n_clue_lo = atoi(argv[arg_idx + 1]);
			++arg_idx;
			break;
		case 'C':
			// specify the maximum number of the clues
			n_clue_hi = atoi(argv[arg_idx + 1]);
			++arg_idx;
			break;
		default:
			std::cerr << "error: unrecognized option '" << argv[arg_idx] << "'" << std::endl;
			return 0;
		}
	}
	if (gen_clue_auto) {
		if (out_filename.empty()) {
			std::cerr << "error: -o must be specified if -a is specified." << std::endl;
			return 0;
		}
	}
	if (!gen_clue_auto) {
		in_filename = argv[arg_idx];
	}

	using namespace penciloid;
	using namespace slitherlink;

	GeneratorOption opt;
	Dictionary dic;
	dic.CreateDefault();
	opt.field_dictionary = &dic;

	Problem problem;
	std::random_device dev;
	std::mt19937 rnd(dev());

	if (!gen_clue_auto) {
		std::ifstream ifs(in_filename);
		ifs >> height >> width;

		CluePlacement clue_placement{ Y(height), X(width) };
		for (Y y(0); y < height; ++y) {
			for (X x(0); x < width; ++x) {
				std::string token;
				ifs >> token;

				if (token[0] >= '0' && token[0] <= '3') {
					clue_placement.SetClue(CellPosition(y, x), Clue(static_cast<int>(token[0] - '0')));
				} else if (token[0] == '5') {
					clue_placement.SetClue(CellPosition(y, x), kSomeClue);
				}
			}
		}

		GenerateWithCluePlacement(clue_placement, opt, &rnd, &problem);
	} else {
		if (n_clue_lo == -1 || n_clue_hi == -1) {
			n_clue_lo = static_cast<int>(height * width * 0.3);
			n_clue_hi = static_cast<int>(height * width * 0.4);
		}
		GenerateAuto(height, width, n_clue_lo, n_clue_hi, penciloid::slitherlink::kSymmetryDyad, opt, &rnd, &problem);
	}

	if (out_filename.empty()) {
		out_filename = in_filename + ".generated.txt";
	}
	std::ofstream ofs(out_filename);
	ofs << height << std::endl;
	ofs << width << std::endl;
	for (Y y(0); y < height; ++y) {
		for (X x(0); x < width; ++x) {
			Clue c = problem.GetClue(CellPosition(y, x));
			if (c == kNoClue) ofs << ". ";
			else ofs << static_cast<int>(c) << " ";
		}
		ofs << std::endl;
	}
	return 0;
}
<commit_msg>frontend_slitherlink_generator: add error detection<commit_after>#include <iostream>
#include <fstream>
#include <string>
#include <random>
#include <sstream>

#include "slitherlink/sl_dictionary.h"
#include "slitherlink/sl_generator.h"
#include "slitherlink/sl_generator_option.h"
#include "slitherlink/sl_clue_placement.h"
#include "slitherlink/sl_problem.h"

namespace
{
void ShowUsage(int argc, char** argv)
{
	std::cerr << "Usage: " << argv[0] << " [options] [file]" << std::endl;
	std::cerr << "Options:\n\
  -o <file>     Place the output into <file>\n\
  -a            Generate the clue placement automatically\n\
  -h <height>   Set the height of the problem <height>\n\
  -w <width>    Set the width of the problem <width>\n\
  -c <num>      Set the minimum number of the clues <num>\n\
  -C <num>      Set the maximum number of the clues <num>\n\
\n\
Options -h, -w, -c and -C are valid only if -a is specified.\n\
If -a is not specified, the input file should be specified for the clue placement." << std::endl;
}
bool GenerateWithCluePlacement(
	penciloid::slitherlink::CluePlacement &placement,
	penciloid::slitherlink::GeneratorOption &opt,
	std::mt19937 *rnd,
	penciloid::slitherlink::Problem *problem,
	int n_trial = -1)
{
	if (n_trial < 0) {
		while (!penciloid::slitherlink::GenerateByLocalSearch(placement, opt, rnd, problem));
		return true;
	}
	while (n_trial) {
		if (penciloid::slitherlink::GenerateByLocalSearch(placement, opt, rnd, problem)) {
			return true;
		}
		--n_trial;
	}
	return false;
}
void GenerateAuto(
	int height,
	int width,
	int n_clue_lo,
	int n_clue_hi,
	int symmetry,
	penciloid::slitherlink::GeneratorOption &opt,
	std::mt19937 *rnd,
	penciloid::slitherlink::Problem *problem)
{
	using namespace penciloid;
	using namespace slitherlink;
	for (;;) {
		int n_clues = std::uniform_int_distribution<int>(n_clue_lo, n_clue_hi)(*rnd);
		CluePlacement placement = GenerateCluePlacement(Y(height), X(width), n_clues, symmetry, rnd);
		if (GenerateWithCluePlacement(placement, opt, rnd, problem, 3)) {
			break;
		}
	}
}
}

int main(int argc, char** argv)
{
	if (argc < 2) {
		ShowUsage(argc, argv);
		return 0;
	}

	std::string in_filename = "", out_filename = "";
	int height = -1, width = -1, n_clue_lo = -1, n_clue_hi = -1;
	bool gen_clue_auto = false;

	// parse options
	int arg_idx = 1;
	for (; arg_idx < argc; ++arg_idx) {
		if (argv[arg_idx][0] != '-') {
			// option ended
			break;
		}
		bool is_next_int = false;
		int val_next_int;
		if (arg_idx + 1 < argc) {
			std::istringstream iss(argv[arg_idx + 1]);
			iss >> val_next_int;
			if (!iss.fail()) is_next_int = true;
		}

		char opt = argv[arg_idx][1];
		switch (opt)
		{
		case 'o':
			// specify the output file
			if (arg_idx + 1 >= argc) {
				std::cerr << "error: missing value after -o" << std::endl;
				return 0;
			}
			out_filename = argv[arg_idx + 1];
			++arg_idx;
			break;
		case 'a':
			// generate clue placement automatically
			gen_clue_auto = true;
			break;
		case 'h':
			// specify the height of the generated problem (enabled only if '-a' is specified)
			if (!is_next_int) {
				std::cerr << "error: missing integer value after -h" << std::endl;
				return 0;
			}
			height = val_next_int;
			++arg_idx;
			break;
		case 'w':
			// specify the width of the generated problem (enabled only if '-a' is specified)
			if (!is_next_int) {
				std::cerr << "error: missing integer value after -w" << std::endl;
				return 0;
			}
			width = val_next_int;
			++arg_idx;
			break;
		case 'c':
			// specify the minimum number of the clues
			if (!is_next_int) {
				std::cerr << "error: missing integer value after -c" << std::endl;
				return 0;
			}
			n_clue_lo = val_next_int;
			++arg_idx;
			break;
		case 'C':
			// specify the maximum number of the clues
			if (!is_next_int) {
				std::cerr << "error: missing integer value after -C" << std::endl;
				return 0;
			}
			n_clue_hi = val_next_int;
			++arg_idx;
			break;
		default:
			std::cerr << "error: unrecognized option '" << argv[arg_idx] << "'" << std::endl;
			return 0;
		}
	}
	if (gen_clue_auto) {
		if (out_filename.empty()) {
			std::cerr << "error: -o must be specified if -a is specified." << std::endl;
			return 0;
		}
	}
	if (!gen_clue_auto) {
		in_filename = argv[arg_idx];
	}

	using namespace penciloid;
	using namespace slitherlink;

	GeneratorOption opt;
	Dictionary dic;
	dic.CreateDefault();
	opt.field_dictionary = &dic;

	Problem problem;
	std::random_device dev;
	std::mt19937 rnd(dev());

	if (!gen_clue_auto) {
		std::ifstream ifs(in_filename);
		if (ifs.fail()) {
			std::cerr << "error: couldn't open file '" << in_filename << "'" << std::endl;
			return 0;
		}
		ifs >> height >> width;
		if (ifs.fail() || height <= 0 || width <= 0) {
			std::cerr << "error: invalid input format" << std::endl;
			return 0;
		}
		CluePlacement clue_placement{ Y(height), X(width) };
		for (Y y(0); y < height; ++y) {
			for (X x(0); x < width; ++x) {
				std::string token;
				ifs >> token;
				if (ifs.fail()) {
					std::cerr << "error: invalid input format" << std::endl;
					return 0;
				}

				if (token[0] >= '0' && token[0] <= '3') {
					clue_placement.SetClue(CellPosition(y, x), Clue(static_cast<int>(token[0] - '0')));
				} else if (token[0] == '5') {
					clue_placement.SetClue(CellPosition(y, x), kSomeClue);
				} else {
					std::cerr << "error: invalid input format" << std::endl;
					return 0;
				}
			}
		}

		GenerateWithCluePlacement(clue_placement, opt, &rnd, &problem);
	} else {
		if (n_clue_lo == -1 || n_clue_hi == -1) {
			n_clue_lo = static_cast<int>(height * width * 0.3);
			n_clue_hi = static_cast<int>(height * width * 0.4);
		}
		GenerateAuto(height, width, n_clue_lo, n_clue_hi, penciloid::slitherlink::kSymmetryDyad, opt, &rnd, &problem);
	}

	if (out_filename.empty()) {
		out_filename = in_filename + ".generated.txt";
	}
	std::ofstream ofs(out_filename);
	if (!ofs.good()) {
		std::cerr << "error: couldn't open file '" << in_filename << "'" << std::endl;
		return 0;
	}
	ofs << height << std::endl;
	ofs << width << std::endl;
	for (Y y(0); y < height; ++y) {
		for (X x(0); x < width; ++x) {
			Clue c = problem.GetClue(CellPosition(y, x));
			if (c == kNoClue) ofs << ". ";
			else ofs << static_cast<int>(c) << " ";
		}
		ofs << std::endl;
	}
	return 0;
}
<|endoftext|>


<commit_before>// InfoDlg.cpp : implementation file
//

#include "stdafx.h"
#include "MGen.h"
#include "InfoDlg.h"
#include "afxdialogex.h"
#include "MainFrm.h"
#include "GLibrary/GMidi.h"
#include "MGenView.h"

#ifdef _DEBUG
#define new DEBUG_NEW
#endif

// CInfoDlg dialog

IMPLEMENT_DYNAMIC(CInfoDlg, CDialog)

CInfoDlg::CInfoDlg(CWnd* pParent /*=NULL*/)
	: CDialog(IDD_DIALOG_INFO, pParent)
{

}

CInfoDlg::~CInfoDlg()
{
}

void CInfoDlg::DoDataExchange(CDataExchange* pDX)
{
	CDialog::DoDataExchange(pDX);
	DDX_Control(pDX, IDC_RICHEDIT21, m_info);
}

BEGIN_MESSAGE_MAP(CInfoDlg, CDialog)
END_MESSAGE_MAP()

// CInfoDlg message handlers

BOOL CInfoDlg::OnInitDialog()
{
	CDialog::OnInitDialog();

	CMainFrame *mf = (CMainFrame *)AfxGetMainWnd();
	CGMidi *pGen = mf->pGen;
	if (pGen != 0) {
		if (!pGen->mutex_output.try_lock_for(chrono::milliseconds(1000))) {
			mf->WriteLog(5, "InfoDlg mutex timed out: showing nothing");
			return TRUE;
		}
		int ms = ((CMGenView*)(mf->GetActiveView()))->mouse_step;
		int mv = ((CMGenView*)(mf->GetActiveView()))->mouse_voice;
		// Note start and end
		int i = ms - pGen->coff[ms][mv];
		int ei = ms + pGen->noff[ms][mv] - 1;
		CString st, st2;

		st.Format("Step: %d (measure %d)", ms, ms / 8);
		SetWindowText(st);
		//m_info.AddText(st, RGB(0, 0, 0), CFE_BOLD);
		st.Format("Tempo: %.1f bpm (randomized from %.1f bpm)\nStep start time: %.3f s (%.2f ms long), end time %.3f s\n",
			pGen->tempo[ms], pGen->tempo_src[ms], pGen->stime[ms] / pGen->m_pspeed / 10,
			(pGen->etime[ms] - pGen->stime[ms]) * 100 / pGen->m_pspeed, pGen->etime[ms] / pGen->m_pspeed / 10);
		m_info.AddText(st, RGB(0, 0, 0), 0);
		m_info.AddText("\n", RGB(170, 0, 0), 0);

		st.Format("Voice: %d (%s, channel %d, type %d)\n", mv,
			pGen->InstGName[pGen->instr[mv]] + "/" + pGen->InstCName[pGen->instr[mv]],
			pGen->instr_channel[pGen->instr[mv]], pGen->instr_type[pGen->instr[mv]]);
		m_info.AddText(st, RGB(0, 0, 0), CFE_BOLD);
		st.Format("Instrument library: %s\n", pGen->instr_lib[pGen->instr[mv]]);
		m_info.AddText(st, RGB(0, 0, 0), 0);
		st.Format("Voice show transpose: %d semitones\n", pGen->show_transpose[mv]);
		m_info.AddText(st, RGB(0, 0, 0), 0);
		if (pGen->midifile_loaded) {
			st.Format("From MIDI file: track %d \"%s\" local-voice %d, channel %d, delta %d ms (%.0f%% croche)\n", pGen->track_id[mv], pGen->track_name[mv], pGen->track_vid[mv], pGen->midi_ch[ms][mv], pGen->midi_delta[ms][mv], (float)(pGen->midi_delta[ms][mv]) / 300.0*(float)(pGen->tempo[ms]));
			m_info.AddText(st, RGB(0, 0, 200), 0);
		}
		m_info.AddText("\n", RGB(0, 0, 0), 0);

		st.Format("Note: %s (midi %d)\n", CGLib::GetNoteName(pGen->note[ms][mv]), pGen->note[ms][mv]);
		m_info.AddText(st, RGB(0, 0, 0), CFE_BOLD);
		st.Format("Key: %s%s\n", NoteName[pGen->tonic[i][mv]], pGen->minor[i][mv]?"m":"");
		m_info.AddText(st, RGB(0, 0, 0), 0);
		st.Format("Note length: %d steps\n", pGen->len[ms][mv]);
		m_info.AddText(st, RGB(0, 0, 0), 0);
		st.Format("Note velocity: %d\n", pGen->vel[i][mv]);
		m_info.AddText(st, RGB(0, 0, 0), 0);
		st.Format("Lyrics from MIDI file: %s\n", pGen->lyrics[i][mv]);
		m_info.AddText(st, RGB(0, 0, 0), 0);

		st.Format("Playback note start delta: %.3f s (with delta %.3f s)\nPlayback note ending delta: %.3f s (with delta %.3f s)\n",
			pGen->dstime[i][mv] / 1000.0, pGen->stime[i] / pGen->m_pspeed / 10 + pGen->dstime[i][mv] / 1000.0,
			pGen->detime[ei][mv] / 1000.0, pGen->etime[ei] / pGen->m_pspeed / 10 + pGen->detime[ei][mv] / 1000.0);
		m_info.AddText(st, RGB(0, 0, 0), 0);
		if (pGen->nsr1[i][mv] > 0) {
			st.Format("Note scan range: %d - %d\n", pGen->nsr1[i][mv], pGen->nsr2[i][mv]);
			m_info.AddText(st, RGB(0, 0, 0), 0);
		}

		st2 = "";
		for (int n = 0; n < pGen->ngraph[i][mv].size(); ++n) {
			if (pGen->ngraph[i][mv][n] > -1) {
				st.Format("%.1f ", pGen->ngraph[i][mv][n]);
				if (st2 != "") st2 += ", ";
				st2 += st;
			}
		}
		if (st2 != "") m_info.AddText("MeloCurve: " + st2 + "\n", RGB(0, 0, 0), 0);

		st.Format("Lengroup: %d\n", pGen->lengroup[i][mv]);
		m_info.AddText(st, RGB(0, 17in 0, 0), 0);
		st.Format("Articulation: %s\n", ArticName[pGen->artic[i][mv]]);
		m_info.AddText(st, RGB(0, 170, 0), 0);
		st.Format("Adapt comment(start) : %s\nAdapt comment(end) : %s\n",
			pGen->adapt_comment[i][mv], pGen->adapt_comment[ei][mv]);
		m_info.AddText(st, RGB(0, 170, 0), 0);
		st.Format("Note comment: %s\n", pGen->comment[i][mv]);
		m_info.AddText(st, RGB(180, 0, 0), 0);
		st.Format("Note mark: %s\n", pGen->mark[i][mv]);
		m_info.AddText(st, RGB(180, 0, 0), 0);

		m_info.AddText("\n", RGB(0, 0, 0), 0);
		if (pGen->mel_id[i][mv] > -1) {
			st.Format("Melody: %s\n", pGen->mel_info[pGen->mel_id[i][mv]]);
			m_info.AddText(st, RGB(0, 0, 180), 0);
			m_info.AddText("\n", RGB(0, 0, 0), 0);
		}

		st.Format("Current offset: %d steps\n", pGen->coff[ms][mv]);
		m_info.AddText(st, RGB(0, 0, 0), CFE_BOLD);
		st.Format("Previous offset : %d steps\nNext offset : %d steps\n",
			pGen->poff[ms][mv], pGen->noff[ms][mv]);
		m_info.AddText(st, RGB(0, 0, 0), 0);
		st.Format("Dynamics: %d\n", pGen->dyn[ms][mv]);
		m_info.AddText(st, RGB(0, 0, 0), 0);
		st.Format("Vibrato intensity: %d\nVibrato speed: %d\n", pGen->vib[ms][mv], pGen->vibf[ms][mv]);
		m_info.AddText(st, RGB(0, 0, 0), 0);
		st.Format("Pause indicator: %d\n", pGen->pause[ms][mv]);
		m_info.AddText(st, RGB(0, 0, 0), 0);
		//AddText("Some text text text\r\n", RGB(250, 100, 0), CFE_BOLD | CFE_ITALIC | CFE_STRIKEOUT | CFE_UNDERLINE);
		m_info.SetSel(0, 0);
		pGen->mutex_output.unlock();
	}

	return TRUE;  // return TRUE unless you set the focus to a control
								// EXCEPTION: OCX Property Pages should return FALSE
}
<commit_msg>Fix bug<commit_after>// InfoDlg.cpp : implementation file
//

#include "stdafx.h"
#include "MGen.h"
#include "InfoDlg.h"
#include "afxdialogex.h"
#include "MainFrm.h"
#include "GLibrary/GMidi.h"
#include "MGenView.h"

#ifdef _DEBUG
#define new DEBUG_NEW
#endif

// CInfoDlg dialog

IMPLEMENT_DYNAMIC(CInfoDlg, CDialog)

CInfoDlg::CInfoDlg(CWnd* pParent /*=NULL*/)
	: CDialog(IDD_DIALOG_INFO, pParent)
{

}

CInfoDlg::~CInfoDlg()
{
}

void CInfoDlg::DoDataExchange(CDataExchange* pDX)
{
	CDialog::DoDataExchange(pDX);
	DDX_Control(pDX, IDC_RICHEDIT21, m_info);
}

BEGIN_MESSAGE_MAP(CInfoDlg, CDialog)
END_MESSAGE_MAP()

// CInfoDlg message handlers

BOOL CInfoDlg::OnInitDialog()
{
	CDialog::OnInitDialog();

	CMainFrame *mf = (CMainFrame *)AfxGetMainWnd();
	CGMidi *pGen = mf->pGen;
	if (pGen != 0) {
		if (!pGen->mutex_output.try_lock_for(chrono::milliseconds(1000))) {
			mf->WriteLog(5, "InfoDlg mutex timed out: showing nothing");
			return TRUE;
		}
		int ms = ((CMGenView*)(mf->GetActiveView()))->mouse_step;
		int mv = ((CMGenView*)(mf->GetActiveView()))->mouse_voice;
		// Note start and end
		int i = ms - pGen->coff[ms][mv];
		int ei = ms + pGen->noff[ms][mv] - 1;
		CString st, st2;

		st.Format("Step: %d (measure %d)", ms, ms / 8);
		SetWindowText(st);
		//m_info.AddText(st, RGB(0, 0, 0), CFE_BOLD);
		st.Format("Tempo: %.1f bpm (randomized from %.1f bpm)\nStep start time: %.3f s (%.2f ms long), end time %.3f s\n",
			pGen->tempo[ms], pGen->tempo_src[ms], pGen->stime[ms] / pGen->m_pspeed / 10,
			(pGen->etime[ms] - pGen->stime[ms]) * 100 / pGen->m_pspeed, pGen->etime[ms] / pGen->m_pspeed / 10);
		m_info.AddText(st, RGB(0, 0, 0), 0);
		m_info.AddText("\n", RGB(170, 0, 0), 0);

		st.Format("Voice: %d (%s, channel %d, type %d)\n", mv,
			pGen->InstGName[pGen->instr[mv]] + "/" + pGen->InstCName[pGen->instr[mv]],
			pGen->instr_channel[pGen->instr[mv]], pGen->instr_type[pGen->instr[mv]]);
		m_info.AddText(st, RGB(0, 0, 0), CFE_BOLD);
		st.Format("Instrument library: %s\n", pGen->instr_lib[pGen->instr[mv]]);
		m_info.AddText(st, RGB(0, 0, 0), 0);
		st.Format("Voice show transpose: %d semitones\n", pGen->show_transpose[mv]);
		m_info.AddText(st, RGB(0, 0, 0), 0);
		if (pGen->midifile_loaded) {
			st.Format("From MIDI file: track %d \"%s\" local-voice %d, channel %d, delta %d ms (%.0f%% croche)\n", pGen->track_id[mv], pGen->track_name[mv], pGen->track_vid[mv], pGen->midi_ch[ms][mv], pGen->midi_delta[ms][mv], (float)(pGen->midi_delta[ms][mv]) / 300.0*(float)(pGen->tempo[ms]));
			m_info.AddText(st, RGB(0, 0, 200), 0);
		}
		m_info.AddText("\n", RGB(0, 0, 0), 0);

		st.Format("Note: %s (midi %d)\n", CGLib::GetNoteName(pGen->note[ms][mv]), pGen->note[ms][mv]);
		m_info.AddText(st, RGB(0, 0, 0), CFE_BOLD);
		st.Format("Key: %s%s\n", NoteName[pGen->tonic[i][mv]], pGen->minor[i][mv]?"m":"");
		m_info.AddText(st, RGB(0, 0, 0), 0);
		st.Format("Note length: %d steps\n", pGen->len[ms][mv]);
		m_info.AddText(st, RGB(0, 0, 0), 0);
		st.Format("Note velocity: %d\n", pGen->vel[i][mv]);
		m_info.AddText(st, RGB(0, 0, 0), 0);
		st.Format("Lyrics from MIDI file: %s\n", pGen->lyrics[i][mv]);
		m_info.AddText(st, RGB(0, 0, 0), 0);

		st.Format("Playback note start delta: %.3f s (with delta %.3f s)\nPlayback note ending delta: %.3f s (with delta %.3f s)\n",
			pGen->dstime[i][mv] / 1000.0, pGen->stime[i] / pGen->m_pspeed / 10 + pGen->dstime[i][mv] / 1000.0,
			pGen->detime[ei][mv] / 1000.0, pGen->etime[ei] / pGen->m_pspeed / 10 + pGen->detime[ei][mv] / 1000.0);
		m_info.AddText(st, RGB(0, 0, 0), 0);
		if (pGen->nsr1[i][mv] > 0) {
			st.Format("Note scan range: %d - %d\n", pGen->nsr1[i][mv], pGen->nsr2[i][mv]);
			m_info.AddText(st, RGB(0, 0, 0), 0);
		}

		st2 = "";
		for (int n = 0; n < pGen->ngraph[i][mv].size(); ++n) {
			if (pGen->ngraph[i][mv][n] > -1) {
				st.Format("%.1f ", pGen->ngraph[i][mv][n]);
				if (st2 != "") st2 += ", ";
				st2 += st;
			}
		}
		if (st2 != "") m_info.AddText("MeloCurve: " + st2 + "\n", RGB(0, 0, 0), 0);

		st.Format("Lengroup: %d\n", pGen->lengroup[i][mv]);
		m_info.AddText(st, RGB(0, 170, 0), 0);
		st.Format("Articulation: %s\n", ArticName[pGen->artic[i][mv]]);
		m_info.AddText(st, RGB(0, 170, 0), 0);
		st.Format("Adapt comment(start) : %s\nAdapt comment(end) : %s\n",
			pGen->adapt_comment[i][mv], pGen->adapt_comment[ei][mv]);
		m_info.AddText(st, RGB(0, 170, 0), 0);
		st.Format("Note comment: %s\n", pGen->comment[i][mv]);
		m_info.AddText(st, RGB(180, 0, 0), 0);
		st.Format("Note mark: %s\n", pGen->mark[i][mv]);
		m_info.AddText(st, RGB(180, 0, 0), 0);

		m_info.AddText("\n", RGB(0, 0, 0), 0);
		if (pGen->mel_id[i][mv] > -1) {
			st.Format("Melody: %s\n", pGen->mel_info[pGen->mel_id[i][mv]]);
			m_info.AddText(st, RGB(0, 0, 180), 0);
			m_info.AddText("\n", RGB(0, 0, 0), 0);
		}

		st.Format("Current offset: %d steps\n", pGen->coff[ms][mv]);
		m_info.AddText(st, RGB(0, 0, 0), CFE_BOLD);
		st.Format("Previous offset : %d steps\nNext offset : %d steps\n",
			pGen->poff[ms][mv], pGen->noff[ms][mv]);
		m_info.AddText(st, RGB(0, 0, 0), 0);
		st.Format("Dynamics: %d\n", pGen->dyn[ms][mv]);
		m_info.AddText(st, RGB(0, 0, 0), 0);
		st.Format("Vibrato intensity: %d\nVibrato speed: %d\n", pGen->vib[ms][mv], pGen->vibf[ms][mv]);
		m_info.AddText(st, RGB(0, 0, 0), 0);
		st.Format("Pause indicator: %d\n", pGen->pause[ms][mv]);
		m_info.AddText(st, RGB(0, 0, 0), 0);
		//AddText("Some text text text\r\n", RGB(250, 100, 0), CFE_BOLD | CFE_ITALIC | CFE_STRIKEOUT | CFE_UNDERLINE);
		m_info.SetSel(0, 0);
		pGen->mutex_output.unlock();
	}

	return TRUE;  // return TRUE unless you set the focus to a control
								// EXCEPTION: OCX Property Pages should return FALSE
}
<|endoftext|>


<commit_before>/* Copyright(c) 1998-1999, ALICE Experiment at CERN, All rights reserved. *
 * See cxx source for full Copyright notice                               */

/* $Id$ */

/// By Laurent Aphecetche

{
  gSystem->SetIncludePath("-I${ALICE_ROOT}/include -I${ALICE_ROOT}/MUON -I${ALICE_ROOT}/MUON/mapping");
}
<commit_msg>Adding loading MUON libraries (Laurent)<commit_after>/* Copyright(c) 1998-1999, ALICE Experiment at CERN, All rights reserved. *
 * See cxx source for full Copyright notice                               */

/* $Id$ */

/// By Laurent Aphecetche

{
  cout << "Loading MUON libraries ..." << endl;
  gROOT->LoadMacro("${ALICE_ROOT}/MUON/loadlibs.C");
  gInterpreter->ProcessLine("loadlibs()");

  cout << "Setting include path ..." << endl;
  gSystem->SetIncludePath("-I${ALICE_ROOT}/include -I${ALICE_ROOT}/MUON -I${ALICE_ROOT}/MUON/mapping");
}
<|endoftext|>


<commit_before>/*
 * This file is open source software, licensed to you under the terms
 * of the Apache License, Version 2.0 (the "License").  See the NOTICE file
 * distributed with this work for additional information regarding copyright
 * ownership.  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.
 */
/*
 * Copyright (C) 2019 ScyllaDB Ltd.
 */

#include <seastar/core/app-template.hh>
#include <seastar/core/coroutine.hh>
#include <seastar/core/fstream.hh>
#include <seastar/core/sleep.hh>

int main(int argc, char** argv) {
    seastar::app_template app;
    app.run(argc, argv, [] () -> seastar::future<> {
        std::cout << "this is a completely useless program\nplease stand by...\n";
        auto f = seastar::parallel_for_each(std::vector<int> { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 }, [] (int i) -> seastar::future<> {
            co_await seastar::sleep(std::chrono::seconds(i));
            std::cout << i << "\n";
        });

        auto file = co_await seastar::open_file_dma("useless_file.txt", seastar::open_flags::create | seastar::open_flags::wo);
        auto out = seastar::make_file_output_stream(file);
        seastar::sstring str = "nothing to see here, move along now\n";
        co_await out.write(str);
        co_await out.flush();
        co_await out.close();

        co_await std::move(f);
        std::cout << "done\n";
    });
}
<commit_msg>tests: demos: coroutine_demo: add missing include for open_file_dma()<commit_after>/*
 * This file is open source software, licensed to you under the terms
 * of the Apache License, Version 2.0 (the "License").  See the NOTICE file
 * distributed with this work for additional information regarding copyright
 * ownership.  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.
 */
/*
 * Copyright (C) 2019 ScyllaDB Ltd.
 */

#include <seastar/core/app-template.hh>
#include <seastar/core/coroutine.hh>
#include <seastar/core/fstream.hh>
#include <seastar/core/sleep.hh>
#include <seastar/core/seastar.hh>

int main(int argc, char** argv) {
    seastar::app_template app;
    app.run(argc, argv, [] () -> seastar::future<> {
        std::cout << "this is a completely useless program\nplease stand by...\n";
        auto f = seastar::parallel_for_each(std::vector<int> { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 }, [] (int i) -> seastar::future<> {
            co_await seastar::sleep(std::chrono::seconds(i));
            std::cout << i << "\n";
        });

        auto file = co_await seastar::open_file_dma("useless_file.txt", seastar::open_flags::create | seastar::open_flags::wo);
        auto out = seastar::make_file_output_stream(file);
        seastar::sstring str = "nothing to see here, move along now\n";
        co_await out.write(str);
        co_await out.flush();
        co_await out.close();

        co_await std::move(f);
        std::cout << "done\n";
    });
}
<|endoftext|>


<commit_before>#include "IConnection.h"
#include "IConnectionServer.h"
#include "IConnection.inl"

#include <string.h>
// #include <iostream>

#if defined Socket_OS_Linux
 #include <netinet/in.h>
 #include <netinet/tcp.h>
 #include <netdb.h>
 #include <errno.h>
#elif defined Socket_OS_Windows
#else
#endif

namespace Socket
{
	class CConnectionServer : virtual public TConnection<IConnectionServer>
	{
	public:

		virtual boolean listen(
			uint32 ui32Port)
		{
			if(!open())
			{
				return false;
			}

			int l_iReuseAddress=1;
			::setsockopt(m_i32Socket, SOL_SOCKET, SO_REUSEADDR, &l_iReuseAddress, sizeof(l_iReuseAddress));

			struct sockaddr_in l_oLocalHostAddress;
			memset(&l_oLocalHostAddress, 0, sizeof(l_oLocalHostAddress));
			l_oLocalHostAddress.sin_family=AF_INET;
			l_oLocalHostAddress.sin_port=htons((unsigned short)ui32Port);
			l_oLocalHostAddress.sin_addr.s_addr=htonl(INADDR_ANY);

			if(::bind(m_i32Socket, (struct sockaddr*)&l_oLocalHostAddress, sizeof(l_oLocalHostAddress))==-1)
			{
/*
				switch(errno)
				{
					case EBADF: std::cout << "EBADF" << std::endl; break;
					case ENOTSOCK: std::cout << "ENOTSOCK" << std::endl; break;
					case EADDRINUSE: std::cout << "EADDRINUSE" << std::endl; break;
					case EINVAL: std::cout << "EINVAL" << std::endl; break;
					case EROFS: std::cout << "EROFS" << std::endl; break;
					case EFAULT: std::cout << "EFAULT" << std::endl; break;
					case ENAMETOOLONG: std::cout << "ENAMETOOLONG" << std::endl; break;
					case ENOENT: std::cout << "ENOENT" << std::endl; break;
					case ENOMEM: std::cout << "ENOMEM" << std::endl; break;
					case ENOTDIR: std::cout << "ENOTDIR" << std::endl; break;
					case EACCES: std::cout << "EACCES" << std::endl; break;
					case ELOOP: std::cout << "ELOOP" << std::endl; break;
					default: std::cout << "Bind_unknown" << std::endl;
				}
*/
				return false;
			}

			if(::listen(m_i32Socket, 1)==-1)
			{
/*
				switch(errno)
				{
					case EADDRINUSE: std::cout << "EADDRINUSE" << std::endl; break;
					case EBADF: std::cout << "EBADF" << std::endl; break;
					case ENOTSOCK: std::cout << "ENOTSOCK" << std::endl; break;
					case EOPNOTSUPP: std::cout << "EOPNOTSUPP" << std::endl; break;
					default: std::cout << "Listen_unknown" << std::endl;
				}
*/
				return false;
			}

			return true;
		}

		virtual IConnection* accept(void)
		{
			struct sockaddr_in l_oClientAddress;
#if defined Socket_OS_Linux
			socklen_t l_iClientAddressSize=sizeof(l_oClientAddress);
#elif defined Socket_OS_Windows
			int l_iClientAddressSize=sizeof(l_oClientAddress);
#else
#endif
			int32 l_i32ClientSocket=::accept(m_i32Socket, (struct sockaddr*)&l_oClientAddress, &l_iClientAddressSize);
			if(l_iClientAddressSize==-1)
			{
				return NULL;
			}
			return new TConnection<IConnection>(l_i32ClientSocket);
		}
	};

	IConnectionServer* createConnectionServer(void)
	{
		return new CConnectionServer();
	}
};
<commit_msg>openvibe-module socket :  * ported reuse adress option to windows<commit_after>#include "IConnection.h"
#include "IConnectionServer.h"
#include "IConnection.inl"

#include <string.h>
// #include <iostream>

#if defined Socket_OS_Linux
 #include <netinet/in.h>
 #include <netinet/tcp.h>
 #include <netdb.h>
 #include <errno.h>
#elif defined Socket_OS_Windows
#else
#endif

namespace Socket
{
	class CConnectionServer : virtual public TConnection<IConnectionServer>
	{
	public:

		virtual boolean listen(
			uint32 ui32Port)
		{
			if(!open())
			{
				return false;
			}

			int l_iReuseAddress=1;
#if defined Socket_OS_Windows
			::setsockopt(m_i32Socket, SOL_SOCKET, SO_REUSEADDR, reinterpret_cast<const char*>(&l_iReuseAddress), sizeof(l_iReuseAddress));
#else
			::setsockopt(m_i32Socket, SOL_SOCKET, SO_REUSEADDR, &l_iReuseAddress, sizeof(l_iReuseAddress));
#endif

			struct sockaddr_in l_oLocalHostAddress;
			memset(&l_oLocalHostAddress, 0, sizeof(l_oLocalHostAddress));
			l_oLocalHostAddress.sin_family=AF_INET;
			l_oLocalHostAddress.sin_port=htons((unsigned short)ui32Port);
			l_oLocalHostAddress.sin_addr.s_addr=htonl(INADDR_ANY);

			if(::bind(m_i32Socket, (struct sockaddr*)&l_oLocalHostAddress, sizeof(l_oLocalHostAddress))==-1)
			{
/*
				switch(errno)
				{
					case EBADF: std::cout << "EBADF" << std::endl; break;
					case ENOTSOCK: std::cout << "ENOTSOCK" << std::endl; break;
					case EADDRINUSE: std::cout << "EADDRINUSE" << std::endl; break;
					case EINVAL: std::cout << "EINVAL" << std::endl; break;
					case EROFS: std::cout << "EROFS" << std::endl; break;
					case EFAULT: std::cout << "EFAULT" << std::endl; break;
					case ENAMETOOLONG: std::cout << "ENAMETOOLONG" << std::endl; break;
					case ENOENT: std::cout << "ENOENT" << std::endl; break;
					case ENOMEM: std::cout << "ENOMEM" << std::endl; break;
					case ENOTDIR: std::cout << "ENOTDIR" << std::endl; break;
					case EACCES: std::cout << "EACCES" << std::endl; break;
					case ELOOP: std::cout << "ELOOP" << std::endl; break;
					default: std::cout << "Bind_unknown" << std::endl;
				}
*/
				return false;
			}

			if(::listen(m_i32Socket, 1)==-1)
			{
/*
				switch(errno)
				{
					case EADDRINUSE: std::cout << "EADDRINUSE" << std::endl; break;
					case EBADF: std::cout << "EBADF" << std::endl; break;
					case ENOTSOCK: std::cout << "ENOTSOCK" << std::endl; break;
					case EOPNOTSUPP: std::cout << "EOPNOTSUPP" << std::endl; break;
					default: std::cout << "Listen_unknown" << std::endl;
				}
*/
				return false;
			}

			return true;
		}

		virtual IConnection* accept(void)
		{
			struct sockaddr_in l_oClientAddress;
#if defined Socket_OS_Linux
			socklen_t l_iClientAddressSize=sizeof(l_oClientAddress);
#elif defined Socket_OS_Windows
			int l_iClientAddressSize=sizeof(l_oClientAddress);
#else
#endif
			int32 l_i32ClientSocket=::accept(m_i32Socket, (struct sockaddr*)&l_oClientAddress, &l_iClientAddressSize);
			if(l_iClientAddressSize==-1)
			{
				return NULL;
			}
			return new TConnection<IConnection>(l_i32ClientSocket);
		}
	};

	IConnectionServer* createConnectionServer(void)
	{
		return new CConnectionServer();
	}
};
<|endoftext|>


<commit_before>/*
 * File:   DebugServer.cpp
 * Author: thomas
 *
 * Created on 10. September 2010, 15:38
 */

#include <string>

#include "DebugServer.h"

DebugServer::DebugServer()
: socket(NULL)
{
  GError *err = NULL;

  g_message("Creating new socket object");

  socket = g_socket_new(G_SOCKET_FAMILY_IPV4, G_SOCKET_TYPE_STREAM, G_SOCKET_PROTOCOL_TCP, &err);
  GInetAddress* inetAddress = g_inet_address_new_any(G_SOCKET_FAMILY_IPV4);

  GSocketAddress* socketAddress = g_inet_socket_address_new(inetAddress, 12345);

  g_message("Binding socket to port %d", 12345);
  g_socket_bind(socket, socketAddress, true, &err);
  g_assert(err == NULL);

  g_message("Listen");
  g_socket_listen(socket, &err);
  g_assert(err == NULL);

  g_message("Try to accept");
  GSocket* activeConnection = g_socket_accept(socket, NULL, &err);
  g_assert(err == NULL);

  g_message("Hey, someone is connected!");
  std::string msg = "Good morning, the DebugServer is not openend yet. Please be patient.\n";
  g_socket_send(activeConnection, msg.c_str(), msg.size(), NULL, NULL);

  g_socket_close(activeConnection, NULL);

}

DebugServer::~DebugServer()
{
  g_object_unref(socket);
}

<commit_msg>- trying out non-blocking mode, check for 30 seconds if someone connects, otherwise shutdown<commit_after>/*
 * File:   DebugServer.cpp
 * Author: thomas
 *
 * Created on 10. September 2010, 15:38
 */

#include <string>

#include "DebugServer.h"

DebugServer::DebugServer()
: socket(NULL)
{
  GError *err = NULL;

  g_message("Creating new socket object");

  socket = g_socket_new(G_SOCKET_FAMILY_IPV4, G_SOCKET_TYPE_STREAM, G_SOCKET_PROTOCOL_TCP, &err);
  GInetAddress* inetAddress = g_inet_address_new_any(G_SOCKET_FAMILY_IPV4);

  GSocketAddress* socketAddress = g_inet_socket_address_new(inetAddress, 12345);

  g_message("Binding socket to port %d", 12345);
  g_socket_bind(socket, socketAddress, true, &err);
  g_assert(err == NULL);

  g_message("Listen");
  g_socket_listen(socket, &err);
  g_assert(err == NULL);

  g_message("Set to unblocking mode");
  g_socket_set_blocking(socket, false);

  GSocket* activeConnection = NULL;
  unsigned int counter = 0;
  while(activeConnection == NULL && counter < 30)
  {
    g_message("Checking for client");
    activeConnection = g_socket_accept(socket, NULL, NULL);

    counter++;
    sleep(1);
  }

  if(activeConnection != NULL)
  {
    g_message("Hey, someone is connected!");
    std::string msg = "Good morning, the DebugServer is not openend yet. Please be patient.\n";
    g_socket_send(activeConnection, msg.c_str(), msg.size(), NULL, NULL);

    g_socket_close(activeConnection, NULL);
    g_object_unref(activeConnection);
  }

}

DebugServer::~DebugServer()
{
  g_object_unref(socket);
}

<|endoftext|>


<commit_before>#include <vtkRenderer.h>
#include <vtkRenderWindow.h>
#include <vtkRenderWindowInteractor.h>
#include <vtkSphereSource.h>
#include <vtkPolyDataMapper.h>
#include <vtkActor.h>
#include <vtkCamera.h>
#include <vtkConeSource.h>
#include <vtkGlyph3D.h>

int main( int, char *[] )
{
  // create the rendering objects
  vtkRenderer *ren1 = vtkRenderer::New();
  vtkRenderWindow *renWin = vtkRenderWindow::New();
    renWin->AddRenderer(ren1);
  vtkRenderWindowInteractor *iren = vtkRenderWindowInteractor::New();
    iren->SetRenderWindow(renWin);

  // create the pipline, ball and spikes
  vtkSphereSource *sphere = vtkSphereSource::New();
    sphere->SetPhiResolution(7); sphere->SetThetaResolution(7);
  vtkPolyDataMapper *sphereMapper = vtkPolyDataMapper::New();
    sphereMapper->SetInputConnection(sphere->GetOutputPort());
  vtkActor *sphereActor = vtkActor::New();
    sphereActor->SetMapper(sphereMapper);
  vtkActor *sphereActor2 = vtkActor::New();
    sphereActor2->SetMapper(sphereMapper);

  vtkConeSource *cone = vtkConeSource::New();
    cone->SetResolution(5);
  vtkGlyph3D *glyph = vtkGlyph3D::New();
    glyph->SetInputConnection(sphere->GetOutputPort());
    glyph->SetSourceConnection(cone->GetOutputPort());
    glyph->SetVectorModeToUseNormal();
    glyph->SetScaleModeToScaleByVector();
    glyph->SetScaleFactor(0.25);
  vtkPolyDataMapper *spikeMapper = vtkPolyDataMapper::New();
    spikeMapper->SetInputConnection(glyph->GetOutputPort());
  vtkActor *spikeActor = vtkActor::New();
    spikeActor->SetMapper(spikeMapper);
  vtkActor *spikeActor2 = vtkActor::New();
    spikeActor2->SetMapper(spikeMapper);

  spikeActor->SetPosition(0,0.7,0);
  sphereActor->SetPosition(0,0.7,0);
  spikeActor2->SetPosition(0,-1.0,-10);
  sphereActor2->SetPosition(0,-1.0,-10);
  spikeActor2->SetScale(1.5,1.5,1.5);
  sphereActor2->SetScale(1.5,1.5,1.5);

  ren1->AddActor(sphereActor);
  ren1->AddActor(spikeActor);
  ren1->AddActor(sphereActor2);
  ren1->AddActor(spikeActor2);
  ren1->SetBackground(0.1,0.2,0.4);
  renWin->SetSize(300,300);
  renWin->DoubleBufferOff();

  // do the first render and then zoom in a little
  renWin->Render();
  ren1->GetActiveCamera()->SetFocalPoint(0,0,0.0);
  ren1->GetActiveCamera()->Zoom(1.8);
  ren1->GetActiveCamera()->SetFocalDisk(0.05);

  renWin->SetFDFrames(11);
  renWin->Render();

  iren->Start();

  // Clean up allocated memory
  ren1->Delete();
  renWin->Delete();
  iren->Delete();
  sphere->Delete();
  sphereMapper->Delete();
  sphereActor->Delete();
  sphereActor2->Delete();
  cone->Delete();
  glyph->Delete();
  spikeMapper->Delete();
  spikeActor->Delete();
  spikeActor2->Delete();
}
<commit_msg>BUG: Remove legacy code<commit_after>#include <vtkRenderer.h>
#include <vtkRenderWindow.h>
#include <vtkRenderWindowInteractor.h>
#include <vtkSphereSource.h>
#include <vtkPolyDataMapper.h>
#include <vtkActor.h>
#include <vtkCamera.h>
#include <vtkConeSource.h>
#include <vtkGlyph3D.h>

int main( int, char *[] )
{
  // create the rendering objects
  vtkRenderer *ren1 = vtkRenderer::New();
  vtkRenderWindow *renWin = vtkRenderWindow::New();
    renWin->AddRenderer(ren1);
  vtkRenderWindowInteractor *iren = vtkRenderWindowInteractor::New();
    iren->SetRenderWindow(renWin);

  // create the pipline, ball and spikes
  vtkSphereSource *sphere = vtkSphereSource::New();
    sphere->SetPhiResolution(7); sphere->SetThetaResolution(7);
  vtkPolyDataMapper *sphereMapper = vtkPolyDataMapper::New();
    sphereMapper->SetInputConnection(sphere->GetOutputPort());
  vtkActor *sphereActor = vtkActor::New();
    sphereActor->SetMapper(sphereMapper);
  vtkActor *sphereActor2 = vtkActor::New();
    sphereActor2->SetMapper(sphereMapper);

  vtkConeSource *cone = vtkConeSource::New();
    cone->SetResolution(5);
  vtkGlyph3D *glyph = vtkGlyph3D::New();
    glyph->SetInputConnection(sphere->GetOutputPort());
    glyph->SetSourceConnection(cone->GetOutputPort());
    glyph->SetVectorModeToUseNormal();
    glyph->SetScaleModeToScaleByVector();
    glyph->SetScaleFactor(0.25);
  vtkPolyDataMapper *spikeMapper = vtkPolyDataMapper::New();
    spikeMapper->SetInputConnection(glyph->GetOutputPort());
  vtkActor *spikeActor = vtkActor::New();
    spikeActor->SetMapper(spikeMapper);
  vtkActor *spikeActor2 = vtkActor::New();
    spikeActor2->SetMapper(spikeMapper);

  spikeActor->SetPosition(0,0.7,0);
  sphereActor->SetPosition(0,0.7,0);
  spikeActor2->SetPosition(0,-1.0,-10);
  sphereActor2->SetPosition(0,-1.0,-10);
  spikeActor2->SetScale(1.5,1.5,1.5);
  sphereActor2->SetScale(1.5,1.5,1.5);

  ren1->AddActor(sphereActor);
  ren1->AddActor(spikeActor);
  ren1->AddActor(sphereActor2);
  ren1->AddActor(spikeActor2);
  ren1->SetBackground(0.1,0.2,0.4);
  renWin->SetSize(300,300);
  renWin->DoubleBufferOff();

  // do the first render and then zoom in a little
  renWin->Render();
  ren1->GetActiveCamera()->SetFocalPoint(0,0,0.0);
  ren1->GetActiveCamera()->Zoom(1.8);
  ren1->GetActiveCamera()->SetFocalDisk(0.05);

  renWin->Render();

  iren->Start();

  // Clean up allocated memory
  ren1->Delete();
  renWin->Delete();
  iren->Delete();
  sphere->Delete();
  sphereMapper->Delete();
  sphereActor->Delete();
  sphereActor2->Delete();
  cone->Delete();
  glyph->Delete();
  spikeMapper->Delete();
  spikeActor->Delete();
  spikeActor2->Delete();
  return EXIT_SUCCESS;
}
<|endoftext|>