<commit_before>#include "orbit_mpi.hh"
#include "pyORBIT_Object.hh"

#include "wrap_synch_part_redefinition_z_de.hh"
#include "wrap_bunch.hh"

#include <iostream>

#include "SynchPartRedefinitionZdE.hh"

namespace wrap_synch_part_redefinition{

  void error(const char* msg){ ORBIT_MPI_Finalize(msg); }

#ifdef __cplusplus
extern "C" {
#endif

	/**
	    Constructor for python class wrapping c++ SynchPartRedefinitionZdE instance.
      It never will be called directly.
	*/
	static PyObject* SynchPartRedefinitionZdE_new(PyTypeObject *type, PyObject *args, PyObject *kwds){
		pyORBIT_Object* self;
		self = (pyORBIT_Object *) type->tp_alloc(type, 0);
		self->cpp_obj = NULL;
		return (PyObject *) self;
	}

  /** This is implementation of the __init__ method */
  static int SynchPartRedefinitionZdE_init(pyORBIT_Object *self, PyObject *args, PyObject *kwds){
		self->cpp_obj =  new SynchPartRedefinitionZdE();
	  ((SynchPartRedefinitionZdE*) self->cpp_obj)->setPyWrapper((PyObject*) self);
    return 0;
  }

 /** Performs the calculation of the z and dE averages of the bunch */
  static PyObject* SynchPartRedefinitionZdE_analyzeBunch(PyObject *self, PyObject *args){
	  SynchPartRedefinitionZdE* cpp_SynchPartRedefinitionZdE = (SynchPartRedefinitionZdE*)((pyORBIT_Object*) self)->cpp_obj;
		PyObject* pyBunch;
		if(!PyArg_ParseTuple(args,"O:analyzeBunch",&pyBunch)){
			ORBIT_MPI_Finalize("SynchPartRedefinitionZdE - analyzeBunch(Bunch* bunch) - parameter is needed.");
		}
		PyObject* pyORBIT_Bunch_Type = wrap_orbit_bunch::getBunchType("Bunch");
		if(!PyObject_IsInstance(pyBunch,pyORBIT_Bunch_Type)){
			ORBIT_MPI_Finalize("SynchPartRedefinitionZdE - analyzeBunch(Bunch* bunch) - method needs a Bunch.");
		}
		Bunch* cpp_bunch = (Bunch*) ((pyORBIT_Object*)pyBunch)->cpp_obj;
		cpp_SynchPartRedefinitionZdE->analyzeBunch(cpp_bunch);
		Py_INCREF(Py_None);
		return Py_None;
  }

  /** Move the synch particle energy to the average energy. */
  static PyObject* SynchPartRedefinitionZdE_center_dE(PyObject *self, PyObject *args){
	  SynchPartRedefinitionZdE* cpp_SynchPartRedefinitionZdE = (SynchPartRedefinitionZdE*)((pyORBIT_Object*) self)->cpp_obj;
		PyObject* pyBunch;
		if(!PyArg_ParseTuple(args,"O:center_dE",&pyBunch)){
			ORBIT_MPI_Finalize("SynchPartRedefinitionZdE - center_dE(Bunch* bunch) - parameter is needed.");
		}
		PyObject* pyORBIT_Bunch_Type = wrap_orbit_bunch::getBunchType("Bunch");
		if(!PyObject_IsInstance(pyBunch,pyORBIT_Bunch_Type)){
			ORBIT_MPI_Finalize("SynchPartRedefinitionZdE - center_dE(Bunch* bunch) - method needs a Bunch.");
		}
		Bunch* cpp_bunch = (Bunch*) ((pyORBIT_Object*)pyBunch)->cpp_obj;
		cpp_SynchPartRedefinitionZdE->centerE(cpp_bunch);
		Py_INCREF(Py_None);
		return Py_None;
  }

   /** Move the synch particle's z position to the center of the bunch */
  static PyObject* SynchPartRedefinitionZdE_centerZ(PyObject *self, PyObject *args){
	  SynchPartRedefinitionZdE* cpp_SynchPartRedefinitionZdE = (SynchPartRedefinitionZdE*)((pyORBIT_Object*) self)->cpp_obj;
		PyObject* pyBunch;
		if(!PyArg_ParseTuple(args,"O:centerZ",&pyBunch)){
			ORBIT_MPI_Finalize("SynchPartRedefinitionZdE - centerZ(Bunch* bunch) - parameter is needed.");
		}
		PyObject* pyORBIT_Bunch_Type = wrap_orbit_bunch::getBunchType("Bunch");
		if(!PyObject_IsInstance(pyBunch,pyORBIT_Bunch_Type)){
			ORBIT_MPI_Finalize("SynchPartRedefinitionZdE - centerZ(Bunch* bunch) - method needs a Bunch.");
		}
		Bunch* cpp_bunch = (Bunch*) ((pyORBIT_Object*)pyBunch)->cpp_obj;
		cpp_SynchPartRedefinitionZdE->centerZ(cpp_bunch);
		Py_INCREF(Py_None);
		return Py_None;
  }

  /** Shift the synch particle energy. */
  static PyObject* SynchPartRedefinitionZdE_shift_dE(PyObject *self, PyObject *args){
	  SynchPartRedefinitionZdE* cpp_SynchPartRedefinitionZdE = (SynchPartRedefinitionZdE*)((pyORBIT_Object*) self)->cpp_obj;
		PyObject* pyBunch;
		double delta_E = 0.;
		if(!PyArg_ParseTuple(args,"Od:shift_dE",&pyBunch,&delta_E)){
			ORBIT_MPI_Finalize("SynchPartRedefinitionZdE - shift_dE(Bunch* bunch,delta_E) - parameters are needed.");
		}
		PyObject* pyORBIT_Bunch_Type = wrap_orbit_bunch::getBunchType("Bunch");
		if(!PyObject_IsInstance(pyBunch,pyORBIT_Bunch_Type)){
			ORBIT_MPI_Finalize("SynchPartRedefinitionZdE - shift_dE(Bunch* bunch,delta_E) - method needs a Bunch.");
		}
		Bunch* cpp_bunch = (Bunch*) ((pyORBIT_Object*)pyBunch)->cpp_obj;
		cpp_SynchPartRedefinitionZdE->shiftE(cpp_bunch,delta_E);
		Py_INCREF(Py_None);
		return Py_None;
  }

   /** Shift the synch particle's z position */
  static PyObject* SynchPartRedefinitionZdE_shiftZ(PyObject *self, PyObject *args){
	  SynchPartRedefinitionZdE* cpp_SynchPartRedefinitionZdE = (SynchPartRedefinitionZdE*)((pyORBIT_Object*) self)->cpp_obj;
		PyObject* pyBunch;
		double delta_z = 0.;
		if(!PyArg_ParseTuple(args,"Od:shiftZ",&pyBunch,&delta_z)){
			ORBIT_MPI_Finalize("SynchPartRedefinitionZdE - shiftZ(Bunch* bunch, delta_z) - parameters are needed.");
		}
		PyObject* pyORBIT_Bunch_Type = wrap_orbit_bunch::getBunchType("Bunch");
		if(!PyObject_IsInstance(pyBunch,pyORBIT_Bunch_Type)){
			ORBIT_MPI_Finalize("SynchPartRedefinitionZdE - shiftZ(Bunch* bunch, delta_z) - method needs a Bunch.");
		}
		Bunch* cpp_bunch = (Bunch*) ((pyORBIT_Object*)pyBunch)->cpp_obj;
		cpp_SynchPartRedefinitionZdE->shiftZ(cpp_bunch,delta_z);
		Py_INCREF(Py_None);
		return Py_None;
  }

	/** Returns the average z postion */
	static PyObject* SynchPartRedefinitionZdE_getAvg_Z(PyObject *self, PyObject *args){
		SynchPartRedefinitionZdE* cpp_SynchPartRedefinitionZdE = (SynchPartRedefinitionZdE*)((pyORBIT_Object*) self)->cpp_obj;
		return Py_BuildValue("d",cpp_SynchPartRedefinitionZdE->getAvg_Z());
	}

	/** Returns the average dE value */
	static PyObject* SynchPartRedefinitionZdE_getAvg_dE(PyObject *self, PyObject *args){
		SynchPartRedefinitionZdE* cpp_SynchPartRedefinitionZdE = (SynchPartRedefinitionZdE*)((pyORBIT_Object*) self)->cpp_obj;
		return Py_BuildValue("d",cpp_SynchPartRedefinitionZdE->getAvg_dE());
	}

  //-----------------------------------------------------
  //destructor for python SynchPartRedefinitionZdE class (__del__ method).
  //-----------------------------------------------------
  static void SynchPartRedefinitionZdE_del(pyORBIT_Object* self){
		//std::cerr<<"The SynchPartRedefinitionZdE __del__ has been called!"<<std::endl;
		delete ((SynchPartRedefinitionZdE*)self->cpp_obj);
		self->ob_type->tp_free((PyObject*)self);
  }

	// defenition of the methods of the python SynchPartRedefinitionZdE wrapper class
	// they will be vailable from python level
  static PyMethodDef SynchPartRedefinitionZdEClassMethods[] = {
		{ "analyzeBunch",	SynchPartRedefinitionZdE_analyzeBunch,	METH_VARARGS,"Calculates of the z and dE averages of the bunch."},
		{ "center_dE",    SynchPartRedefinitionZdE_center_dE,	    METH_VARARGS,"Transforms the synch part. energy to the average over the bunch."},
		{ "centerZ",      SynchPartRedefinitionZdE_centerZ,	      METH_VARARGS,"Transforms the synch part. z-coord. to the average over the bunch."},
		{ "shift_dE",     SynchPartRedefinitionZdE_shift_dE,	    METH_VARARGS,"Shift enegry of the synch part."},
		{ "shiftZ",       SynchPartRedefinitionZdE_shiftZ,	      METH_VARARGS,"Shift z-coord. the synch part."},
 		{ "getAvg_Z",			SynchPartRedefinitionZdE_getAvg_Z,    	METH_VARARGS,"Returns the average z postion."},
 		{ "getAvg_dE",		SynchPartRedefinitionZdE_getAvg_dE,    	METH_VARARGS,"Returns the average dE value."},
		{NULL}
  };

	// defenition of the memebers of the python SynchPartRedefinitionZdE wrapper class
	// they will be vailable from python level
	static PyMemberDef SynchPartRedefinitionZdEClassMembers [] = {
		{NULL}
	};

	//new python SynchPartRedefinitionZdE wrapper type definition
	static PyTypeObject pyORBIT_SynchPartRedefinitionZdE_Type = {
		PyObject_HEAD_INIT(NULL)
		0, /*ob_size*/
		"SynchPartRedefinitionZdE", /*tp_name*/
		sizeof(pyORBIT_Object), /*tp_basicsize*/
		0, /*tp_itemsize*/
		(destructor) SynchPartRedefinitionZdE_del , /*tp_dealloc*/
		0, /*tp_print*/
		0, /*tp_getattr*/
		0, /*tp_setattr*/
		0, /*tp_compare*/
		0, /*tp_repr*/
		0, /*tp_as_number*/
		0, /*tp_as_sequence*/
		0, /*tp_as_mapping*/
		0, /*tp_hash */
		0, /*tp_call*/
		0, /*tp_str*/
		0, /*tp_getattro*/
		0, /*tp_setattro*/
		0, /*tp_as_buffer*/
		Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /*tp_flags*/
		"The SynchPartRedefinitionZdE python wrapper", /* tp_doc */
		0, /* tp_traverse */
		0, /* tp_clear */
		0, /* tp_richcompare */
		0, /* tp_weaklistoffset */
		0, /* tp_iter */
		0, /* tp_iternext */
		SynchPartRedefinitionZdEClassMethods, /* tp_methods */
		SynchPartRedefinitionZdEClassMembers, /* tp_members */
		0, /* tp_getset */
		0, /* tp_base */
		0, /* tp_dict */
		0, /* tp_descr_get */
		0, /* tp_descr_set */
		0, /* tp_dictoffset */
		(initproc) SynchPartRedefinitionZdE_init, /* tp_init */
		0, /* tp_alloc */
		SynchPartRedefinitionZdE_new, /* tp_new */
	};

	//--------------------------------------------------
	//Initialization SynchPartRedefinitionZdE of the pySynchPartRedefinitionZdE class
	//--------------------------------------------------
  void initsynchpartredefinition(PyObject* module){
		if (PyType_Ready(&pyORBIT_SynchPartRedefinitionZdE_Type) < 0) return;
		Py_INCREF(&pyORBIT_SynchPartRedefinitionZdE_Type);
		PyModule_AddObject(module, "SynchPartRedefinitionZdE", (PyObject *)&pyORBIT_SynchPartRedefinitionZdE_Type);
	}

#ifdef __cplusplus
}
#endif

}
<commit_msg>Names of the methods are changed to make them uniform.<commit_after>#include "orbit_mpi.hh"
#include "pyORBIT_Object.hh"

#include "wrap_synch_part_redefinition_z_de.hh"
#include "wrap_bunch.hh"

#include <iostream>

#include "SynchPartRedefinitionZdE.hh"

namespace wrap_synch_part_redefinition{

  void error(const char* msg){ ORBIT_MPI_Finalize(msg); }

#ifdef __cplusplus
extern "C" {
#endif

	/**
	    Constructor for python class wrapping c++ SynchPartRedefinitionZdE instance.
      It never will be called directly.
	*/
	static PyObject* SynchPartRedefinitionZdE_new(PyTypeObject *type, PyObject *args, PyObject *kwds){
		pyORBIT_Object* self;
		self = (pyORBIT_Object *) type->tp_alloc(type, 0);
		self->cpp_obj = NULL;
		return (PyObject *) self;
	}

  /** This is implementation of the __init__ method */
  static int SynchPartRedefinitionZdE_init(pyORBIT_Object *self, PyObject *args, PyObject *kwds){
		self->cpp_obj =  new SynchPartRedefinitionZdE();
	  ((SynchPartRedefinitionZdE*) self->cpp_obj)->setPyWrapper((PyObject*) self);
    return 0;
  }

 /** Performs the calculation of the z and dE averages of the bunch */
  static PyObject* SynchPartRedefinitionZdE_analyzeBunch(PyObject *self, PyObject *args){
	  SynchPartRedefinitionZdE* cpp_SynchPartRedefinitionZdE = (SynchPartRedefinitionZdE*)((pyORBIT_Object*) self)->cpp_obj;
		PyObject* pyBunch;
		if(!PyArg_ParseTuple(args,"O:analyzeBunch",&pyBunch)){
			ORBIT_MPI_Finalize("SynchPartRedefinitionZdE - analyzeBunch(Bunch* bunch) - parameter is needed.");
		}
		PyObject* pyORBIT_Bunch_Type = wrap_orbit_bunch::getBunchType("Bunch");
		if(!PyObject_IsInstance(pyBunch,pyORBIT_Bunch_Type)){
			ORBIT_MPI_Finalize("SynchPartRedefinitionZdE - analyzeBunch(Bunch* bunch) - method needs a Bunch.");
		}
		Bunch* cpp_bunch = (Bunch*) ((pyORBIT_Object*)pyBunch)->cpp_obj;
		cpp_SynchPartRedefinitionZdE->analyzeBunch(cpp_bunch);
		Py_INCREF(Py_None);
		return Py_None;
  }

  /** Move the synch particle energy to the average energy. */
  static PyObject* SynchPartRedefinitionZdE_center_dE(PyObject *self, PyObject *args){
	  SynchPartRedefinitionZdE* cpp_SynchPartRedefinitionZdE = (SynchPartRedefinitionZdE*)((pyORBIT_Object*) self)->cpp_obj;
		PyObject* pyBunch;
		if(!PyArg_ParseTuple(args,"O:center_dE",&pyBunch)){
			ORBIT_MPI_Finalize("SynchPartRedefinitionZdE - center_dE(Bunch* bunch) - parameter is needed.");
		}
		PyObject* pyORBIT_Bunch_Type = wrap_orbit_bunch::getBunchType("Bunch");
		if(!PyObject_IsInstance(pyBunch,pyORBIT_Bunch_Type)){
			ORBIT_MPI_Finalize("SynchPartRedefinitionZdE - center_dE(Bunch* bunch) - method needs a Bunch.");
		}
		Bunch* cpp_bunch = (Bunch*) ((pyORBIT_Object*)pyBunch)->cpp_obj;
		cpp_SynchPartRedefinitionZdE->centerE(cpp_bunch);
		Py_INCREF(Py_None);
		return Py_None;
  }

   /** Move the synch particle's z position to the center of the bunch */
  static PyObject* SynchPartRedefinitionZdE_centerZ(PyObject *self, PyObject *args){
	  SynchPartRedefinitionZdE* cpp_SynchPartRedefinitionZdE = (SynchPartRedefinitionZdE*)((pyORBIT_Object*) self)->cpp_obj;
		PyObject* pyBunch;
		if(!PyArg_ParseTuple(args,"O:centerZ",&pyBunch)){
			ORBIT_MPI_Finalize("SynchPartRedefinitionZdE - centerZ(Bunch* bunch) - parameter is needed.");
		}
		PyObject* pyORBIT_Bunch_Type = wrap_orbit_bunch::getBunchType("Bunch");
		if(!PyObject_IsInstance(pyBunch,pyORBIT_Bunch_Type)){
			ORBIT_MPI_Finalize("SynchPartRedefinitionZdE - centerZ(Bunch* bunch) - method needs a Bunch.");
		}
		Bunch* cpp_bunch = (Bunch*) ((pyORBIT_Object*)pyBunch)->cpp_obj;
		cpp_SynchPartRedefinitionZdE->centerZ(cpp_bunch);
		Py_INCREF(Py_None);
		return Py_None;
  }

  /** Shift the synch particle energy. */
  static PyObject* SynchPartRedefinitionZdE_shift_dE(PyObject *self, PyObject *args){
	  SynchPartRedefinitionZdE* cpp_SynchPartRedefinitionZdE = (SynchPartRedefinitionZdE*)((pyORBIT_Object*) self)->cpp_obj;
		PyObject* pyBunch;
		double delta_E = 0.;
		if(!PyArg_ParseTuple(args,"Od:shift_dE",&pyBunch,&delta_E)){
			ORBIT_MPI_Finalize("SynchPartRedefinitionZdE - shift_dE(Bunch* bunch,delta_E) - parameters are needed.");
		}
		PyObject* pyORBIT_Bunch_Type = wrap_orbit_bunch::getBunchType("Bunch");
		if(!PyObject_IsInstance(pyBunch,pyORBIT_Bunch_Type)){
			ORBIT_MPI_Finalize("SynchPartRedefinitionZdE - shift_dE(Bunch* bunch,delta_E) - method needs a Bunch.");
		}
		Bunch* cpp_bunch = (Bunch*) ((pyORBIT_Object*)pyBunch)->cpp_obj;
		cpp_SynchPartRedefinitionZdE->shiftE(cpp_bunch,delta_E);
		Py_INCREF(Py_None);
		return Py_None;
  }

   /** Shift the synch particle's z position */
  static PyObject* SynchPartRedefinitionZdE_shiftZ(PyObject *self, PyObject *args){
	  SynchPartRedefinitionZdE* cpp_SynchPartRedefinitionZdE = (SynchPartRedefinitionZdE*)((pyORBIT_Object*) self)->cpp_obj;
		PyObject* pyBunch;
		double delta_z = 0.;
		if(!PyArg_ParseTuple(args,"Od:shiftZ",&pyBunch,&delta_z)){
			ORBIT_MPI_Finalize("SynchPartRedefinitionZdE - shiftZ(Bunch* bunch, delta_z) - parameters are needed.");
		}
		PyObject* pyORBIT_Bunch_Type = wrap_orbit_bunch::getBunchType("Bunch");
		if(!PyObject_IsInstance(pyBunch,pyORBIT_Bunch_Type)){
			ORBIT_MPI_Finalize("SynchPartRedefinitionZdE - shiftZ(Bunch* bunch, delta_z) - method needs a Bunch.");
		}
		Bunch* cpp_bunch = (Bunch*) ((pyORBIT_Object*)pyBunch)->cpp_obj;
		cpp_SynchPartRedefinitionZdE->shiftZ(cpp_bunch,delta_z);
		Py_INCREF(Py_None);
		return Py_None;
  }

	/** Returns the average z postion */
	static PyObject* SynchPartRedefinitionZdE_getAvg_Z(PyObject *self, PyObject *args){
		SynchPartRedefinitionZdE* cpp_SynchPartRedefinitionZdE = (SynchPartRedefinitionZdE*)((pyORBIT_Object*) self)->cpp_obj;
		return Py_BuildValue("d",cpp_SynchPartRedefinitionZdE->getAvg_Z());
	}

	/** Returns the average dE value */
	static PyObject* SynchPartRedefinitionZdE_getAvg_dE(PyObject *self, PyObject *args){
		SynchPartRedefinitionZdE* cpp_SynchPartRedefinitionZdE = (SynchPartRedefinitionZdE*)((pyORBIT_Object*) self)->cpp_obj;
		return Py_BuildValue("d",cpp_SynchPartRedefinitionZdE->getAvg_dE());
	}

  //-----------------------------------------------------
  //destructor for python SynchPartRedefinitionZdE class (__del__ method).
  //-----------------------------------------------------
  static void SynchPartRedefinitionZdE_del(pyORBIT_Object* self){
		//std::cerr<<"The SynchPartRedefinitionZdE __del__ has been called!"<<std::endl;
		delete ((SynchPartRedefinitionZdE*)self->cpp_obj);
		self->ob_type->tp_free((PyObject*)self);
  }

	// defenition of the methods of the python SynchPartRedefinitionZdE wrapper class
	// they will be vailable from python level
  static PyMethodDef SynchPartRedefinitionZdEClassMethods[] = {
		{ "analyzeBunch",	SynchPartRedefinitionZdE_analyzeBunch,	METH_VARARGS,"Calculates of the z and dE averages of the bunch."},
		{ "center_dE",    SynchPartRedefinitionZdE_center_dE,	    METH_VARARGS,"Transforms the synch part. energy to the average over the bunch."},
		{ "center_Z",      SynchPartRedefinitionZdE_centerZ,	      METH_VARARGS,"Transforms the synch part. z-coord. to the average over the bunch."},
		{ "shift_dE",     SynchPartRedefinitionZdE_shift_dE,	    METH_VARARGS,"Shift enegry of the synch part."},
		{ "shift_Z",       SynchPartRedefinitionZdE_shiftZ,	      METH_VARARGS,"Shift z-coord. the synch part."},
 		{ "getAvg_Z",			SynchPartRedefinitionZdE_getAvg_Z,    	METH_VARARGS,"Returns the average z postion."},
 		{ "getAvg_dE",		SynchPartRedefinitionZdE_getAvg_dE,    	METH_VARARGS,"Returns the average dE value."},
		{NULL}
  };

	// defenition of the memebers of the python SynchPartRedefinitionZdE wrapper class
	// they will be vailable from python level
	static PyMemberDef SynchPartRedefinitionZdEClassMembers [] = {
		{NULL}
	};

	//new python SynchPartRedefinitionZdE wrapper type definition
	static PyTypeObject pyORBIT_SynchPartRedefinitionZdE_Type = {
		PyObject_HEAD_INIT(NULL)
		0, /*ob_size*/
		"SynchPartRedefinitionZdE", /*tp_name*/
		sizeof(pyORBIT_Object), /*tp_basicsize*/
		0, /*tp_itemsize*/
		(destructor) SynchPartRedefinitionZdE_del , /*tp_dealloc*/
		0, /*tp_print*/
		0, /*tp_getattr*/
		0, /*tp_setattr*/
		0, /*tp_compare*/
		0, /*tp_repr*/
		0, /*tp_as_number*/
		0, /*tp_as_sequence*/
		0, /*tp_as_mapping*/
		0, /*tp_hash */
		0, /*tp_call*/
		0, /*tp_str*/
		0, /*tp_getattro*/
		0, /*tp_setattro*/
		0, /*tp_as_buffer*/
		Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /*tp_flags*/
		"The SynchPartRedefinitionZdE python wrapper", /* tp_doc */
		0, /* tp_traverse */
		0, /* tp_clear */
		0, /* tp_richcompare */
		0, /* tp_weaklistoffset */
		0, /* tp_iter */
		0, /* tp_iternext */
		SynchPartRedefinitionZdEClassMethods, /* tp_methods */
		SynchPartRedefinitionZdEClassMembers, /* tp_members */
		0, /* tp_getset */
		0, /* tp_base */
		0, /* tp_dict */
		0, /* tp_descr_get */
		0, /* tp_descr_set */
		0, /* tp_dictoffset */
		(initproc) SynchPartRedefinitionZdE_init, /* tp_init */
		0, /* tp_alloc */
		SynchPartRedefinitionZdE_new, /* tp_new */
	};

	//--------------------------------------------------
	//Initialization SynchPartRedefinitionZdE of the pySynchPartRedefinitionZdE class
	//--------------------------------------------------
  void initsynchpartredefinition(PyObject* module){
		if (PyType_Ready(&pyORBIT_SynchPartRedefinitionZdE_Type) < 0) return;
		Py_INCREF(&pyORBIT_SynchPartRedefinitionZdE_Type);
		PyModule_AddObject(module, "SynchPartRedefinitionZdE", (PyObject *)&pyORBIT_SynchPartRedefinitionZdE_Type);
	}

#ifdef __cplusplus
}
#endif

}
<|endoftext|>


<commit_before>/* Copyright (c) 2016 PaddlePaddle Authors. All Rights Reserved.

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 "paddle/fluid/framework/lod_rank_table.h"
#include "paddle/fluid/framework/lod_tensor.h"
#include "paddle/fluid/operators/array_operator.h"
#include "paddle/fluid/operators/math/math_function.h"

namespace paddle {
namespace operators {

class ShrinkRNNMemoryOp : public ArrayOp {
 public:
  ShrinkRNNMemoryOp(const std::string &type,
                    const framework::VariableNameMap &inputs,
                    const framework::VariableNameMap &outputs,
                    const framework::AttributeMap &attrs)
      : ArrayOp(type, inputs, outputs, attrs) {}

 private:
  void RunImpl(const framework::Scope &scope,
               const platform::Place &place) const override {
    auto *x_var = scope.FindVar(Input("X"));
    PADDLE_ENFORCE(x_var != nullptr, "Input X must be set");
    auto &x_tensor = x_var->Get<framework::LoDTensor>();
    size_t offset = this->GetOffset(scope, place);
    auto *rank_table_var = scope.FindVar(Input("RankTable"));
    PADDLE_ENFORCE(rank_table_var != nullptr, "RankTable must be set");
    auto &rank_table = rank_table_var->Get<framework::LoDRankTable>();

    auto &rank_items = rank_table.items();
    int dst_num_rows =
        std::lower_bound(rank_items.begin(), rank_items.end(), offset,
                         [](const framework::LoDRankTable::TableItem &a,
                            size_t b) { return a.length > b; }) -
        rank_items.begin();

    auto *out_var = scope.FindVar(Output("Out"));
    PADDLE_ENFORCE(out_var != nullptr, "Output(Out) must be set.");
    auto &out_tensor = *out_var->GetMutable<framework::LoDTensor>();

    size_t height = dst_num_rows;

    // do shrink for the top level LoD
    if (x_tensor.lod().size() > 0 &&
        x_tensor.lod()[0].size() > static_cast<size_t>(dst_num_rows)) {
      auto lod_offset = framework::GetSubLoDAndAbsoluteOffset(x_tensor.lod(), 0,
                                                              dst_num_rows, 0);
      height = lod_offset.second.second;
      auto out_lod = out_tensor.mutable_lod();
      framework::AppendLoD(out_lod, lod_offset.first);
    }

    if (dst_num_rows != 0) {
      out_tensor.ShareDataWith(x_tensor.Slice(0, height));
    }
  }
};

class ShrinkRNNMemoryOpProtoMaker : public framework::OpProtoAndCheckerMaker {
 public:
  void Make() override {
    AddInput("X", "(LoDTensor) The RNN step memory to be shrinked.");
    AddInput("RankTable", "(LoDRankTable) The lod_rank_table of dynamic RNN.");
    AddInput("I",
             "(LoDTensor) The step index. The RNN step memory 'X' will be "
             "shrinked to match the size of the input of the index'th step.");
    AddOutput("Out", "(LoDTensor) The shrinked RNN step memory.");
    AddComment(R"DOC(
This operator is used to shrink output batch of memory defined in dynamic RNN.

Dynamic RNN is able to handle variable-length sequences, in which, sequences in
a mini-batch are sorted by their lengths first. After that, the longest sequence
becomes the first one in the sorted batch, followed by the second longest, the
third longest, and so on. Dynamic RNN then slices a batch input timestep by
timestep from the sorted input. Once any sequence in the input batch reaches its
end, memory defined in dynamicRNN has to shrink its outputs to adapt to the input
batch size for the next time step.
)DOC");
  }
};

class ShrinkRNNMemoryInferShape : public framework::InferShapeBase {
 public:
  void operator()(framework::InferShapeContext *context) const override {
    PADDLE_ENFORCE(context->HasInput("X"));
    PADDLE_ENFORCE(context->HasInput("I"));
    PADDLE_ENFORCE(context->HasInput("RankTable"));
    context->SetOutputDim("Out", context->GetInputDim("X"));
  }
};

class ShrinkRNNMemoryGradOp : public ArrayOp {
 public:
  ShrinkRNNMemoryGradOp(const std::string &type,
                        const framework::VariableNameMap &inputs,
                        const framework::VariableNameMap &outputs,
                        const framework::AttributeMap &attrs)
      : ArrayOp(type, inputs, outputs, attrs) {}

 private:
  void RunImpl(const framework::Scope &scope,
               const platform::Place &place) const override {
    auto *dout_var = scope.FindVar(Input(framework::GradVarName("Out")));
    auto *dx_var = scope.FindVar(Output(framework::GradVarName("X")));
    PADDLE_ENFORCE(dx_var != nullptr, "Input Gradient should not be nullptr");
    auto *x_var = scope.FindVar(Input("X"));
    PADDLE_ENFORCE(x_var != nullptr);

    auto &x_tensor = x_var->Get<framework::LoDTensor>();
    auto &dx_tensor = *dx_var->GetMutable<framework::LoDTensor>();
    dx_tensor.Resize(x_tensor.dims());
    dx_tensor.mutable_data(x_tensor.place(), x_tensor.type());

    // get device context from pool
    platform::DeviceContextPool &pool = platform::DeviceContextPool::Instance();
    auto &dev_ctx = *pool.Get(place);

    if (dout_var == nullptr) {  // dx_tensor fill zero
      math::set_constant(dev_ctx, &dx_tensor, 0.0f);
    } else {
      auto &dout_tensor = dout_var->Get<framework::LoDTensor>();
      auto height = dout_tensor.dims()[0];
      auto slice = dx_tensor.Slice(0, static_cast<int>(height));
      framework::TensorCopy(dout_tensor, dout_tensor.place(), dev_ctx, &slice);
      if (dx_tensor.dims()[0] > height) {
        auto rest_tensor = dx_tensor.Slice(
            static_cast<int>(height), static_cast<int>(dx_tensor.dims()[0]));
        math::set_constant(dev_ctx, &rest_tensor, 0.0f);
      }
    }
    dx_tensor.set_lod(x_tensor.lod());
  }
};

class ShrinkRNNMemoryGradInferShape : public framework::InferShapeBase {
 public:
  void operator()(framework::InferShapeContext *context) const override {
    PADDLE_ENFORCE(context->HasInput("X"));
    PADDLE_ENFORCE(context->HasOutput(framework::GradVarName("X")));
    context->SetOutputDim(framework::GradVarName("X"),
                          context->GetInputDim("X"));
    context->ShareLoD("X", framework::GradVarName("X"));
  }
};

class ShrinkRNNGradOpMaker : public framework::SingleGradOpDescMaker {
 public:
  using framework::SingleGradOpDescMaker::SingleGradOpDescMaker;

 protected:
  std::unique_ptr<framework::OpDesc> Apply() const override {
    auto *op = new framework::OpDesc();
    op->SetType("shrink_rnn_memory_grad");
    op->SetInput("X", Input("X"));
    op->SetInput(framework::GradVarName("Out"), OutputGrad("Out"));
    op->SetOutput(framework::GradVarName("X"), InputGrad("X"));
    op->SetAttrMap(Attrs());
    return std::unique_ptr<framework::OpDesc>(op);
  }
};

}  // namespace operators
}  // namespace paddle

namespace ops = paddle::operators;
REGISTER_OPERATOR(shrink_rnn_memory, ops::ShrinkRNNMemoryOp,
                  ops::ShrinkRNNMemoryInferShape,
                  ops::ShrinkRNNMemoryOpProtoMaker, ops::ShrinkRNNGradOpMaker);
REGISTER_OPERATOR(shrink_rnn_memory_grad, ops::ShrinkRNNMemoryGradOp,
                  ops::ShrinkRNNMemoryGradInferShape);
<commit_msg>"fix style" (#13094)<commit_after>/* Copyright (c) 2016 PaddlePaddle Authors. All Rights Reserved.

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 "paddle/fluid/framework/lod_rank_table.h"
#include "paddle/fluid/framework/lod_tensor.h"
#include "paddle/fluid/operators/array_operator.h"
#include "paddle/fluid/operators/math/math_function.h"

namespace paddle {
namespace operators {

class ShrinkRNNMemoryOp : public ArrayOp {
 public:
  ShrinkRNNMemoryOp(const std::string &type,
                    const framework::VariableNameMap &inputs,
                    const framework::VariableNameMap &outputs,
                    const framework::AttributeMap &attrs)
      : ArrayOp(type, inputs, outputs, attrs) {}

 private:
  void RunImpl(const framework::Scope &scope,
               const platform::Place &place) const override {
    auto *x_var = scope.FindVar(Input("X"));
    PADDLE_ENFORCE(x_var != nullptr, "Input X must be set");
    auto &x_tensor = x_var->Get<framework::LoDTensor>();
    size_t offset = this->GetOffset(scope, place);
    auto *rank_table_var = scope.FindVar(Input("RankTable"));
    PADDLE_ENFORCE(rank_table_var != nullptr, "RankTable must be set");
    auto &rank_table = rank_table_var->Get<framework::LoDRankTable>();

    auto &rank_items = rank_table.items();
    int dst_num_rows =
        std::lower_bound(rank_items.begin(), rank_items.end(), offset,
                         [](const framework::LoDRankTable::TableItem &a,
                            size_t b) { return a.length > b; }) -
        rank_items.begin();

    auto *out_var = scope.FindVar(Output("Out"));
    PADDLE_ENFORCE(out_var != nullptr, "Output(Out) must be set.");
    auto &out_tensor = *out_var->GetMutable<framework::LoDTensor>();

    size_t height = dst_num_rows;

    // do shrink for the top level LoD
    if (x_tensor.lod().size() > 0 &&
        x_tensor.lod()[0].size() > static_cast<size_t>(dst_num_rows)) {
      auto lod_offset = framework::GetSubLoDAndAbsoluteOffset(x_tensor.lod(), 0,
                                                              dst_num_rows, 0);
      height = lod_offset.second.second;
      auto out_lod = out_tensor.mutable_lod();
      framework::AppendLoD(out_lod, lod_offset.first);
    }

    if (dst_num_rows != 0) {
      out_tensor.mutable_data(place, x_tensor.type());
      auto dev_ctx = platform::DeviceContextPool::Instance().Get(place);
      framework::TensorCopy(x_tensor.Slice(0, height), place, *dev_ctx,
                            &out_tensor);
    }
  }
};

class ShrinkRNNMemoryOpProtoMaker : public framework::OpProtoAndCheckerMaker {
 public:
  void Make() override {
    AddInput("X", "(LoDTensor) The RNN step memory to be shrinked.");
    AddInput("RankTable", "(LoDRankTable) The lod_rank_table of dynamic RNN.");
    AddInput("I",
             "(LoDTensor) The step index. The RNN step memory 'X' will be "
             "shrinked to match the size of the input of the index'th step.");
    AddOutput("Out", "(LoDTensor) The shrinked RNN step memory.");
    AddComment(R"DOC(
This operator is used to shrink output batch of memory defined in dynamic RNN.

Dynamic RNN is able to handle variable-length sequences, in which, sequences in
a mini-batch are sorted by their lengths first. After that, the longest sequence
becomes the first one in the sorted batch, followed by the second longest, the
third longest, and so on. Dynamic RNN then slices a batch input timestep by
timestep from the sorted input. Once any sequence in the input batch reaches its
end, memory defined in dynamicRNN has to shrink its outputs to adapt to the input
batch size for the next time step.
)DOC");
  }
};

class ShrinkRNNMemoryInferShape : public framework::InferShapeBase {
 public:
  void operator()(framework::InferShapeContext *context) const override {
    PADDLE_ENFORCE(context->HasInput("X"));
    PADDLE_ENFORCE(context->HasInput("I"));
    PADDLE_ENFORCE(context->HasInput("RankTable"));
    context->SetOutputDim("Out", context->GetInputDim("X"));
  }
};

class ShrinkRNNMemoryGradOp : public ArrayOp {
 public:
  ShrinkRNNMemoryGradOp(const std::string &type,
                        const framework::VariableNameMap &inputs,
                        const framework::VariableNameMap &outputs,
                        const framework::AttributeMap &attrs)
      : ArrayOp(type, inputs, outputs, attrs) {}

 private:
  void RunImpl(const framework::Scope &scope,
               const platform::Place &place) const override {
    auto *dout_var = scope.FindVar(Input(framework::GradVarName("Out")));
    auto *dx_var = scope.FindVar(Output(framework::GradVarName("X")));
    PADDLE_ENFORCE(dx_var != nullptr, "Input Gradient should not be nullptr");
    auto *x_var = scope.FindVar(Input("X"));
    PADDLE_ENFORCE(x_var != nullptr);

    auto &x_tensor = x_var->Get<framework::LoDTensor>();
    auto &dx_tensor = *dx_var->GetMutable<framework::LoDTensor>();
    dx_tensor.Resize(x_tensor.dims());
    dx_tensor.mutable_data(x_tensor.place(), x_tensor.type());

    // get device context from pool
    platform::DeviceContextPool &pool = platform::DeviceContextPool::Instance();
    auto &dev_ctx = *pool.Get(place);

    if (dout_var == nullptr) {  // dx_tensor fill zero
      math::set_constant(dev_ctx, &dx_tensor, 0.0f);
    } else {
      auto &dout_tensor = dout_var->Get<framework::LoDTensor>();
      auto height = dout_tensor.dims()[0];
      auto slice = dx_tensor.Slice(0, static_cast<int>(height));
      framework::TensorCopy(dout_tensor, dout_tensor.place(), dev_ctx, &slice);
      if (dx_tensor.dims()[0] > height) {
        auto rest_tensor = dx_tensor.Slice(
            static_cast<int>(height), static_cast<int>(dx_tensor.dims()[0]));
        math::set_constant(dev_ctx, &rest_tensor, 0.0f);
      }
    }
    dx_tensor.set_lod(x_tensor.lod());
  }
};

class ShrinkRNNMemoryGradInferShape : public framework::InferShapeBase {
 public:
  void operator()(framework::InferShapeContext *context) const override {
    PADDLE_ENFORCE(context->HasInput("X"));
    PADDLE_ENFORCE(context->HasOutput(framework::GradVarName("X")));
    context->SetOutputDim(framework::GradVarName("X"),
                          context->GetInputDim("X"));
    context->ShareLoD("X", framework::GradVarName("X"));
  }
};

class ShrinkRNNGradOpMaker : public framework::SingleGradOpDescMaker {
 public:
  using framework::SingleGradOpDescMaker::SingleGradOpDescMaker;

 protected:
  std::unique_ptr<framework::OpDesc> Apply() const override {
    auto *op = new framework::OpDesc();
    op->SetType("shrink_rnn_memory_grad");
    op->SetInput("X", Input("X"));
    op->SetInput(framework::GradVarName("Out"), OutputGrad("Out"));
    op->SetOutput(framework::GradVarName("X"), InputGrad("X"));
    op->SetAttrMap(Attrs());
    return std::unique_ptr<framework::OpDesc>(op);
  }
};

}  // namespace operators
}  // namespace paddle

namespace ops = paddle::operators;
REGISTER_OPERATOR(shrink_rnn_memory, ops::ShrinkRNNMemoryOp,
                  ops::ShrinkRNNMemoryInferShape,
                  ops::ShrinkRNNMemoryOpProtoMaker, ops::ShrinkRNNGradOpMaker);
REGISTER_OPERATOR(shrink_rnn_memory_grad, ops::ShrinkRNNMemoryGradOp,
                  ops::ShrinkRNNMemoryGradInferShape);
<|endoftext|>


<commit_before>
#define CATCH_CONFIG_MAIN
#include "catch.hpp"
#include "sdMain.h"
#include <array>
using namespace std;

TEST_CASE("Test all descriptors types"){
    sdScene scene;
    scene.addExtension(EExtension::SD_SOURCE_SPREAD);
    sdEntity * entity = scene.addEntity("MyEntity");

    /*** core ***/
    /// 4.3 core

    // SD_TYPE
    entity->addEvent<SD_TYPE>(0.0, sdDescriptor<SD_TYPE>::EType::SD_LISTENER);
    REQUIRE(entity->getValueAsString<SD_TYPE>(0.0) == "listener");
    REQUIRE(*(entity->getValue<SD_TYPE>(0.0)) == sdDescriptor<SD_TYPE>::SD_LISTENER);

    // SD_PRESENT
    entity->addEvent<SD_PRESENT>(0.0, false);
    REQUIRE(entity->getValueAsString<SD_PRESENT>(0.0) == "false");
    REQUIRE(*(entity->getValue<SD_PRESENT>(0.0)) == false);

    // SD_POSITION
    entity->addEvent<SD_POSITION>(0.0, {0.2,0.3,0.4});
    REQUIRE( entity->getValueAsString<SD_POSITION>(0.0) == "0.2 0.3 0.4");
    REQUIRE( entity->getValue<SD_POSITION>(0.0)->at(0) == 0.2);
    REQUIRE( entity->getValue<SD_POSITION>(0.0)->at(1) == 0.3);
    REQUIRE( entity->getValue<SD_POSITION>(0.0)->at(2) == 0.4);

    // SD_ORIENTATION
    entity->addEvent<SD_ORIENTATION>(0.0, {0.5,0.6,0.7});
    REQUIRE( entity->getValueAsString<SD_ORIENTATION>(0.0) == "0.5 0.6 0.7");
    REQUIRE( entity->getValue<SD_ORIENTATION>(0.0)->at(0) == 0.5);
    REQUIRE( entity->getValue<SD_ORIENTATION>(0.0)->at(1) == 0.6);
    REQUIRE( entity->getValue<SD_ORIENTATION>(0.0)->at(2) == 0.7);

    /** core functionalities **/
    /// 4.4.1 media

    // SD_MEDIA_ID
    entity->addEvent<SD_MEDIA_ID>(0.0, "mymedia");
    REQUIRE( entity->getValueAsString<SD_MEDIA_ID>(0.0) == "mymedia");
    REQUIRE( *entity->getValue<SD_MEDIA_ID>(0.0) == "mymedia");

    // SD_MEDIA_TYPE
    entity->addEvent<SD_MEDIA_TYPE>(0.0, "live" );
    REQUIRE( entity->getValueAsString<SD_MEDIA_TYPE>(0.0) == "live");
    REQUIRE( *entity->getValue<SD_MEDIA_TYPE>(0.0) == "live");

    // SD_MEDIA_LOCATION
    entity->addEvent<SD_MEDIA_LOCATION>(0.0, "/path/to/my/file");
    REQUIRE( entity->getValueAsString<SD_MEDIA_LOCATION>(0.0) == "/path/to/my/file");
    REQUIRE( *entity->getValue<SD_MEDIA_LOCATION>(0.0) == "/path/to/my/file");

    // SD_MEDIA_CHANNEL
    entity->addEvent<SD_MEDIA_CHANNEL>(0.0, 2);
    REQUIRE( entity->getValueAsString<SD_MEDIA_CHANNEL>(0.0) == "2");
    REQUIRE( *entity->getValue<SD_MEDIA_CHANNEL>(0.0) == 2);

    // SD_MEDIA_TIME_OFFSET
    entity->addEvent<SD_MEDIA_TIME_OFFSET>(0.0, 20.2);
    REQUIRE( entity->getValueAsString<SD_MEDIA_TIME_OFFSET>(0.0) == "20.2");
    REQUIRE( *entity->getValue<SD_MEDIA_TIME_OFFSET>(0.0) == 20.2);

    // SD_MEDIA_GAIN
    entity->addEvent<SD_MEDIA_GAIN>(0.0, 0.4);
    REQUIRE( entity->getValueAsString<SD_MEDIA_GAIN>(0.0) == "0.4");
    REQUIRE( *entity->getValue<SD_MEDIA_GAIN>(0.0) == 0.4);

    /// 4.4.2 loop

    // SD_LOOP_TYPE
    entity->addEvent<SD_LOOP_TYPE>(0.0, std::make_pair(sdDescriptor<SD_LOOP_TYPE>::SD_REPEAT, 3));
    REQUIRE( entity->getValueAsString<SD_LOOP_TYPE>(0.0) == "repeat 3");
    REQUIRE( entity->getValue<SD_LOOP_TYPE>(0.0)->first == sdDescriptor<SD_LOOP_TYPE>::SD_REPEAT);
    REQUIRE( entity->getValue<SD_LOOP_TYPE>(0.0)->second == 3);

    // SD_LOOP_POINTS
    entity->addEvent<SD_LOOP_POINTS>(0.0, {3,5});
    REQUIRE( entity->getValueAsString<SD_LOOP_POINTS>(0.0) == "3 5");
    REQUIRE( entity->getValue<SD_LOOP_POINTS>(0.0)->at(0) == 3);
    REQUIRE( entity->getValue<SD_LOOP_POINTS>(0.0)->at(1) == 5);

    // SD_LOOP_WAIT_TIME
    entity->addEvent<SD_LOOP_WAIT_TIME>(0.0, 1.0);
    REQUIRE( entity->getValueAsString<SD_LOOP_WAIT_TIME>(0.0) == "1");
    REQUIRE( *entity->getValue<SD_LOOP_WAIT_TIME>(0.0) == 1);

    /// 4.4.3 interpolation
    entity->addEvent<SD_INTERPOLATION_TYPE>(0.0, sdDescriptor<SD_INTERPOLATION_TYPE>::SD_NONE);
    REQUIRE( entity->getValueAsString<SD_INTERPOLATION_TYPE>(0.0) == "none");
    REQUIRE( *entity->getValue<SD_INTERPOLATION_TYPE>(0.0) == sdDescriptor<SD_INTERPOLATION_TYPE>::SD_NONE);

    // SD_SOURCE_SPREAD_SPREAD
    entity->addEvent<SD_SOURCE_SPREAD_SPREAD>(0.0, 0.5);
    REQUIRE( entity->getValueAsString<SD_SOURCE_SPREAD_SPREAD>(0.0) == "0.5");
    REQUIRE( *entity->getValue<SD_SOURCE_SPREAD_SPREAD>(0.0) == 0.5);

    // SD_HARDWARE_OUT_PHYSICAL_CHANNEL
    entity->addEvent<SD_HARDWARE_OUT_PHYSICAL_CHANNEL>(0.5,3);
    REQUIRE(entity->getValue<SD_HARDWARE_OUT_PHYSICAL_CHANNEL>(0.5) == nullptr);

    scene.addExtension(EExtension::SD_HARDWARE_OUT);
    entity->addEvent<SD_HARDWARE_OUT_PHYSICAL_CHANNEL>(0.5,3);
    REQUIRE(*entity->getValue<SD_HARDWARE_OUT_PHYSICAL_CHANNEL>(0.5) == 3);

}
<commit_msg>[TDD] test for hardware out added<commit_after>
#define CATCH_CONFIG_MAIN
#include "catch.hpp"
#include "sdMain.h"
#include <array>
using namespace std;

TEST_CASE("Test all descriptors types"){
    sdScene scene;
    scene.addExtension(EExtension::SD_SOURCE_SPREAD);
    sdEntity * entity = scene.addEntity("MyEntity");

    /*** core ***/
    /// 4.3 core

    // SD_TYPE
    entity->addEvent<SD_TYPE>(0.0, sdDescriptor<SD_TYPE>::EType::SD_LISTENER);
    REQUIRE(entity->getValueAsString<SD_TYPE>(0.0) == "listener");
    REQUIRE(*(entity->getValue<SD_TYPE>(0.0)) == sdDescriptor<SD_TYPE>::SD_LISTENER);

    // SD_PRESENT
    entity->addEvent<SD_PRESENT>(0.0, false);
    REQUIRE(entity->getValueAsString<SD_PRESENT>(0.0) == "false");
    REQUIRE(*(entity->getValue<SD_PRESENT>(0.0)) == false);

    // SD_POSITION
    entity->addEvent<SD_POSITION>(0.0, {0.2,0.3,0.4});
    REQUIRE( entity->getValueAsString<SD_POSITION>(0.0) == "0.2 0.3 0.4");
    REQUIRE( entity->getValue<SD_POSITION>(0.0)->at(0) == 0.2);
    REQUIRE( entity->getValue<SD_POSITION>(0.0)->at(1) == 0.3);
    REQUIRE( entity->getValue<SD_POSITION>(0.0)->at(2) == 0.4);

    // SD_ORIENTATION
    entity->addEvent<SD_ORIENTATION>(0.0, {0.5,0.6,0.7});
    REQUIRE( entity->getValueAsString<SD_ORIENTATION>(0.0) == "0.5 0.6 0.7");
    REQUIRE( entity->getValue<SD_ORIENTATION>(0.0)->at(0) == 0.5);
    REQUIRE( entity->getValue<SD_ORIENTATION>(0.0)->at(1) == 0.6);
    REQUIRE( entity->getValue<SD_ORIENTATION>(0.0)->at(2) == 0.7);

    /** core functionalities **/
    /// 4.4.1 media

    // SD_MEDIA_ID
    entity->addEvent<SD_MEDIA_ID>(0.0, "mymedia");
    REQUIRE( entity->getValueAsString<SD_MEDIA_ID>(0.0) == "mymedia");
    REQUIRE( *entity->getValue<SD_MEDIA_ID>(0.0) == "mymedia");

    // SD_MEDIA_TYPE
    entity->addEvent<SD_MEDIA_TYPE>(0.0, "live" );
    REQUIRE( entity->getValueAsString<SD_MEDIA_TYPE>(0.0) == "live");
    REQUIRE( *entity->getValue<SD_MEDIA_TYPE>(0.0) == "live");

    // SD_MEDIA_LOCATION
    entity->addEvent<SD_MEDIA_LOCATION>(0.0, "/path/to/my/file");
    REQUIRE( entity->getValueAsString<SD_MEDIA_LOCATION>(0.0) == "/path/to/my/file");
    REQUIRE( *entity->getValue<SD_MEDIA_LOCATION>(0.0) == "/path/to/my/file");

    // SD_MEDIA_CHANNEL
    entity->addEvent<SD_MEDIA_CHANNEL>(0.0, 2);
    REQUIRE( entity->getValueAsString<SD_MEDIA_CHANNEL>(0.0) == "2");
    REQUIRE( *entity->getValue<SD_MEDIA_CHANNEL>(0.0) == 2);

    // SD_MEDIA_TIME_OFFSET
    entity->addEvent<SD_MEDIA_TIME_OFFSET>(0.0, 20.2);
    REQUIRE( entity->getValueAsString<SD_MEDIA_TIME_OFFSET>(0.0) == "20.2");
    REQUIRE( *entity->getValue<SD_MEDIA_TIME_OFFSET>(0.0) == 20.2);

    // SD_MEDIA_GAIN
    entity->addEvent<SD_MEDIA_GAIN>(0.0, 0.4);
    REQUIRE( entity->getValueAsString<SD_MEDIA_GAIN>(0.0) == "0.4");
    REQUIRE( *entity->getValue<SD_MEDIA_GAIN>(0.0) == 0.4);

    /// 4.4.2 loop

    // SD_LOOP_TYPE
    entity->addEvent<SD_LOOP_TYPE>(0.0, std::make_pair(sdDescriptor<SD_LOOP_TYPE>::SD_REPEAT, 3));
    REQUIRE( entity->getValueAsString<SD_LOOP_TYPE>(0.0) == "repeat 3");
    REQUIRE( entity->getValue<SD_LOOP_TYPE>(0.0)->first == sdDescriptor<SD_LOOP_TYPE>::SD_REPEAT);
    REQUIRE( entity->getValue<SD_LOOP_TYPE>(0.0)->second == 3);

    // SD_LOOP_POINTS
    entity->addEvent<SD_LOOP_POINTS>(0.0, {3,5});
    REQUIRE( entity->getValueAsString<SD_LOOP_POINTS>(0.0) == "3 5");
    REQUIRE( entity->getValue<SD_LOOP_POINTS>(0.0)->at(0) == 3);
    REQUIRE( entity->getValue<SD_LOOP_POINTS>(0.0)->at(1) == 5);

    // SD_LOOP_WAIT_TIME
    entity->addEvent<SD_LOOP_WAIT_TIME>(0.0, 1.0);
    REQUIRE( entity->getValueAsString<SD_LOOP_WAIT_TIME>(0.0) == "1");
    REQUIRE( *entity->getValue<SD_LOOP_WAIT_TIME>(0.0) == 1);

    /// 4.4.3 interpolation
    entity->addEvent<SD_INTERPOLATION_TYPE>(0.0, sdDescriptor<SD_INTERPOLATION_TYPE>::SD_NONE);
    REQUIRE( entity->getValueAsString<SD_INTERPOLATION_TYPE>(0.0) == "none");
    REQUIRE( *entity->getValue<SD_INTERPOLATION_TYPE>(0.0) == sdDescriptor<SD_INTERPOLATION_TYPE>::SD_NONE);

    // SD_SOURCE_SPREAD_SPREAD
    entity->addEvent<SD_SOURCE_SPREAD_SPREAD>(0.0, 0.5);
    REQUIRE( entity->getValueAsString<SD_SOURCE_SPREAD_SPREAD>(0.0) == "0.5");
    REQUIRE( *entity->getValue<SD_SOURCE_SPREAD_SPREAD>(0.0) == 0.5);

    // SD_HARDWARE_OUT_PHYSICAL_CHANNEL

}

TEST_CASE("hardware out extension"){
    sdScene scene;
    scene.addExtension(EExtension::SD_SINK_ENTITY);
    scene.addExtension(EExtension::SD_HARDWARE_OUT);

    auto leftSpeaker = scene.addEntity("JBL-Left", EKind::SD_SINK);
    auto rightSpeaker = scene.addEntity("JBL-Right", EKind::SD_SINK);

    // physical channel
    leftSpeaker->addMeta<SD_HARDWARE_OUT_PHYSICAL_CHANNEL>(10);
    REQUIRE(leftSpeaker->getValueAsString<SD_HARDWARE_OUT_PHYSICAL_CHANNEL>() == "10");
    REQUIRE(*leftSpeaker->getValue<SD_HARDWARE_OUT_PHYSICAL_CHANNEL>() == 10);

    rightSpeaker->addEvent("1.0", "hardware-out", "physical-channel",  "11");
    REQUIRE(rightSpeaker->getValueAsString<SD_HARDWARE_OUT_PHYSICAL_CHANNEL>(1.0) == "11");
    REQUIRE(*rightSpeaker->getValue<SD_HARDWARE_OUT_PHYSICAL_CHANNEL>(1.0) == 11);

    // gain
    leftSpeaker->addMeta<SD_HARDWARE_OUT_GAIN>(0.5);
    REQUIRE(leftSpeaker->getValueAsString<SD_HARDWARE_OUT_GAIN>() == "0.5");
    REQUIRE(*leftSpeaker->getValue<SD_HARDWARE_OUT_GAIN>() == 0.5);

    rightSpeaker->addEvent("1.0", "hardware-out", "gain",  "0.6");
    REQUIRE(rightSpeaker->getValueAsString<SD_HARDWARE_OUT_GAIN>(1.0) == "0.6");
    REQUIRE(*rightSpeaker->getValue<SD_HARDWARE_OUT_GAIN>(1.0) == 0.6);

}
<|endoftext|>


<commit_before>// Time:  O(k * log(min(m, n)))
// Space: O(min(m, n))

// BST solution.
class Solution {
public:
    /**
     * @param matrix: a matrix of integers
     * @param k: an integer
     * @return: the kth smallest number in the matrix
     */
    int kthSmallest(vector<vector<int> > &matrix, int k) {
        multimap<int, pair<int, int>> min_bst;
        int kth_smallest = 0;

        // Find min number of height and width
        if (matrix.size() < matrix[0].size()) {
            // Init BST by the first element of each row.
            for (int i = 0; i < matrix.size(); ++i) {
                min_bst.emplace(move(pair<int, pair<int, int>>{matrix[i][0], {i, 0}}));
            }

            while (k--) {
                // Pop the min of BST.
                kth_smallest = min_bst.cbegin()->first;
                int i = min_bst.cbegin()->second.first;
                int j = min_bst.cbegin()->second.second;
                min_bst.erase(min_bst.cbegin());

                // Insert the next possible element.
                if (j + 1 < matrix[i].size()) {
                    min_bst.emplace(move(pair<int, pair<int, int>>{matrix[i][j + 1], {i, j + 1}}));
                }
            }
        } else {
            // Init BST by the first element of each column.
            for (int j = 0; j < matrix[0].size(); ++j) {
                min_bst.emplace(move(pair<int, pair<int, int>>{matrix[0][j], {0, j}}));
            }

            while (k--) {
                // Pop the min of BST.
                kth_smallest = min_bst.cbegin()->first;
                int i = min_bst.cbegin()->second.first;
                int j = min_bst.cbegin()->second.second;
                min_bst.erase(min_bst.cbegin());

                // Insert the next possible element.
                if (i + 1 < matrix.size()) {
                    min_bst.emplace(move(pair<int, pair<int, int>>{matrix[i + 1][j], {i + 1, j}}));
                }
            }
        }

        return kth_smallest;
    }
};

// Time:  O(k * log(min(m, n)))
// Space: O(min(m, n))

// Heap solution.
class Solution {
public:
    struct Compare {
        bool operator()(const pair<int, pair<int, int>>& a, const pair<int, pair<int, int>>& b) {
            return a.first > b.first;
        }
    };
    /**
     * @param matrix: a matrix of integers
     * @param k: an integer
     * @return: the kth smallest number in the matrix
     */
    int kthSmallest(vector<vector<int> > &matrix, int k) {
        priority_queue<pair<int, pair<int, int>>, vector<pair<int, pair<int, int>>>, Compare> min_heap;
        int kth_smallest = 0;

        // Find min number of height and width
        if (matrix.size() < matrix[0].size()) {
            // Init Heap by the first element of each row.
            for (int i = 0; i < matrix.size(); ++i) {
                min_heap.emplace(move(pair<int, pair<int, int>>{matrix[i][0], {i, 0}}));
            }

            while (k--) {
                // Pop the min of Heap.
                kth_smallest = min_heap.top().first;
                int i = min_heap.top().second.first;
                int j = min_heap.top().second.second;
                min_heap.pop();

                // Insert the next possible element.
                if (j + 1 < matrix[i].size()) {
                    min_heap.emplace(move(pair<int, pair<int, int>>{matrix[i][j + 1], {i, j + 1}}));
                }
            }
        } else {
            // Init Heap by the first element of each column.
            for (int j = 0; j < matrix[0].size(); ++j) {
                min_heap.emplace(move(pair<int, pair<int, int>>{matrix[0][j], {0, j}}));
            }

            while (k--) {
                // Pop the min of Heap.
                kth_smallest = min_heap.top().first;
                int i = min_heap.top().second.first;
                int j = min_heap.top().second.second;
                min_heap.pop();

                // Insert the next possible element.
                if (i + 1 < matrix.size()) {
                    min_heap.emplace(move(pair<int, pair<int, int>>{matrix[i + 1][j], {i + 1, j}}));
                }
            }
        }

        return kth_smallest;
    }
};
<commit_msg>Update kth-smallest-number-in-sorted-matrix.cpp<commit_after>// Time:  O(k * log(min(m, n)))
// Space: O(min(m, n))

// BST solution.
class Solution {
public:
    /**
     * @param matrix: a matrix of integers
     * @param k: an integer
     * @return: the kth smallest number in the matrix
     */
    int kthSmallest(vector<vector<int> > &matrix, int k) {
        multimap<int, pair<int, int>> min_bst;
        int kth_smallest = 0;

        // Find min number of height and width
        if (matrix.size() < matrix[0].size()) {
            // Init BST by the first element of each row.
            for (int i = 0; i < matrix.size(); ++i) {
                min_bst.emplace(move(pair<int, pair<int, int>>{matrix[i][0], {i, 0}}));
            }

            while (k--) {
                // Pop the min of BST.
                kth_smallest = min_bst.cbegin()->first;
                int i = min_bst.cbegin()->second.first;
                int j = min_bst.cbegin()->second.second;
                min_bst.erase(min_bst.cbegin());

                // Insert the next possible element.
                if (j + 1 < matrix[i].size()) {
                    min_bst.emplace(move(pair<int, pair<int, int>>{matrix[i][j + 1], {i, j + 1}}));
                }
            }
        } else {
            // Init BST by the first element of each column.
            for (int j = 0; j < matrix[0].size(); ++j) {
                min_bst.emplace(move(pair<int, pair<int, int>>{matrix[0][j], {0, j}}));
            }

            while (k--) {
                // Pop the min of BST.
                kth_smallest = min_bst.cbegin()->first;
                int i = min_bst.cbegin()->second.first;
                int j = min_bst.cbegin()->second.second;
                min_bst.erase(min_bst.cbegin());

                // Insert the next possible element.
                if (i + 1 < matrix.size()) {
                    min_bst.emplace(move(pair<int, pair<int, int>>{matrix[i + 1][j], {i + 1, j}}));
                }
            }
        }

        return kth_smallest;
    }
};

// Time:  O(k * log(min(m, n)))
// Space: O(min(m, n))
// Heap solution.
class Solution {
public:
    struct Compare {
        bool operator()(const pair<int, pair<int, int>>& a, const pair<int, pair<int, int>>& b) {
            return a.first > b.first;
        }
    };
    /**
     * @param matrix: a matrix of integers
     * @param k: an integer
     * @return: the kth smallest number in the matrix
     */
    int kthSmallest(vector<vector<int> > &matrix, int k) {
        priority_queue<pair<int, pair<int, int>>, vector<pair<int, pair<int, int>>>, Compare> min_heap;
        int kth_smallest = 0;

        // Find min number of height and width
        if (matrix.size() < matrix[0].size()) {
            // Init Heap by the first element of each row.
            for (int i = 0; i < matrix.size(); ++i) {
                min_heap.emplace(move(pair<int, pair<int, int>>{matrix[i][0], {i, 0}}));
            }

            while (k--) {
                // Pop the min of Heap.
                kth_smallest = min_heap.top().first;
                int i = min_heap.top().second.first;
                int j = min_heap.top().second.second;
                min_heap.pop();

                // Insert the next possible element.
                if (j + 1 < matrix[i].size()) {
                    min_heap.emplace(move(pair<int, pair<int, int>>{matrix[i][j + 1], {i, j + 1}}));
                }
            }
        } else {
            // Init Heap by the first element of each column.
            for (int j = 0; j < matrix[0].size(); ++j) {
                min_heap.emplace(move(pair<int, pair<int, int>>{matrix[0][j], {0, j}}));
            }

            while (k--) {
                // Pop the min of Heap.
                kth_smallest = min_heap.top().first;
                int i = min_heap.top().second.first;
                int j = min_heap.top().second.second;
                min_heap.pop();

                // Insert the next possible element.
                if (i + 1 < matrix.size()) {
                    min_heap.emplace(move(pair<int, pair<int, int>>{matrix[i + 1][j], {i + 1, j}}));
                }
            }
        }

        return kth_smallest;
    }
};
<|endoftext|>


<commit_before>/*
 * EMULAB-COPYRIGHT
 * Copyright (c) 2005-2006 University of Utah and the Flux Group.
 * All rights reserved.
 */

/*
 * A set of functions useful for exploring the neighborhood of a particular
 * solution.
 */

static const char rcsid[] = "$Id: neighborhood.cc,v 1.4 2009-05-20 18:06:08 tarunp Exp $";

#include "neighborhood.h"

// From asssign.cc
extern bool allow_overload;
#ifdef PER_VNODE_TT
extern pclass_types vnode_type_table;
#endif

/*
 * This overly-verbose function returns true if it's okay to map vn to pn,
 * false otherwise
 */
inline bool pnode_is_match(tb_vnode *vn, tb_pnode *pn) {
  // Find the type record for this type
  tb_pnode::types_map::iterator mit = pn->types.find(vn->type);
  if (mit == pn->types.end()) {
    // The node doesn't even have this type, we can exit early
    return false;
  }

  bool matched = false;
  tb_pnode::type_record *tr = mit->second;
  if (tr->is_static()) {
    if ((tr->get_current_load() + vn->typecount) > tr->get_max_load()) {
      // This would put us over its max load
      if (allow_overload && (tr->get_max_load() > 1)) {
	// That's okay, we're allowing overload
	matched = true;
      } else {
	// Nope, it's full
	matched = false;
      }
    } else {
      // Plenty of room for us
      matched = true;
    }
  } else { // the type is not static
    if (pn->typed) {
      if (pn->current_type != vn->type) {
	// Failure - the pnode has a type, and it isn't ours
	matched = false;
      } else {
	if ((pn->current_type_record->get_current_load() + vn->typecount) >
	    pn->current_type_record->get_max_load()) {
	  // This would put us over its max load
	  //if (allow_overload && (tr->max_load > 1) &&
	  //    ((pn->current_type_record->current_load + vn->typecount) <
	  //    (pn->current_type_record->max_load + 2))) {
	  if (allow_overload && (tr->get_max_load() > 1)) {
	    // That's okay, we're allowing overload
	    matched = true;
	  } else {
	    // Failure - the type is right, but the pnode is full
	    matched = false;
	  }
	} else {
	  // It's under its max load, we can fit in
	  matched = true;
	}
      }
    } else {
      // pnode doesn't have a type
      matched = true;
    }
  }

  // Commented out for now because it's too slow!
#if 0
  // Check for 'local' desires - the reason we take the time to do this here is
  // that they are actually, in many ways, like types with vn->typecount > 1.
  if (matched && !vn->desires.empty()) {
    tb_vnode::desires_map::iterator desire_it;
    for (desire_it = vn->desires.begin();
	desire_it != vn->desires.end();
	desire_it++) {
      if (desire_it->is_l_additive()) {
	  tb_pnode::features_map::iterator feature_it =
	      pn->features.find(desire_it->first);
	  if (feature_it == pn->features.end()) {
	      matched = false;
	      break;
	  }
	  // If we are allowing overloading, do so only to a limited degree
	  if (allow_overload) {
	      if ((feature_it->second < desire_it->second)
		  && (feature_it->second - desire_it->second)
		  < (desire_it->second * 2)) {
		      matched = false;
		      break;
		  }
	  } else {
	      // No overloading, and this would put us over the limit
	      if (feature_it->second < desire_it->second) {
		  matched = false;
		  break;
	      }
	  }
      }
  }
  }
#endif

  return matched;
}

/*
 * Finds a pnode which:
 * 1) One of the vnode's neighbors is mapped to
 * 2) Satisifies the usual pnode mapping constraints
 * 3) The vnode is not already mapped to
 */
tb_pnode *find_pnode_connected(vvertex vv, tb_vnode *vn) {

  //cerr << "find_pnode_connected(" << vn->name << ") called" << endl;

  // We make a list of all neighboring vnodes so that we can go through
  // them in random order
  vector<vedge> visit_order(out_degree(vv,VG));
  voedge_iterator vedge_it,end_vedge_it;
  tie(vedge_it,end_vedge_it) = out_edges(vv,VG);
  for (int i = 0; vedge_it != end_vedge_it; vedge_it++, i++) {
    visit_order[i] = *vedge_it;
  }
  for (size_t i = 0; i < visit_order.size(); i++) {
	int i1 = RANDOM() % visit_order.size();
	int i2 = RANDOM() % visit_order.size();
	vedge tmp = visit_order[i1];
	visit_order[i1] = visit_order[i2];
	visit_order[i2] = tmp;
  }
  for (size_t i = 0; i < visit_order.size(); i++) {
    vvertex neighbor_vv = target(visit_order[i],VG);
    tb_vnode *neighbor_vn = get(vvertex_pmap,neighbor_vv);
    //cerr << "    trying " << neighbor_vn->name << endl;
    // Skip any that aren't assigned
    if (!neighbor_vn->assigned) {
      //cerr << "        not assigned" << endl;
      continue;
    }

    // Skip any that are assigned to the same pnode we are
    if (neighbor_vn->assignment == vn->assignment) {
      //cerr << "        same assignment" << endl;
      continue;
    }

    // Check to make sure that our vn can map to the neibor's assigment
    tb_pnode *neighbor_pnode = get(pvertex_pmap,neighbor_vn->assignment);
    //cerr << "        neighbor on " << neighbor_pnode->name << endl;
    if (pnode_is_match(vn,neighbor_pnode)) {
      //cerr << "        good" << endl;
      //cerr << "    worked" << endl;
      return neighbor_pnode;
    }
    //cerr << "        doesn't match" << endl;
  }

  //cerr << "    failed" << endl;
  return NULL;
}

tb_pnode *find_pnode(tb_vnode *vn)
{
#ifdef PER_VNODE_TT
  tt_entry tt = vnode_type_table[vn->name];
#else
  tt_entry tt = type_table[vn->type];
#endif
  int num_types = tt.first;
  pclass_vector *acceptable_types = tt.second;

  tb_pnode *newpnode = NULL;

  //cerr << "Node is " << vn->name << " First = " << first << endl;

  // Randomize the order in which we go through the list of acceptable pclasses
  // We do this by making a randomly-ordered list of indicies into the
  // acceptable_types vector
  vector<int> traversal_order(num_types);
  for (int i = 0; i < num_types; i++) {
	traversal_order[i] = i;
  }
  for (int i = 0; i < num_types; i++) {
	int i1 = RANDOM() % num_types;
	int i2 = RANDOM() % num_types;
	int tmp = traversal_order[i1];
	traversal_order[i1] = traversal_order[i2];
	traversal_order[i2] = tmp;
  }

  for (int i = 0; i < num_types; i++) {

    int index = traversal_order[i];
    tb_pclass *pclass = (*acceptable_types)[index];

    // Skip pclasses that have been disabled
    if (pclass->disabled) {
	  continue;
    }

#ifndef FIND_PNODE_SEARCH
    // If not searching for the pnode, just grab the front one
    newpnode = pclass->members[vn->type]->front();
#else
#ifdef PER_VNODE_TT
    // If using PER_VNODE_TT and vclasses, it's possible that there are
    // some pclasses in this node's type table that can't be used right now,
    // becuase they contain entires that don't contain the vnodes _current_
    // type
    if (pclass->members.find(vn->type) == pclass->members.end()) {
	continue;
    }
#endif

    list<tb_pnode*>::iterator it = pclass->members[vn->type]->L.begin();
    while (it != pclass->members[vn->type]->L.end()) {
	if (pnode_is_match(vn,*it)) {
	    break;
	} else {
	    it++;
	}
    }
    if (it == pclass->members[vn->type]->L.end()) {
	newpnode = NULL;
    } else {
	newpnode = *it;
    }
#endif // FIND_PNODE_SEARCH
#ifdef PCLASS_DEBUG
    cerr << "Found pclass: " <<
      pclass->name << " and node " <<
      (newpnode == NULL ? "NULL" : newpnode->name) << "\n";
#endif
    if (newpnode != NULL) {
      RDEBUG(cout << " to " << newpnode->name << endl;)
      return newpnode;
    }
  }

  // Nope, didn't find one
  return NULL;
}
<commit_msg>Add some debugging statements<commit_after>/*
 * EMULAB-COPYRIGHT
 * Copyright (c) 2005-2006 University of Utah and the Flux Group.
 * All rights reserved.
 */

/*
 * A set of functions useful for exploring the neighborhood of a particular
 * solution.
 */

static const char rcsid[] = "$Id: neighborhood.cc,v 1.4 2009-05-20 18:06:08 tarunp Exp $";

#include "neighborhood.h"

// From asssign.cc
extern bool allow_overload;
#ifdef PER_VNODE_TT
extern pclass_types vnode_type_table;
#endif

/*
 * This overly-verbose function returns true if it's okay to map vn to pn,
 * false otherwise
 */
inline bool pnode_is_match(tb_vnode *vn, tb_pnode *pn) {
  // Find the type record for this type
  tb_pnode::types_map::iterator mit = pn->types.find(vn->type);
  if (mit == pn->types.end()) {
    // The node doesn't even have this type, we can exit early
    return false;
  }

  bool matched = false;
  tb_pnode::type_record *tr = mit->second;
  if (tr->is_static()) {
    if ((tr->get_current_load() + vn->typecount) > tr->get_max_load()) {
      // This would put us over its max load
      if (allow_overload && (tr->get_max_load() > 1)) {
	// That's okay, we're allowing overload
	matched = true;
      } else {
	// Nope, it's full
	matched = false;
      }
    } else {
      // Plenty of room for us
      matched = true;
    }
  } else { // the type is not static
    if (pn->typed) {
      if (pn->current_type != vn->type) {
	// Failure - the pnode has a type, and it isn't ours
	matched = false;
      } else {
	if ((pn->current_type_record->get_current_load() + vn->typecount) >
	    pn->current_type_record->get_max_load()) {
	  // This would put us over its max load
	  //if (allow_overload && (tr->max_load > 1) &&
	  //    ((pn->current_type_record->current_load + vn->typecount) <
	  //    (pn->current_type_record->max_load + 2))) {
	  if (allow_overload && (tr->get_max_load() > 1)) {
	    // That's okay, we're allowing overload
	    matched = true;
	  } else {
	    // Failure - the type is right, but the pnode is full
	    matched = false;
	  }
	} else {
	  // It's under its max load, we can fit in
	  matched = true;
	}
      }
    } else {
      // pnode doesn't have a type
      matched = true;
    }
  }

  // Commented out for now because it's too slow!
#if 0
  // Check for 'local' desires - the reason we take the time to do this here is
  // that they are actually, in many ways, like types with vn->typecount > 1.
  if (matched && !vn->desires.empty()) {
    tb_vnode::desires_map::iterator desire_it;
    for (desire_it = vn->desires.begin();
	desire_it != vn->desires.end();
	desire_it++) {
      if (desire_it->is_l_additive()) {
	  tb_pnode::features_map::iterator feature_it =
	      pn->features.find(desire_it->first);
	  if (feature_it == pn->features.end()) {
	      matched = false;
	      break;
	  }
	  // If we are allowing overloading, do so only to a limited degree
	  if (allow_overload) {
	      if ((feature_it->second < desire_it->second)
		  && (feature_it->second - desire_it->second)
		  < (desire_it->second * 2)) {
		      matched = false;
		      break;
		  }
	  } else {
	      // No overloading, and this would put us over the limit
	      if (feature_it->second < desire_it->second) {
		  matched = false;
		  break;
	      }
	  }
      }
  }
  }
#endif

  return matched;
}

/*
 * Finds a pnode which:
 * 1) One of the vnode's neighbors is mapped to
 * 2) Satisifies the usual pnode mapping constraints
 * 3) The vnode is not already mapped to
 */
tb_pnode *find_pnode_connected(vvertex vv, tb_vnode *vn) {

  //cerr << "find_pnode_connected(" << vn->name << ") called" << endl;

  // We make a list of all neighboring vnodes so that we can go through
  // them in random order
  vector<vedge> visit_order(out_degree(vv,VG));
  voedge_iterator vedge_it,end_vedge_it;
  tie(vedge_it,end_vedge_it) = out_edges(vv,VG);
  for (int i = 0; vedge_it != end_vedge_it; vedge_it++, i++) {
    visit_order[i] = *vedge_it;
  }
  for (size_t i = 0; i < visit_order.size(); i++) {
	int i1 = RANDOM() % visit_order.size();
	int i2 = RANDOM() % visit_order.size();
	vedge tmp = visit_order[i1];
	visit_order[i1] = visit_order[i2];
	visit_order[i2] = tmp;
  }
  for (size_t i = 0; i < visit_order.size(); i++) {
    vvertex neighbor_vv = target(visit_order[i],VG);
    tb_vnode *neighbor_vn = get(vvertex_pmap,neighbor_vv);
    //cerr << "    trying " << neighbor_vn->name << endl;
    // Skip any that aren't assigned
    if (!neighbor_vn->assigned) {
      //cerr << "        not assigned" << endl;
      continue;
    }

    // Skip any that are assigned to the same pnode we are
    if (neighbor_vn->assignment == vn->assignment) {
      //cerr << "        same assignment" << endl;
      continue;
    }

    // Check to make sure that our vn can map to the neibor's assigment
    tb_pnode *neighbor_pnode = get(pvertex_pmap,neighbor_vn->assignment);
    //cerr << "        neighbor on " << neighbor_pnode->name << endl;
    if (pnode_is_match(vn,neighbor_pnode)) {
      //cerr << "        good" << endl;
      //cerr << "    worked" << endl;
      return neighbor_pnode;
    }
    //cerr << "        doesn't match" << endl;
  }

  //cerr << "    failed" << endl;
  return NULL;
}

tb_pnode *find_pnode(tb_vnode *vn)
{
#ifdef PER_VNODE_TT
  tt_entry tt = vnode_type_table[vn->name];
#else
  tt_entry tt = type_table[vn->type];
#endif
  int num_types = tt.first;
  pclass_vector *acceptable_types = tt.second;

  tb_pnode *newpnode = NULL;

  //cerr << "Node is " << vn->name << " First = " << first << endl;

  // Randomize the order in which we go through the list of acceptable pclasses
  // We do this by making a randomly-ordered list of indicies into the
  // acceptable_types vector
  vector<int> traversal_order(num_types);
  for (int i = 0; i < num_types; i++) {
	traversal_order[i] = i;
  }
  for (int i = 0; i < num_types; i++) {
	int i1 = RANDOM() % num_types;
	int i2 = RANDOM() % num_types;
	int tmp = traversal_order[i1];
	traversal_order[i1] = traversal_order[i2];
	traversal_order[i2] = tmp;
  }

  for (int i = 0; i < num_types; i++) {

    int index = traversal_order[i];
    tb_pclass *pclass = (*acceptable_types)[index];

    // Skip pclasses that have been disabled
    if (pclass->disabled) {
	  continue;
    }

#ifndef FIND_PNODE_SEARCH
    // If not searching for the pnode, just grab the front one
    newpnode = pclass->members[vn->type]->front();
#else
#ifdef PER_VNODE_TT
    // If using PER_VNODE_TT and vclasses, it's possible that there are
    // some pclasses in this node's type table that can't be used right now,
    // becuase they contain entires that don't contain the vnodes _current_
    // type
    if (pclass->members.find(vn->type) == pclass->members.end()) {
	continue;
    }
#endif

    RDEBUG(cout << "find_pnode: Members list has " <<
            pclass->members[vn->type]->L.size() << " type is " << vn->type <<
            endl;)
    list<tb_pnode*>::iterator it = pclass->members[vn->type]->L.begin();
    while (it != pclass->members[vn->type]->L.end()) {
	if (pnode_is_match(vn,*it)) {
	    break;
	} else {
	    it++;
	}
    }
    if (it == pclass->members[vn->type]->L.end()) {
	newpnode = NULL;
    } else {
	newpnode = *it;
    }
#endif // FIND_PNODE_SEARCH
#ifdef PCLASS_DEBUG
    cerr << "Found pclass: " <<
      pclass->name << " and node " <<
      (newpnode == NULL ? "NULL" : newpnode->name) << "\n";
#endif
    if (newpnode != NULL) {
      RDEBUG(cout << " to " << newpnode->name << endl;)
      return newpnode;
    }
  }

  // Nope, didn't find one
  return NULL;
}
<|endoftext|>


<commit_before>/****************************************************************************
**
** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies).
** All rights reserved.
** Contact: Nokia Corporation (qt-info@nokia.com)
**
** This file is part of the test suite of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:LGPL$
** No Commercial Usage
** This file contains pre-release code and may not be distributed.
** You may use this file in accordance with the terms and conditions
** contained in the Technology Preview License Agreement accompanying
** this package.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file.  Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Nokia gives you certain additional
** rights.  These rights are described in the Nokia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** If you have questions regarding the use of this file, please contact
** Nokia at qt-info@nokia.com.
**
**
**
**
**
**
**
**
** $QT_END_LICENSE$
**
****************************************************************************/
#include <qtest.h>
#include "../../../shared/util.h"
#include <QtDeclarative/qmlengine.h>
#include <QtDeclarative/qmlcomponent.h>
#include <private/qmlgraphicswebview_p.h>
#include <private/qmlgraphicspositioners_p.h>
#include <QtWebKit/qwebpage.h>
#include <QtWebKit/qwebframe.h>
#include <QtCore/qdir.h>
#include <QtCore/qfile.h>

class tst_qmlgraphicswebview : public QObject
{
    Q_OBJECT
public:
    tst_qmlgraphicswebview() {}

private slots:
    void basicProperties();
    void historyNav();
    void multipleWindows();
    void loadError();
    void setHtml();
    void javaScript();
    void cleanupTestCase();

private:
    void checkNoErrors(const QmlComponent& component);
    QmlEngine engine;
    QString tmpDir() const
    {
        static QString tmpd = QDir::tempPath()+"/tst_qmlgraphicswebview-"
            + QDateTime::currentDateTime().toString(QLatin1String("yyyyMMddhhmmss"));
        return tmpd;
    }
};

static QString strippedHtml(QString html)
{
    html.replace(QRegExp("\\s+"),"");
    return html;
}

static QString fileContents(const QString& filename)
{
    QFile file(filename);
    Q_ASSERT(file.open(QIODevice::ReadOnly));
    return file.readAll();
}

static void removeRecursive(const QString& dirname)
{
    QDir dir(dirname);
    QFileInfoList entries(dir.entryInfoList(QDir::Dirs|QDir::Files|QDir::NoDotAndDotDot));
    for (int i = 0; i < entries.count(); ++i)
        if (entries[i].isDir())
            removeRecursive(entries[i].filePath());
        else
            dir.remove(entries[i].fileName());
    QDir().rmdir(dirname);
}

void tst_qmlgraphicswebview::cleanupTestCase()
{
    removeRecursive(tmpDir());
}

void tst_qmlgraphicswebview::checkNoErrors(const QmlComponent& component)
{
    if (component.isError()) {
        QList<QmlError> errors = component.errors();
        for (int ii = 0; ii < errors.count(); ++ii) {
            const QmlError &error = errors.at(ii);
            QByteArray errorStr = QByteArray::number(error.line()) + ":" +
                                  QByteArray::number(error.column()) + ":" +
                                  error.description().toUtf8();
            qWarning() << errorStr;
        }
    }
    QVERIFY(!component.isError());
}

void tst_qmlgraphicswebview::basicProperties()
{
    QmlComponent component(&engine, QUrl::fromLocalFile(SRCDIR "/data/basic.qml"));
    checkNoErrors(component);
    QWebSettings::enablePersistentStorage(tmpDir());

    QmlGraphicsWebView *wv = qobject_cast<QmlGraphicsWebView*>(component.create());
    QVERIFY(wv != 0);
    QTRY_COMPARE(wv->progress(), 1.0);
    QCOMPARE(wv->title(),QString("Basic"));
    QTRY_COMPARE(wv->icon().width(), 48);
    QCOMPARE(wv->icon(),QPixmap(SRCDIR "/data/basic.png"));
    QCOMPARE(wv->statusText(),QString("status here"));
    QCOMPARE(strippedHtml(fileContents(SRCDIR "/data/basic.html")), strippedHtml(wv->html()));
    QCOMPARE(wv->width(), 123.0);
    QCOMPARE(wv->preferredWidth(), 0);
    QCOMPARE(wv->zoomFactor(), 1.0);
    QCOMPARE(wv->url(), QUrl::fromLocalFile(SRCDIR "/data/basic.html"));
    QCOMPARE(wv->status(), QmlGraphicsWebView::Ready);
    QVERIFY(wv->reloadAction());
    QVERIFY(wv->reloadAction()->isEnabled());
    QVERIFY(wv->backAction());
    QVERIFY(!wv->backAction()->isEnabled());
    QVERIFY(wv->forwardAction());
    QVERIFY(!wv->forwardAction()->isEnabled());
    QVERIFY(wv->stopAction());
    QVERIFY(!wv->stopAction()->isEnabled());

    wv->setPixelCacheSize(0); // mainly testing that it doesn't crash or anything!
    QCOMPARE(wv->pixelCacheSize(),0);
    wv->reloadAction()->trigger();
    QTRY_COMPARE(wv->progress(), 1.0);
}

void tst_qmlgraphicswebview::historyNav()
{
    QmlComponent component(&engine, QUrl::fromLocalFile(SRCDIR "/data/basic.qml"));
    checkNoErrors(component);
    QWebSettings::enablePersistentStorage(tmpDir());

    QmlGraphicsWebView *wv = qobject_cast<QmlGraphicsWebView*>(component.create());
    QVERIFY(wv != 0);
    for (int i=1; i<=2; ++i) {
        QTRY_COMPARE(wv->progress(), 1.0);
        QCOMPARE(wv->title(),QString("Basic"));
        QTRY_COMPARE(wv->icon().width(), 48);
        QCOMPARE(wv->icon(),QPixmap(SRCDIR "/data/basic.png"));
        QCOMPARE(wv->statusText(),QString("status here"));
        QCOMPARE(strippedHtml(fileContents(SRCDIR "/data/basic.html")), strippedHtml(wv->html()));
        QCOMPARE(wv->width(), 123.0);
        QCOMPARE(wv->preferredWidth(), 0);
        QCOMPARE(wv->zoomFactor(), 1.0);
        QCOMPARE(wv->url(), QUrl::fromLocalFile(SRCDIR "/data/basic.html"));
        QCOMPARE(wv->status(), QmlGraphicsWebView::Ready);
        QVERIFY(wv->reloadAction());
        QVERIFY(wv->reloadAction()->isEnabled());
        QVERIFY(wv->backAction());
        QVERIFY(!wv->backAction()->isEnabled());
        QVERIFY(wv->forwardAction());
        QVERIFY(!wv->forwardAction()->isEnabled());
        QVERIFY(wv->stopAction());
        QVERIFY(!wv->stopAction()->isEnabled());

        wv->reloadAction()->trigger();
    }

    wv->setUrl(QUrl::fromLocalFile(SRCDIR "/data/forward.html"));
    QTRY_COMPARE(wv->progress(), 1.0);
    QCOMPARE(wv->title(),QString("Forward"));
    QCOMPARE(strippedHtml(fileContents(SRCDIR "/data/forward.html")), strippedHtml(wv->html()));
    QCOMPARE(wv->url(), QUrl::fromLocalFile(SRCDIR "/data/forward.html"));
    QCOMPARE(wv->status(), QmlGraphicsWebView::Ready);
    QCOMPARE(wv->statusText(),QString(""));
    QVERIFY(wv->reloadAction());
    QVERIFY(wv->reloadAction()->isEnabled());
    QVERIFY(wv->backAction());
    QVERIFY(wv->backAction()->isEnabled());
    QVERIFY(wv->forwardAction());
    QVERIFY(!wv->forwardAction()->isEnabled());
    QVERIFY(wv->stopAction());
    QVERIFY(!wv->stopAction()->isEnabled());

    wv->backAction()->trigger();

    QTRY_COMPARE(wv->progress(), 1.0);
    QCOMPARE(wv->title(),QString("Basic"));
    QCOMPARE(strippedHtml(fileContents(SRCDIR "/data/basic.html")), strippedHtml(wv->html()));
    QCOMPARE(wv->url(), QUrl::fromLocalFile(SRCDIR "/data/basic.html"));
    QCOMPARE(wv->status(), QmlGraphicsWebView::Ready);
    QVERIFY(wv->reloadAction());
    QVERIFY(wv->reloadAction()->isEnabled());
    QVERIFY(wv->backAction());
    QVERIFY(!wv->backAction()->isEnabled());
    QVERIFY(wv->forwardAction());
    QVERIFY(wv->forwardAction()->isEnabled());
    QVERIFY(wv->stopAction());
    QVERIFY(!wv->stopAction()->isEnabled());
}

void tst_qmlgraphicswebview::multipleWindows()
{
    QmlComponent component(&engine, QUrl::fromLocalFile(SRCDIR "/data/newwindows.qml"));
    checkNoErrors(component);

    QmlGraphicsGrid *grid = qobject_cast<QmlGraphicsGrid*>(component.create());
    QVERIFY(grid != 0);
    QTRY_COMPARE(grid->children().count(), 2+5); // Component, Loader, 5 WebViews
}

void tst_qmlgraphicswebview::loadError()
{
    QmlComponent component(&engine, QUrl::fromLocalFile(SRCDIR "/data/loadError.qml"));
    checkNoErrors(component);
    QWebSettings::enablePersistentStorage(tmpDir());

    QmlGraphicsWebView *wv = qobject_cast<QmlGraphicsWebView*>(component.create());
    QVERIFY(wv != 0);
    for (int i=1; i<=2; ++i) {
        QTRY_COMPARE(wv->progress(), 1.0);
        QCOMPARE(wv->title(),QString(""));
        QCOMPARE(wv->statusText(),QString("")); // HTML 'status bar' text, not error message
        QCOMPARE(wv->url(), QUrl::fromLocalFile(SRCDIR "/data/does-not-exist.html")); // Unlike QWebPage, which loses url
        QCOMPARE(wv->status(), QmlGraphicsWebView::Error);

        wv->reloadAction()->trigger();
    }
}

void tst_qmlgraphicswebview::setHtml()
{
    QmlComponent component(&engine, QUrl::fromLocalFile(SRCDIR "/data/sethtml.qml"));
    checkNoErrors(component);
    QmlGraphicsWebView *wv = qobject_cast<QmlGraphicsWebView*>(component.create());
    QVERIFY(wv != 0);
    QCOMPARE(wv->html(),QString("
This is a string set on the WebView
"));
}

void tst_qmlgraphicswebview::javaScript()
{
    QmlComponent component(&engine, QUrl::fromLocalFile(SRCDIR "/data/javaScript.qml"));
    checkNoErrors(component);
    QmlGraphicsWebView *wv = qobject_cast<QmlGraphicsWebView*>(component.create());
    QVERIFY(wv != 0);
    QTRY_COMPARE(wv->progress(), 1.0);
    QCOMPARE(wv->evaluateJavaScript("123").toInt(), 123);
    QCOMPARE(wv->evaluateJavaScript("window.status").toString(), QString("status here"));
    QCOMPARE(wv->evaluateJavaScript("window.myjsname.qmlprop").toString(), QString("qmlvalue"));
}

QTEST_MAIN(tst_qmlgraphicswebview)

#include "tst_qmlgraphicswebview.moc"
<commit_msg>test elementAreaAt<commit_after>/****************************************************************************
**
** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies).
** All rights reserved.
** Contact: Nokia Corporation (qt-info@nokia.com)
**
** This file is part of the test suite of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:LGPL$
** No Commercial Usage
** This file contains pre-release code and may not be distributed.
** You may use this file in accordance with the terms and conditions
** contained in the Technology Preview License Agreement accompanying
** this package.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file.  Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Nokia gives you certain additional
** rights.  These rights are described in the Nokia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** If you have questions regarding the use of this file, please contact
** Nokia at qt-info@nokia.com.
**
**
**
**
**
**
**
**
** $QT_END_LICENSE$
**
****************************************************************************/
#include <qtest.h>
#include "../../../shared/util.h"
#include <QtDeclarative/qmlengine.h>
#include <QtDeclarative/qmlcomponent.h>
#include <private/qmlgraphicswebview_p.h>
#include <private/qmlgraphicspositioners_p.h>
#include <QtWebKit/qwebpage.h>
#include <QtWebKit/qwebframe.h>
#include <QtCore/qdir.h>
#include <QtCore/qfile.h>

class tst_qmlgraphicswebview : public QObject
{
    Q_OBJECT
public:
    tst_qmlgraphicswebview() {}

private slots:
    void basicProperties();
    void historyNav();
    void multipleWindows();
    void elementAreaAt();
    void loadError();
    void setHtml();
    void javaScript();
    void cleanupTestCase();

private:
    void checkNoErrors(const QmlComponent& component);
    QmlEngine engine;
    QString tmpDir() const
    {
        static QString tmpd = QDir::tempPath()+"/tst_qmlgraphicswebview-"
            + QDateTime::currentDateTime().toString(QLatin1String("yyyyMMddhhmmss"));
        return tmpd;
    }
};

static QString strippedHtml(QString html)
{
    html.replace(QRegExp("\\s+"),"");
    return html;
}

static QString fileContents(const QString& filename)
{
    QFile file(filename);
    Q_ASSERT(file.open(QIODevice::ReadOnly));
    return file.readAll();
}

static void removeRecursive(const QString& dirname)
{
    QDir dir(dirname);
    QFileInfoList entries(dir.entryInfoList(QDir::Dirs|QDir::Files|QDir::NoDotAndDotDot));
    for (int i = 0; i < entries.count(); ++i)
        if (entries[i].isDir())
            removeRecursive(entries[i].filePath());
        else
            dir.remove(entries[i].fileName());
    QDir().rmdir(dirname);
}

void tst_qmlgraphicswebview::cleanupTestCase()
{
    removeRecursive(tmpDir());
}

void tst_qmlgraphicswebview::checkNoErrors(const QmlComponent& component)
{
    if (component.isError()) {
        QList<QmlError> errors = component.errors();
        for (int ii = 0; ii < errors.count(); ++ii) {
            const QmlError &error = errors.at(ii);
            QByteArray errorStr = QByteArray::number(error.line()) + ":" +
                                  QByteArray::number(error.column()) + ":" +
                                  error.description().toUtf8();
            qWarning() << errorStr;
        }
    }
    QVERIFY(!component.isError());
}

void tst_qmlgraphicswebview::basicProperties()
{
    QmlComponent component(&engine, QUrl::fromLocalFile(SRCDIR "/data/basic.qml"));
    checkNoErrors(component);
    QWebSettings::enablePersistentStorage(tmpDir());

    QmlGraphicsWebView *wv = qobject_cast<QmlGraphicsWebView*>(component.create());
    QVERIFY(wv != 0);
    QTRY_COMPARE(wv->progress(), 1.0);
    QCOMPARE(wv->title(),QString("Basic"));
    QTRY_COMPARE(wv->icon().width(), 48);
    QCOMPARE(wv->icon(),QPixmap(SRCDIR "/data/basic.png"));
    QCOMPARE(wv->statusText(),QString("status here"));
    QCOMPARE(strippedHtml(fileContents(SRCDIR "/data/basic.html")), strippedHtml(wv->html()));
    QCOMPARE(wv->width(), 123.0);
    QCOMPARE(wv->preferredWidth(), 0);
    QCOMPARE(wv->zoomFactor(), 1.0);
    QCOMPARE(wv->url(), QUrl::fromLocalFile(SRCDIR "/data/basic.html"));
    QCOMPARE(wv->status(), QmlGraphicsWebView::Ready);
    QVERIFY(wv->reloadAction());
    QVERIFY(wv->reloadAction()->isEnabled());
    QVERIFY(wv->backAction());
    QVERIFY(!wv->backAction()->isEnabled());
    QVERIFY(wv->forwardAction());
    QVERIFY(!wv->forwardAction()->isEnabled());
    QVERIFY(wv->stopAction());
    QVERIFY(!wv->stopAction()->isEnabled());

    wv->setPixelCacheSize(0); // mainly testing that it doesn't crash or anything!
    QCOMPARE(wv->pixelCacheSize(),0);
    wv->reloadAction()->trigger();
    QTRY_COMPARE(wv->progress(), 1.0);
}

void tst_qmlgraphicswebview::historyNav()
{
    QmlComponent component(&engine, QUrl::fromLocalFile(SRCDIR "/data/basic.qml"));
    checkNoErrors(component);
    QWebSettings::enablePersistentStorage(tmpDir());

    QmlGraphicsWebView *wv = qobject_cast<QmlGraphicsWebView*>(component.create());
    QVERIFY(wv != 0);
    for (int i=1; i<=2; ++i) {
        QTRY_COMPARE(wv->progress(), 1.0);
        QCOMPARE(wv->title(),QString("Basic"));
        QTRY_COMPARE(wv->icon().width(), 48);
        QCOMPARE(wv->icon(),QPixmap(SRCDIR "/data/basic.png"));
        QCOMPARE(wv->statusText(),QString("status here"));
        QCOMPARE(strippedHtml(fileContents(SRCDIR "/data/basic.html")), strippedHtml(wv->html()));
        QCOMPARE(wv->width(), 123.0);
        QCOMPARE(wv->preferredWidth(), 0);
        QCOMPARE(wv->zoomFactor(), 1.0);
        QCOMPARE(wv->url(), QUrl::fromLocalFile(SRCDIR "/data/basic.html"));
        QCOMPARE(wv->status(), QmlGraphicsWebView::Ready);
        QVERIFY(wv->reloadAction());
        QVERIFY(wv->reloadAction()->isEnabled());
        QVERIFY(wv->backAction());
        QVERIFY(!wv->backAction()->isEnabled());
        QVERIFY(wv->forwardAction());
        QVERIFY(!wv->forwardAction()->isEnabled());
        QVERIFY(wv->stopAction());
        QVERIFY(!wv->stopAction()->isEnabled());

        wv->reloadAction()->trigger();
    }

    wv->setUrl(QUrl::fromLocalFile(SRCDIR "/data/forward.html"));
    QTRY_COMPARE(wv->progress(), 1.0);
    QCOMPARE(wv->title(),QString("Forward"));
    QCOMPARE(strippedHtml(fileContents(SRCDIR "/data/forward.html")), strippedHtml(wv->html()));
    QCOMPARE(wv->url(), QUrl::fromLocalFile(SRCDIR "/data/forward.html"));
    QCOMPARE(wv->status(), QmlGraphicsWebView::Ready);
    QCOMPARE(wv->statusText(),QString(""));
    QVERIFY(wv->reloadAction());
    QVERIFY(wv->reloadAction()->isEnabled());
    QVERIFY(wv->backAction());
    QVERIFY(wv->backAction()->isEnabled());
    QVERIFY(wv->forwardAction());
    QVERIFY(!wv->forwardAction()->isEnabled());
    QVERIFY(wv->stopAction());
    QVERIFY(!wv->stopAction()->isEnabled());

    wv->backAction()->trigger();

    QTRY_COMPARE(wv->progress(), 1.0);
    QCOMPARE(wv->title(),QString("Basic"));
    QCOMPARE(strippedHtml(fileContents(SRCDIR "/data/basic.html")), strippedHtml(wv->html()));
    QCOMPARE(wv->url(), QUrl::fromLocalFile(SRCDIR "/data/basic.html"));
    QCOMPARE(wv->status(), QmlGraphicsWebView::Ready);
    QVERIFY(wv->reloadAction());
    QVERIFY(wv->reloadAction()->isEnabled());
    QVERIFY(wv->backAction());
    QVERIFY(!wv->backAction()->isEnabled());
    QVERIFY(wv->forwardAction());
    QVERIFY(wv->forwardAction()->isEnabled());
    QVERIFY(wv->stopAction());
    QVERIFY(!wv->stopAction()->isEnabled());
}

void tst_qmlgraphicswebview::multipleWindows()
{
    QmlComponent component(&engine, QUrl::fromLocalFile(SRCDIR "/data/newwindows.qml"));
    checkNoErrors(component);

    QmlGraphicsGrid *grid = qobject_cast<QmlGraphicsGrid*>(component.create());
    QVERIFY(grid != 0);
    QTRY_COMPARE(grid->children().count(), 2+5); // Component, Loader, 5 WebViews
}

void tst_qmlgraphicswebview::loadError()
{
    QmlComponent component(&engine, QUrl::fromLocalFile(SRCDIR "/data/loadError.qml"));
    checkNoErrors(component);
    QWebSettings::enablePersistentStorage(tmpDir());

    QmlGraphicsWebView *wv = qobject_cast<QmlGraphicsWebView*>(component.create());
    QVERIFY(wv != 0);
    for (int i=1; i<=2; ++i) {
        QTRY_COMPARE(wv->progress(), 1.0);
        QCOMPARE(wv->title(),QString(""));
        QCOMPARE(wv->statusText(),QString("")); // HTML 'status bar' text, not error message
        QCOMPARE(wv->url(), QUrl::fromLocalFile(SRCDIR "/data/does-not-exist.html")); // Unlike QWebPage, which loses url
        QCOMPARE(wv->status(), QmlGraphicsWebView::Error);

        wv->reloadAction()->trigger();
    }
}

void tst_qmlgraphicswebview::setHtml()
{
    QmlComponent component(&engine, QUrl::fromLocalFile(SRCDIR "/data/sethtml.qml"));
    checkNoErrors(component);
    QmlGraphicsWebView *wv = qobject_cast<QmlGraphicsWebView*>(component.create());
    QVERIFY(wv != 0);
    QCOMPARE(wv->html(),QString("
This is a string set on the WebView
"));
}

void tst_qmlgraphicswebview::elementAreaAt()
{
    QmlComponent component(&engine, QUrl::fromLocalFile(SRCDIR "/data/elements.qml"));
    checkNoErrors(component);
    QmlGraphicsWebView *wv = qobject_cast<QmlGraphicsWebView*>(component.create());
    QVERIFY(wv != 0);
    QTRY_COMPARE(wv->progress(), 1.0);

    QCOMPARE(wv->elementAreaAt(40,30,100,100),QRect(1,1,75,54)); // Area A in data/elements.html
    QCOMPARE(wv->elementAreaAt(130,30,200,100),QRect(78,3,110,50)); // Area B
    QCOMPARE(wv->elementAreaAt(40,30,400,400),QRect(0,0,310,100)); // Whole view
    QCOMPARE(wv->elementAreaAt(130,30,280,280),QRect(76,1,223,54)); // Area BC
    QCOMPARE(wv->elementAreaAt(130,30,400,400),QRect(0,0,310,100)); // Whole view
}

void tst_qmlgraphicswebview::javaScript()
{
    QmlComponent component(&engine, QUrl::fromLocalFile(SRCDIR "/data/javaScript.qml"));
    checkNoErrors(component);
    QmlGraphicsWebView *wv = qobject_cast<QmlGraphicsWebView*>(component.create());
    QVERIFY(wv != 0);
    QTRY_COMPARE(wv->progress(), 1.0);
    QCOMPARE(wv->evaluateJavaScript("123").toInt(), 123);
    QCOMPARE(wv->evaluateJavaScript("window.status").toString(), QString("status here"));
    QCOMPARE(wv->evaluateJavaScript("window.myjsname.qmlprop").toString(), QString("qmlvalue"));
}

QTEST_MAIN(tst_qmlgraphicswebview)

#include "tst_qmlgraphicswebview.moc"
<|endoftext|>


<commit_before>// ======================================================================== //
// Copyright 2009-2020 Intel Corporation                                    //
//                                                                          //
// 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 "../../../external/catch.hpp"
#include "../../../../kernels/geometry/sphere_intersector.h"
#include "../../../../common/simd/sse.cpp"

using namespace embree;

namespace __sphere_unit_tests_internal {

  struct fakeEpilog {

    fakeEpilog (Ray& ray)
      : ray_(ray) {}

    bool operator ()(const vbool<4> & ,
                     const sse2::SphereIntersectorHitM<4>& hit) const {

      ray_.id = -1;
      for (auto i=0; i<4; ++i) {
        if (hit.vt[i] > 1.e-5f && hit.vt[i] < ray_.tfar) {
          ray_.tfar = hit.vt[i];
          ray_.id = i;
        }
      }
      return ray_.id != -1;
    }

    Ray& ray_;
  };

}

TEST_CASE ("Overlapping spheres with filtering - Issue 676 fix-intersection-epilog-handling", "[spheres]")
{
  sse2::CurvePrecalculations1 pre;
  vbool<4> valid {true, true, false, false};
  Vec3fa org (14.8001127f, -9.01768494f, 3.47012758f);
  Vec3fa dir (-0.989340246f, -0.0190101117f, -0.144376263f);
  Ray ray (org, dir);
  Vec4vf<4> v0;
  v0.x = vfloat<4>{ 9.66870880f,  10.0441875f, 0.f, 0.f};
  v0.y = vfloat<4>{-16.3965702f, -9.69345284f, 0.f, 0.f};
  v0.z = vfloat<4>{ 3.93995930f,  3.94893074f, 0.f, 0.f};
  v0.w = vfloat<4>{9.f, 9.f, 0.f, 0.f};

  __sphere_unit_tests_internal::fakeEpilog epilog (ray);

  sse2::SphereIntersector1<4>::intersect (valid, ray, pre, v0, epilog);
  int id = ray.id;
  REQUIRE (id == 0);
  REQUIRE (ray.tfar == Approx (10.2983));
}
<commit_msg>compile fix when only a single ISA is enabled<commit_after>// ======================================================================== //
// Copyright 2009-2020 Intel Corporation                                    //
//                                                                          //
// 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 "../../../external/catch.hpp"
#include "../../../../kernels/geometry/sphere_intersector.h"
#include "../../../../common/simd/sse.cpp"

using namespace embree;

namespace __sphere_unit_tests_internal {

  struct fakeEpilog {

    fakeEpilog (Ray& ray)
      : ray_(ray) {}

    bool operator ()(const vbool<4> & ,
                     const isa::SphereIntersectorHitM<4>& hit) const {

      ray_.id = -1;
      for (auto i=0; i<4; ++i) {
        if (hit.vt[i] > 1.e-5f && hit.vt[i] < ray_.tfar) {
          ray_.tfar = hit.vt[i];
          ray_.id = i;
        }
      }
      return ray_.id != -1;
    }

    Ray& ray_;
  };

}

TEST_CASE ("Overlapping spheres with filtering - Issue 676 fix-intersection-epilog-handling", "[spheres]")
{
  isa::CurvePrecalculations1 pre;
  vbool<4> valid {true, true, false, false};
  Vec3fa org (14.8001127f, -9.01768494f, 3.47012758f);
  Vec3fa dir (-0.989340246f, -0.0190101117f, -0.144376263f);
  Ray ray (org, dir);
  Vec4vf<4> v0;
  v0.x = vfloat<4>{ 9.66870880f,  10.0441875f, 0.f, 0.f};
  v0.y = vfloat<4>{-16.3965702f, -9.69345284f, 0.f, 0.f};
  v0.z = vfloat<4>{ 3.93995930f,  3.94893074f, 0.f, 0.f};
  v0.w = vfloat<4>{9.f, 9.f, 0.f, 0.f};

  __sphere_unit_tests_internal::fakeEpilog epilog (ray);

  isa::SphereIntersector1<4>::intersect (valid, ray, pre, v0, epilog);
  int id = ray.id;
  REQUIRE (id == 0);
  REQUIRE (ray.tfar == Approx (10.2983));
}
<|endoftext|>