<commit_before>// This file is a part of the OpenSurgSim project.
// Copyright 2013, SimQuest Solutions Inc.
//
// 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 <gtest/gtest.h>

#include "SurgSim/DataStructures/TriangleMesh.h"
#include "SurgSim/DataStructures/TriangleMeshBase.h"
#include "SurgSim/Math/Vector.h"

using SurgSim::DataStructures::TriangleMesh;
using SurgSim::Math::Vector3d;

namespace SurgSim
{
namespace DataStructures
{

TEST(MeshTest, NormalTest)
{
	typedef SurgSim::DataStructures::TriangleMeshBase<void, void, void> TriangleMeshBase;
	typedef SurgSim::DataStructures::MeshElement<2, void> EdgeElement;
	typedef SurgSim::DataStructures::MeshElement<3, void> TriangleElement;

	std::shared_ptr<TriangleMeshBase> mesh = std::make_shared<TriangleMeshBase>();

	// Add vertex
	TriangleMeshBase::VertexType v0(Vector3d(-1.0, -1.0, -1.0));
	TriangleMeshBase::VertexType v1(Vector3d( 1.0, -1.0, -1.0));
	TriangleMeshBase::VertexType v2(Vector3d(-1.0,  1.0, -1.0));

	mesh->addVertex(v0);
	mesh->addVertex(v1);
	mesh->addVertex(v2);

	// Add edges
	std::array<unsigned int, 2> edgePoints01;
	std::array<unsigned int, 2> edgePoints02;
	std::array<unsigned int, 2> edgePoints12;

	EdgeElement element01(edgePoints01);
	EdgeElement element02(edgePoints02);
	EdgeElement element12(edgePoints12);

	TriangleMeshBase::EdgeType e01(element01);
	TriangleMeshBase::EdgeType e02(element02);
	TriangleMeshBase::EdgeType e12(element12);

	mesh->addEdge(e01);
	mesh->addEdge(e02);
	mesh->addEdge(e12);

	// Add triangle
	std::array<unsigned int, 3> trianglePoints = {0, 1, 2};

	TriangleElement triangleElement(trianglePoints);
	TriangleMeshBase::TriangleType t(triangleElement);
	mesh->addTriangle(t);

	std::shared_ptr<TriangleMesh> collisionMesh = std::make_shared<TriangleMesh>(mesh);

	Vector3d expectedZNormal(0.0, 0.0, 1.0);
	EXPECT_EQ(expectedZNormal, collisionMesh->getNormal(0));

	// Update new vertex location of v2 to v3
	Vector3d v3(-1.0, -1.0, 1.0);
	SurgSim::DataStructures::Vertex<SurgSim::DataStructures::EmptyData>& v2p = collisionMesh->getVertex(2);
	v2p = v3;

	// Recompute normals for CollisionMesh
	collisionMesh->calculateNormals();
	Vector3d expectedXNormal(0.0, -1.0, 0.0);
	EXPECT_EQ(expectedXNormal, collisionMesh->getNormal(0));
}

};
};<commit_msg>Fix UnitTest failing of DataStructure::TriangleMesh<commit_after>// This file is a part of the OpenSurgSim project.
// Copyright 2013, SimQuest Solutions Inc.
//
// 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 <gtest/gtest.h>

#include "SurgSim/DataStructures/TriangleMesh.h"
#include "SurgSim/DataStructures/TriangleMeshBase.h"
#include "SurgSim/Math/Vector.h"

using SurgSim::DataStructures::TriangleMesh;
using SurgSim::Math::Vector3d;

namespace SurgSim
{
namespace DataStructures
{

TEST(TriangleMeshTest, NormalTest)
{
	typedef SurgSim::DataStructures::TriangleMeshBase<void, void, void> TriangleMeshBase;
	typedef SurgSim::DataStructures::MeshElement<2, void> EdgeElement;
	typedef SurgSim::DataStructures::MeshElement<3, void> TriangleElement;

	std::shared_ptr<TriangleMeshBase> mesh = std::make_shared<TriangleMeshBase>();

	// Add vertex
	TriangleMeshBase::VertexType v0(Vector3d(-1.0, -1.0, -1.0));
	TriangleMeshBase::VertexType v1(Vector3d( 1.0, -1.0, -1.0));
	TriangleMeshBase::VertexType v2(Vector3d(-1.0,  1.0, -1.0));

	mesh->addVertex(v0);
	mesh->addVertex(v1);
	mesh->addVertex(v2);

	// Add edges
	std::array<unsigned int, 2> edgePoints01;
	std::array<unsigned int, 2> edgePoints02;
	std::array<unsigned int, 2> edgePoints12;

	EdgeElement element01(edgePoints01);
	EdgeElement element02(edgePoints02);
	EdgeElement element12(edgePoints12);

	TriangleMeshBase::EdgeType e01(element01);
	TriangleMeshBase::EdgeType e02(element02);
	TriangleMeshBase::EdgeType e12(element12);

	mesh->addEdge(e01);
	mesh->addEdge(e02);
	mesh->addEdge(e12);

	// Add triangle
	std::array<unsigned int, 3> trianglePoints = {0, 1, 2};

	TriangleElement triangleElement(trianglePoints);
	TriangleMeshBase::TriangleType t(triangleElement);
	mesh->addTriangle(t);

	std::shared_ptr<TriangleMesh> collisionMesh = std::make_shared<TriangleMesh>(mesh);

	Vector3d expectedZNormal(0.0, 0.0, 1.0);
	EXPECT_EQ(expectedZNormal, collisionMesh->getNormal(0));

	// Update new vertex location of v2 to v3
	Vector3d v3(-1.0, -1.0, 1.0);
	SurgSim::DataStructures::Vertex<SurgSim::DataStructures::EmptyData>& v2p = collisionMesh->getVertex(2);
	v2p = v3;

	// Recompute normals for CollisionMesh
	collisionMesh->calculateNormals();
	Vector3d expectedXNormal(0.0, -1.0, 0.0);
	EXPECT_EQ(expectedXNormal, collisionMesh->getNormal(0));
}

};
};<|endoftext|>


<commit_before>/*=========================================================================

  Program:   ORFEO Toolbox
  Language:  C++
  Date:      $Date$
  Version:   $Revision$

  Copyright (c) Centre National d'Etudes Spatiales. All rights reserved.
  See OTBCopyright.txt for details.

     This software is distributed WITHOUT ANY WARRANTY; without even
     the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
     PURPOSE.  See the above copyright notices for more information.

=========================================================================*/

#include "itkMacro.h"
#include "otbImage.h"
#include <iostream>
#include <fstream>

#include "otbSVMModel.h"
#include "otbSVMKernels.h"
#include "svm.h"

int otbSVMComposedKernelFunctorTest( int itkNotUsed(argc), char* argv[] )
{
  typedef unsigned char                                   InputPixelType;
  typedef unsigned char                                   LabelPixelType;

  typedef otb::SVMModel< InputPixelType, LabelPixelType >   ModelType;

  ModelType::Pointer svmModel = ModelType::New();

  otb::CustomKernelFunctor         customFunctor;
  otb::SAMKernelFunctor            SAMFunctor;
  ComposedKernelFunctor            composedKernelFunctor;
  composedKernelFunctor.AddKernelFunctorModelToKernelList(&customFunctor);
  composedKernelFunctor.AddKernelFunctorModelToKernelList(&SAMFunctor);
  composedKernelFunctor.AddPonderationToPonderationList(1.5);
  composedKernelFunctor.AddPonderationToPonderationList(2.0);
  composedKernelFunctor.SetName("compositionFilter");

  struct svm_model *model;
  model = new svm_model;
  model->param.svm_type = 0;
  model->param.kernel_type = 6;
  model->nr_class = 2;
  model->l = 5;
  model->sv_coef = new double*[model->nr_class-1];

  for(int i=0; i<model->nr_class-1; i++)
    model->sv_coef[i] = new double[model->l];
  model->SV = new svm_node*[model->l];
  for(int n = 0; n<model->l; ++n)
    {
      model->SV[n]= new svm_node;
      model->SV[n]->index = -1;
      model->SV[n]->value = 0.;
    }

  model->sv_coef[0][0] = 0.125641;
  model->sv_coef[0][1] = 1;
  model->sv_coef[0][2] = 0;
  model->sv_coef[0][3] = -1;
  model->sv_coef[0][4] = -0.54994;

  model->rho = new double[1];
  model->probA = new double[1];
  model->probB = new double[1];
  model->rho[0] = 22.3117;
  model->probA[0] = -0.541009;
  model->probB[0] = -0.687381;
  model->param.const_coef = 2.;
  model->param.lin_coef = 5.;
  model->param.gamma = 1.5;
  model->param.degree = 2;

  model->label = new int[2];
  model->label[0] = 1;
  model->label[1] = -1;
  model->nSV = new int[2];
  model->nSV[0] = 3;
  model->nSV[1] = 2;

  model->param.kernel_composed = &composedKernelFunctor;
  svmModel->SetModel(model);

  struct svm_node *x = new svm_node[3];
  struct svm_node *y = new svm_node[3];

  struct svm_node **SVx = new svm_node*[1];
  struct svm_node **SVy = new svm_node*[1];
  SVx[0] = new svm_node[1];
  SVy[0] = new svm_node[1];
  SVx[0] = &x[0];
  SVy[0] = &y[0];

  x[0].index = 1;
  x[0].value = 10;
  x[1].index = -1;
  x[1].value = 10000;

  y[0].index = 1;
  y[0].value = 5;
  y[1].index = -1;
  y[1].value = 10000;

  double resAdd =0.;
  double resMul =0.;
  double res1 = 0.;
  double res2 = 0.;

  std::ofstream file;
  file.open(argv[1]);

  file<<"Inputs Values: 10, 5, Inputs Ponderation: 1.5, 2"<<std::endl;

  file<<std::endl;

  file<<"Functor Results:"<<std::endl;

  res1 = customFunctor(SVx[0], SVy[0], model->param);
  file<<"Custom Functor only: "<<res1<<std::endl;
  //std::cout<<"customFunctor : "<<res1<<std::endl;
  res2 = SAMFunctor(SVx[0], SVy[0], model->param);
  file<<"SAM Functor only: "<<res2<<std::endl;
  //std::cout<<"SAMFunctor : "<<res2<<std::endl;
  file<<"Composed Functor: "<<std::endl;
  resAdd = (*(svmModel->GetModel()->param.kernel_composed))(SVx[0], SVy[0], svmModel->GetModel()->param);

  //std::cout<<"composed : "<<resAdd<<std::endl;

  svmModel->GetModel()->param.kernel_composed->SetMultiplyKernelFunctor(true);
  resMul = (*(svmModel->GetModel()->param.kernel_composed))(SVx[0], SVy[0], svmModel->GetModel()->param);

  //std::cout<<"composed : "<<resAdd<<std::endl;
  file<<"Addition: "<<resAdd<<", "<<"Multiplication: "<<resMul<<std::endl;

  file.close();

  //svmModel->GetModel()->param.kernel_composed->print_parameters();

  svmModel->SaveModel(argv[2]);

  ModelType::Pointer svmModelBis = ModelType::New();
  svmModelBis->LoadModel(argv[2]);

  //svmModelBis->GetModel()->param.kernel_composed->print_parameters();

  svmModelBis->SaveModel(argv[3]);

  // Free all memory

  for(int i=0; i<model->nr_class-1; i++)
    delete [] model->sv_coef[i];
  delete model->sv_coef;

  for(int n = 0; n<model->l; ++n)
    delete model->SV[n];

  delete [] model->SV;
  delete [] model->rho;
  delete [] model->probA;
  delete [] model->probB;
  delete [] model->label;
  delete [] model->nSV;
  delete [] x;
  delete [] y;
  delete [] SVx[0];
  delete [] SVy[0];
  delete [] SVx;
  delete [] sVy;

  delete model;

  return EXIT_SUCCESS;
}
<commit_msg>COMP: small error<commit_after>/*=========================================================================

  Program:   ORFEO Toolbox
  Language:  C++
  Date:      $Date$
  Version:   $Revision$

  Copyright (c) Centre National d'Etudes Spatiales. All rights reserved.
  See OTBCopyright.txt for details.

     This software is distributed WITHOUT ANY WARRANTY; without even
     the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
     PURPOSE.  See the above copyright notices for more information.

=========================================================================*/

#include "itkMacro.h"
#include "otbImage.h"
#include <iostream>
#include <fstream>

#include "otbSVMModel.h"
#include "otbSVMKernels.h"
#include "svm.h"

int otbSVMComposedKernelFunctorTest( int itkNotUsed(argc), char* argv[] )
{
  typedef unsigned char                                   InputPixelType;
  typedef unsigned char                                   LabelPixelType;

  typedef otb::SVMModel< InputPixelType, LabelPixelType >   ModelType;

  ModelType::Pointer svmModel = ModelType::New();

  otb::CustomKernelFunctor         customFunctor;
  otb::SAMKernelFunctor            SAMFunctor;
  ComposedKernelFunctor            composedKernelFunctor;
  composedKernelFunctor.AddKernelFunctorModelToKernelList(&customFunctor);
  composedKernelFunctor.AddKernelFunctorModelToKernelList(&SAMFunctor);
  composedKernelFunctor.AddPonderationToPonderationList(1.5);
  composedKernelFunctor.AddPonderationToPonderationList(2.0);
  composedKernelFunctor.SetName("compositionFilter");

  struct svm_model *model;
  model = new svm_model;
  model->param.svm_type = 0;
  model->param.kernel_type = 6;
  model->nr_class = 2;
  model->l = 5;
  model->sv_coef = new double*[model->nr_class-1];

  for(int i=0; i<model->nr_class-1; i++)
    model->sv_coef[i] = new double[model->l];
  model->SV = new svm_node*[model->l];
  for(int n = 0; n<model->l; ++n)
    {
      model->SV[n]= new svm_node;
      model->SV[n]->index = -1;
      model->SV[n]->value = 0.;
    }

  model->sv_coef[0][0] = 0.125641;
  model->sv_coef[0][1] = 1;
  model->sv_coef[0][2] = 0;
  model->sv_coef[0][3] = -1;
  model->sv_coef[0][4] = -0.54994;

  model->rho = new double[1];
  model->probA = new double[1];
  model->probB = new double[1];
  model->rho[0] = 22.3117;
  model->probA[0] = -0.541009;
  model->probB[0] = -0.687381;
  model->param.const_coef = 2.;
  model->param.lin_coef = 5.;
  model->param.gamma = 1.5;
  model->param.degree = 2;

  model->label = new int[2];
  model->label[0] = 1;
  model->label[1] = -1;
  model->nSV = new int[2];
  model->nSV[0] = 3;
  model->nSV[1] = 2;

  model->param.kernel_composed = &composedKernelFunctor;
  svmModel->SetModel(model);

  struct svm_node *x = new svm_node[3];
  struct svm_node *y = new svm_node[3];

  struct svm_node **SVx = new svm_node*[1];
  struct svm_node **SVy = new svm_node*[1];
  SVx[0] = new svm_node[1];
  SVy[0] = new svm_node[1];
  SVx[0] = &x[0];
  SVy[0] = &y[0];

  x[0].index = 1;
  x[0].value = 10;
  x[1].index = -1;
  x[1].value = 10000;

  y[0].index = 1;
  y[0].value = 5;
  y[1].index = -1;
  y[1].value = 10000;

  double resAdd =0.;
  double resMul =0.;
  double res1 = 0.;
  double res2 = 0.;

  std::ofstream file;
  file.open(argv[1]);

  file<<"Inputs Values: 10, 5, Inputs Ponderation: 1.5, 2"<<std::endl;

  file<<std::endl;

  file<<"Functor Results:"<<std::endl;

  res1 = customFunctor(SVx[0], SVy[0], model->param);
  file<<"Custom Functor only: "<<res1<<std::endl;
  //std::cout<<"customFunctor : "<<res1<<std::endl;
  res2 = SAMFunctor(SVx[0], SVy[0], model->param);
  file<<"SAM Functor only: "<<res2<<std::endl;
  //std::cout<<"SAMFunctor : "<<res2<<std::endl;
  file<<"Composed Functor: "<<std::endl;
  resAdd = (*(svmModel->GetModel()->param.kernel_composed))(SVx[0], SVy[0], svmModel->GetModel()->param);

  //std::cout<<"composed : "<<resAdd<<std::endl;

  svmModel->GetModel()->param.kernel_composed->SetMultiplyKernelFunctor(true);
  resMul = (*(svmModel->GetModel()->param.kernel_composed))(SVx[0], SVy[0], svmModel->GetModel()->param);

  //std::cout<<"composed : "<<resAdd<<std::endl;
  file<<"Addition: "<<resAdd<<", "<<"Multiplication: "<<resMul<<std::endl;

  file.close();

  //svmModel->GetModel()->param.kernel_composed->print_parameters();

  svmModel->SaveModel(argv[2]);

  ModelType::Pointer svmModelBis = ModelType::New();
  svmModelBis->LoadModel(argv[2]);

  //svmModelBis->GetModel()->param.kernel_composed->print_parameters();

  svmModelBis->SaveModel(argv[3]);

  // Free all memory

  for(int i=0; i<model->nr_class-1; i++)
    delete [] model->sv_coef[i];
  delete model->sv_coef;

  for(int n = 0; n<model->l; ++n)
    delete model->SV[n];

  delete [] model->SV;
  delete [] model->rho;
  delete [] model->probA;
  delete [] model->probB;
  delete [] model->label;
  delete [] model->nSV;
  delete [] x;
  delete [] y;
  delete [] SVx[0];
  delete [] SVy[0];
  delete [] SVx;
  delete [] SVy;

  delete model;

  return EXIT_SUCCESS;
}
<|endoftext|>


<commit_before>#include <ros/ros.h>
#include <tf/transform_listener.h>
#include <geometry_msgs/Twist.h>
#include <sensor_msgs/PointCloud.h>

void center_cloud_cb(const sensor_msgs::PointCloud::ConstPtr& inMsg)
{

     if (inMsg->points.size()>0)
     {
ros::Time now = ros::Time(0);
    sensor_msgs::PointCloud cloud_in;
    cloud_in.header.stamp = inMsg->header.stamp;
    cloud_in.header.frame_id = inMsg->header.frame_id;
    cloud_in.points=inMsg->points;

         //center_cloud.points.resize(sifted_centroid_list.size());
         //one_centroid=sifted_centroid_list[0];
         std::cout<<"centroids are:"<<std::endl;
         std::cout<<inMsg->points[0].x<<std::endl;
         tf::StampedTransform transform;
         tf::TransformListener listener;

         //ros::Time now = ros::Time::now();

         ros::Duration(2).sleep();

         listener.waitForTransform("/base_link","/velodyne",now,ros::Duration(0.0));
         listener.lookupTransform("/base_link","/velodyne",now,transform);
         sensor_msgs::PointCloud gobal;

         //cloud_in=*inMsg;
         try {
        //listener.transformPointCloud("/base_link",cloud_in, gobal);

        listener.transformPointCloud("/base_link",now,cloud_in, "/velodyne",gobal);

        std::cout<<"New centroids are:"<<std::endl;
        std::cout<<gobal.points[0].x<<std::endl;
                 } catch (tf2::ExtrapolationException &ex){

//std::cout<<ex.msg<<std::endl;
//continue;
        }

     }

}

int main(int argc, char** argv){
  ros::init(argc, argv, "tf_listener");

  ros::NodeHandle node;
  ros::Subscriber input=node.subscribe("center_cloud",10, center_cloud_cb);

  tf::StampedTransform transform;
  tf::TransformListener listener;

  //listener.lookupTransform("/velodyne","/bask_link",ros::Time(0),transform);
  //std::cout << transform.stamp << std::endl;

  //ros::Rate rate(10.0);
  ros::spin();
  return 0;
};
<commit_msg>Removing remnant<commit_after><|endoftext|>


<commit_before>/*
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements.  See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership.  The ASF licenses this file
 * to you 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.
 *
 * Modified by Cloudius Systems.
 * Copyright 2015 Cloudius Systems.
 */

#include "streaming/stream_request.hh"

namespace streaming {

void stream_request::serialize(bytes::iterator& out) const {
    serialize_string(out, keyspace);

    serialize_int32(out, uint32_t(ranges.size()));
    // for (auto& x : ranges) {
    //     FIXME: query::range<token>
    // }

    serialize_int32(out, uint32_t(column_families.size()));
    for (auto& x : column_families) {
        serialize_string(out, x);
    }

    serialize_int64(out, repaired_at);
}

stream_request stream_request::deserialize(bytes_view& v) {
    auto keyspace_ = read_simple_short_string(v);

    auto num = read_simple<int32_t>(v);
    std::vector<query::range<token>> ranges_;
    for (int32_t i = 0; i < num; i++) {
        // FIXME: query::range<token>
        ranges_.push_back(query::range<token>::make_open_ended_both_sides());
    }

    num = read_simple<int32_t>(v);
    std::vector<sstring> column_families_;
    for (int32_t i = 0; i < num; i++) {
        auto s = read_simple_short_string(v);
        column_families_.push_back(std::move(s));
    }

    auto repaired_at_ = read_simple<int64_t>(v);

    return stream_request(std::move(keyspace_), std::move(ranges_), std::move(column_families_), repaired_at_);
}

size_t stream_request::serialized_size() const {
    size_t size = serialize_string_size(keyspace);

    size += serialize_int32_size;
    // for (auto& x : ranges) {
    //     FIXME: query::range<token>
    // }

    size += serialize_int32_size;
    for (auto& x : column_families) {
        size += serialize_string_size(x);
    }

    size += serialize_int64_size;

    return size;
}

std::ostream& operator<<(std::ostream& os, const stream_request& sr) {
    os << "[ ks = " << sr.keyspace << " cf =  ";
    for (auto& cf : sr.column_families) {
        os << cf << " ";
    }
    return os << "]";
}

} // namespace streaming;
<commit_msg>streaming: Serialize query::range<token> in stream_request<commit_after>/*
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements.  See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership.  The ASF licenses this file
 * to you 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.
 *
 * Modified by Cloudius Systems.
 * Copyright 2015 Cloudius Systems.
 */

#include "streaming/stream_request.hh"
#include "query-request.hh"

namespace streaming {

void stream_request::serialize(bytes::iterator& out) const {
    serialize_string(out, keyspace);

    serialize_int32(out, uint32_t(ranges.size()));
    for (auto& x : ranges) {
        x.serialize(out);
    }

    serialize_int32(out, uint32_t(column_families.size()));
    for (auto& x : column_families) {
        serialize_string(out, x);
    }

    serialize_int64(out, repaired_at);
}

stream_request stream_request::deserialize(bytes_view& v) {
    auto keyspace_ = read_simple_short_string(v);

    auto num = read_simple<int32_t>(v);
    std::vector<query::range<token>> ranges_;
    for (int32_t i = 0; i < num; i++) {
        ranges_.push_back(query::range<token>::deserialize(v));
    }

    num = read_simple<int32_t>(v);
    std::vector<sstring> column_families_;
    for (int32_t i = 0; i < num; i++) {
        auto s = read_simple_short_string(v);
        column_families_.push_back(std::move(s));
    }

    auto repaired_at_ = read_simple<int64_t>(v);

    return stream_request(std::move(keyspace_), std::move(ranges_), std::move(column_families_), repaired_at_);
}

size_t stream_request::serialized_size() const {
    size_t size = serialize_string_size(keyspace);

    size += serialize_int32_size;
    for (auto& x : ranges) {
        size += x.serialized_size();
    }

    size += serialize_int32_size;
    for (auto& x : column_families) {
        size += serialize_string_size(x);
    }

    size += serialize_int64_size;

    return size;
}

std::ostream& operator<<(std::ostream& os, const stream_request& sr) {
    os << "[ ks = " << sr.keyspace << " cf =  ";
    for (auto& cf : sr.column_families) {
        os << cf << " ";
    }
    return os << "]";
}

} // namespace streaming;
<|endoftext|>


<commit_before>/*=========================================================================
 *
 *  Copyright Insight Software Consortium
 *
 *  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.txt
 *
 *  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 <iostream>
#include <string.h>
#include "itkVersion.h"
#include "itkTransformFactoryBase.h"

int itkTransformFactoryBaseTest (int, char*[])
{
  // Call register default transforms
  itk::TransformFactoryBase::RegisterDefaultTransforms();

  // create the list of default transforms
  std::list<std::string> defaultTransforms;
  defaultTransforms.push_back("AffineTransform_double_2_2");
  defaultTransforms.push_back("AffineTransform_double_3_3");
  defaultTransforms.push_back("AffineTransform_double_4_4");
  defaultTransforms.push_back("AffineTransform_double_5_5");
  defaultTransforms.push_back("AffineTransform_double_6_6");
  defaultTransforms.push_back("AffineTransform_double_7_7");
  defaultTransforms.push_back("AffineTransform_double_8_8");
  defaultTransforms.push_back("AffineTransform_double_9_9");
  defaultTransforms.push_back("IdentityTransform_double_2_2");
  defaultTransforms.push_back("IdentityTransform_double_3_3");
  defaultTransforms.push_back("IdentityTransform_double_4_4");
  defaultTransforms.push_back("IdentityTransform_double_5_5");
  defaultTransforms.push_back("IdentityTransform_double_6_6");
  defaultTransforms.push_back("IdentityTransform_double_7_7");
  defaultTransforms.push_back("IdentityTransform_double_8_8");
  defaultTransforms.push_back("IdentityTransform_double_9_9");
  defaultTransforms.push_back("BSplineTransform_double_2_2");
  defaultTransforms.push_back("BSplineTransform_double_3_3");
#ifdef ITKV3_COMPATIBILITY
  defaultTransforms.push_back("BSplineDeformableTransform_double_2_2");
  defaultTransforms.push_back("BSplineDeformableTransform_double_3_3");
#endif
  defaultTransforms.push_back("CenteredAffineTransform_double_2_2");
  defaultTransforms.push_back("CenteredAffineTransform_double_3_3");
  defaultTransforms.push_back("CenteredEuler3DTransform_double_3_3");
  defaultTransforms.push_back("CenteredRigid2DTransform_double_2_2");
  defaultTransforms.push_back("CenteredSimilarity2DTransform_double_2_2");
  defaultTransforms.push_back("Euler2DTransform_double_2_2");
  defaultTransforms.push_back("Euler3DTransform_double_3_3");
  defaultTransforms.push_back("FixedCenterOfRotationAffineTransform_double_3_3");
  defaultTransforms.push_back("QuaternionRigidTransform_double_3_3");
  defaultTransforms.push_back("Rigid2DTransform_double_2_2");
  defaultTransforms.push_back("Rigid3DPerspectiveTransform_double_3_2");
  defaultTransforms.push_back("Rigid3DTransform_double_3_3");
  defaultTransforms.push_back("ScalableAffineTransform_double_3_3");
  defaultTransforms.push_back("ScaleLogarithmicTransform_double_3_3");
  defaultTransforms.push_back("ScaleVersor3DTransform_double_3_3");
  defaultTransforms.push_back("ScaleSkewVersor3DTransform_double_3_3");
  defaultTransforms.push_back("ScaleTransform_double_2_2");
  defaultTransforms.push_back("ScaleTransform_double_3_3");
  defaultTransforms.push_back("ScaleTransform_double_4_4");
  defaultTransforms.push_back("TranslationTransform_double_3_3");
  defaultTransforms.push_back("VersorRigid3DTransform_double_3_3");
  defaultTransforms.push_back("VersorTransform_double_3_3");
  defaultTransforms.push_back("Similarity2DTransform_double_2_2");

  defaultTransforms.push_back("AffineTransform_float_2_2");
  defaultTransforms.push_back("AffineTransform_float_3_3");
  defaultTransforms.push_back("AffineTransform_float_4_4");
  defaultTransforms.push_back("AffineTransform_float_5_5");
  defaultTransforms.push_back("AffineTransform_float_6_6");
  defaultTransforms.push_back("AffineTransform_float_7_7");
  defaultTransforms.push_back("AffineTransform_float_8_8");
  defaultTransforms.push_back("AffineTransform_float_9_9");
  defaultTransforms.push_back("IdentityTransform_float_2_2");
  defaultTransforms.push_back("IdentityTransform_float_3_3");
  defaultTransforms.push_back("IdentityTransform_float_4_4");
  defaultTransforms.push_back("IdentityTransform_float_5_5");
  defaultTransforms.push_back("IdentityTransform_float_6_6");
  defaultTransforms.push_back("IdentityTransform_float_7_7");
  defaultTransforms.push_back("IdentityTransform_float_8_8");
  defaultTransforms.push_back("IdentityTransform_float_9_9");
  defaultTransforms.push_back("BSplineTransform_float_2_2");
  defaultTransforms.push_back("BSplineTransform_float_3_3");
#ifdef ITKV3_COMPATIBILITY
  defaultTransforms.push_back("BSplineDeformableTransform_float_2_2");
  defaultTransforms.push_back("BSplineDeformableTransform_float_3_3");
#endif
  defaultTransforms.push_back("CenteredAffineTransform_float_2_2");
  defaultTransforms.push_back("CenteredAffineTransform_float_3_3");
  defaultTransforms.push_back("CenteredEuler3DTransform_float_3_3");
  defaultTransforms.push_back("CenteredRigid2DTransform_float_2_2");
  defaultTransforms.push_back("CenteredSimilarity2DTransform_float_2_2");
  defaultTransforms.push_back("Euler2DTransform_float_2_2");
  defaultTransforms.push_back("Euler3DTransform_float_3_3");
  defaultTransforms.push_back("FixedCenterOfRotationAffineTransform_float_3_3");
  defaultTransforms.push_back("QuaternionRigidTransform_float_3_3");
  defaultTransforms.push_back("Rigid2DTransform_float_2_2");
  defaultTransforms.push_back("Rigid3DPerspectiveTransform_float_3_2");
  defaultTransforms.push_back("Rigid3DTransform_float_3_3");
  defaultTransforms.push_back("ScalableAffineTransform_float_3_3");
  defaultTransforms.push_back("ScaleLogarithmicTransform_float_3_3");
  defaultTransforms.push_back("ScaleVersor3DTransform_float_3_3");
  defaultTransforms.push_back("ScaleSkewVersor3DTransform_float_3_3");
  defaultTransforms.push_back("ScaleTransform_float_2_2");
  defaultTransforms.push_back("ScaleTransform_float_3_3");
  defaultTransforms.push_back("ScaleTransform_float_4_4");
  defaultTransforms.push_back("TranslationTransform_float_3_3");
  defaultTransforms.push_back("VersorRigid3DTransform_float_3_3");
  defaultTransforms.push_back("VersorTransform_float_3_3");
  defaultTransforms.push_back("Similarity2DTransform_float_2_2");

  // check to make sure that all default transforms have been registered
  defaultTransforms.sort();
  // Print out the names of all the registered transforms
  std::list<std::string> names = itk::TransformFactoryBase::GetFactory()->GetClassOverrideWithNames();
  names.sort();
  std::list<std::string>::iterator namesIt;
  std::list<std::string>::iterator defaultsIt;
  for (namesIt = names.begin(), defaultsIt = defaultTransforms.begin();
       namesIt != names.end(), defaultsIt != defaultTransforms.end();
       namesIt++, defaultsIt++)
    {
    if (strcmp((*namesIt).c_str(), (*defaultsIt).c_str()) != 0)
      {
      std::cout << "[FAILED] " << *defaultsIt << " not registered properly with defaults" << std::endl;
      return EXIT_FAILURE;
      }
    else
      {
      std::cout << "[SUCCESS] " << *defaultsIt << " registered properly" << std::endl;
      }
    }

  // test other methods
  itk::TransformFactoryBase::Pointer base = itk::TransformFactoryBase::New();
  const char* itkVersion = base->GetITKSourceVersion();
  const char* description = base->GetDescription();
  const char* type = base->GetNameOfClass();
  if (strcmp(itkVersion, ITK_SOURCE_VERSION) != 0)
    {
    std::cout << "[FAILED] Did not report version correctly" << std::endl;
    }
  else
    {
    std::cout << "[SUCCESS] Reported version correctly as " << itkVersion << std::endl;
    }
  if (strcmp(description, "Transform FactoryBase") != 0)
    {
    std::cout << "[FAILED] Did not report description correctly" << std::endl;
    }
  else
    {
    std::cout << "[SUCCESS] Reported description correctly as " << description << std::endl;
    }
  if (strcmp(type, "TransformFactoryBase") != 0)
    {
    std::cout << "[FAILED] Did not report type correctly" << std::endl;
    }
  else
    {
    std::cout << "[SUCCESS] Reported type correctly as " << type << std::endl;
    }

  // return successfully
  return EXIT_SUCCESS;

}
<commit_msg>COMP: Fix TransformFactoryBase test by adding new Composite XFRMS<commit_after>/*=========================================================================
 *
 *  Copyright Insight Software Consortium
 *
 *  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.txt
 *
 *  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 <iostream>
#include <string.h>
#include "itkVersion.h"
#include "itkTransformFactoryBase.h"

int itkTransformFactoryBaseTest (int, char*[])
{
  // Call register default transforms
  itk::TransformFactoryBase::RegisterDefaultTransforms();

  // create the list of default transforms
  std::list<std::string> defaultTransforms;
  defaultTransforms.push_back("AffineTransform_double_2_2");
  defaultTransforms.push_back("AffineTransform_double_3_3");
  defaultTransforms.push_back("AffineTransform_double_4_4");
  defaultTransforms.push_back("AffineTransform_double_5_5");
  defaultTransforms.push_back("AffineTransform_double_6_6");
  defaultTransforms.push_back("AffineTransform_double_7_7");
  defaultTransforms.push_back("AffineTransform_double_8_8");
  defaultTransforms.push_back("AffineTransform_double_9_9");
  defaultTransforms.push_back("IdentityTransform_double_2_2");
  defaultTransforms.push_back("IdentityTransform_double_3_3");
  defaultTransforms.push_back("IdentityTransform_double_4_4");
  defaultTransforms.push_back("IdentityTransform_double_5_5");
  defaultTransforms.push_back("IdentityTransform_double_6_6");
  defaultTransforms.push_back("IdentityTransform_double_7_7");
  defaultTransforms.push_back("IdentityTransform_double_8_8");
  defaultTransforms.push_back("IdentityTransform_double_9_9");
  defaultTransforms.push_back("BSplineTransform_double_2_2");
  defaultTransforms.push_back("BSplineTransform_double_3_3");
#ifdef ITKV3_COMPATIBILITY
  defaultTransforms.push_back("BSplineDeformableTransform_double_2_2");
  defaultTransforms.push_back("BSplineDeformableTransform_double_3_3");
#endif
  defaultTransforms.push_back("CenteredAffineTransform_double_2_2");
  defaultTransforms.push_back("CenteredAffineTransform_double_3_3");
  defaultTransforms.push_back("CenteredEuler3DTransform_double_3_3");
  defaultTransforms.push_back("CenteredRigid2DTransform_double_2_2");
  defaultTransforms.push_back("CenteredSimilarity2DTransform_double_2_2");
  defaultTransforms.push_back("Euler2DTransform_double_2_2");
  defaultTransforms.push_back("Euler3DTransform_double_3_3");
  defaultTransforms.push_back("FixedCenterOfRotationAffineTransform_double_3_3");
  defaultTransforms.push_back("QuaternionRigidTransform_double_3_3");
  defaultTransforms.push_back("Rigid2DTransform_double_2_2");
  defaultTransforms.push_back("Rigid3DPerspectiveTransform_double_3_2");
  defaultTransforms.push_back("Rigid3DTransform_double_3_3");
  defaultTransforms.push_back("ScalableAffineTransform_double_3_3");
  defaultTransforms.push_back("ScaleLogarithmicTransform_double_3_3");
  defaultTransforms.push_back("ScaleVersor3DTransform_double_3_3");
  defaultTransforms.push_back("ScaleSkewVersor3DTransform_double_3_3");
  defaultTransforms.push_back("ScaleTransform_double_2_2");
  defaultTransforms.push_back("ScaleTransform_double_3_3");
  defaultTransforms.push_back("ScaleTransform_double_4_4");
  defaultTransforms.push_back("TranslationTransform_double_3_3");
  defaultTransforms.push_back("VersorRigid3DTransform_double_3_3");
  defaultTransforms.push_back("VersorTransform_double_3_3");
  defaultTransforms.push_back("Similarity2DTransform_double_2_2");

  defaultTransforms.push_back("AffineTransform_float_2_2");
  defaultTransforms.push_back("AffineTransform_float_3_3");
  defaultTransforms.push_back("AffineTransform_float_4_4");
  defaultTransforms.push_back("AffineTransform_float_5_5");
  defaultTransforms.push_back("AffineTransform_float_6_6");
  defaultTransforms.push_back("AffineTransform_float_7_7");
  defaultTransforms.push_back("AffineTransform_float_8_8");
  defaultTransforms.push_back("AffineTransform_float_9_9");
  defaultTransforms.push_back("IdentityTransform_float_2_2");
  defaultTransforms.push_back("IdentityTransform_float_3_3");
  defaultTransforms.push_back("IdentityTransform_float_4_4");
  defaultTransforms.push_back("IdentityTransform_float_5_5");
  defaultTransforms.push_back("IdentityTransform_float_6_6");
  defaultTransforms.push_back("IdentityTransform_float_7_7");
  defaultTransforms.push_back("IdentityTransform_float_8_8");
  defaultTransforms.push_back("IdentityTransform_float_9_9");
  defaultTransforms.push_back("BSplineTransform_float_2_2");
  defaultTransforms.push_back("BSplineTransform_float_3_3");
#ifdef ITKV3_COMPATIBILITY
  defaultTransforms.push_back("BSplineDeformableTransform_float_2_2");
  defaultTransforms.push_back("BSplineDeformableTransform_float_3_3");
#endif
  defaultTransforms.push_back("CenteredAffineTransform_float_2_2");
  defaultTransforms.push_back("CenteredAffineTransform_float_3_3");
  defaultTransforms.push_back("CenteredEuler3DTransform_float_3_3");
  defaultTransforms.push_back("CenteredRigid2DTransform_float_2_2");
  defaultTransforms.push_back("CenteredSimilarity2DTransform_float_2_2");
  defaultTransforms.push_back("Euler2DTransform_float_2_2");
  defaultTransforms.push_back("Euler3DTransform_float_3_3");
  defaultTransforms.push_back("FixedCenterOfRotationAffineTransform_float_3_3");
  defaultTransforms.push_back("QuaternionRigidTransform_float_3_3");
  defaultTransforms.push_back("Rigid2DTransform_float_2_2");
  defaultTransforms.push_back("Rigid3DPerspectiveTransform_float_3_2");
  defaultTransforms.push_back("Rigid3DTransform_float_3_3");
  defaultTransforms.push_back("ScalableAffineTransform_float_3_3");
  defaultTransforms.push_back("ScaleLogarithmicTransform_float_3_3");
  defaultTransforms.push_back("ScaleVersor3DTransform_float_3_3");
  defaultTransforms.push_back("ScaleSkewVersor3DTransform_float_3_3");
  defaultTransforms.push_back("ScaleTransform_float_2_2");
  defaultTransforms.push_back("ScaleTransform_float_3_3");
  defaultTransforms.push_back("ScaleTransform_float_4_4");
  defaultTransforms.push_back("TranslationTransform_float_3_3");
  defaultTransforms.push_back("VersorRigid3DTransform_float_3_3");
  defaultTransforms.push_back("VersorTransform_float_3_3");
  defaultTransforms.push_back("Similarity2DTransform_float_2_2");

  // add composites
  defaultTransforms.push_back("CompositeTransform_double_2_2");
  defaultTransforms.push_back("CompositeTransform_double_3_3");
  defaultTransforms.push_back("CompositeTransform_double_4_4");
  defaultTransforms.push_back("CompositeTransform_double_5_5");
  defaultTransforms.push_back("CompositeTransform_double_6_6");
  defaultTransforms.push_back("CompositeTransform_double_7_7");
  defaultTransforms.push_back("CompositeTransform_double_8_8");
  defaultTransforms.push_back("CompositeTransform_double_9_9");
  defaultTransforms.push_back("CompositeTransform_float_2_2");
  defaultTransforms.push_back("CompositeTransform_float_3_3");
  defaultTransforms.push_back("CompositeTransform_float_4_4");
  defaultTransforms.push_back("CompositeTransform_float_5_5");
  defaultTransforms.push_back("CompositeTransform_float_6_6");
  defaultTransforms.push_back("CompositeTransform_float_7_7");
  defaultTransforms.push_back("CompositeTransform_float_8_8");
  defaultTransforms.push_back("CompositeTransform_float_9_9");

  // check to make sure that all default transforms have been registered
  defaultTransforms.sort();
  // Print out the names of all the registered transforms
  std::list<std::string> names = itk::TransformFactoryBase::GetFactory()->GetClassOverrideWithNames();
  names.sort();
  std::list<std::string>::iterator namesIt;
  std::list<std::string>::iterator defaultsIt;
  for (namesIt = names.begin(), defaultsIt = defaultTransforms.begin();
       namesIt != names.end(), defaultsIt != defaultTransforms.end();
       namesIt++, defaultsIt++)
    {
    if (strcmp((*namesIt).c_str(), (*defaultsIt).c_str()) != 0)
      {
      std::cout << "[FAILED] " << *defaultsIt << " not registered properly with defaults" << std::endl;
      return EXIT_FAILURE;
      }
    else
      {
      std::cout << "[SUCCESS] " << *defaultsIt << " registered properly" << std::endl;
      }
    }

  // test other methods
  itk::TransformFactoryBase::Pointer base = itk::TransformFactoryBase::New();
  const char* itkVersion = base->GetITKSourceVersion();
  const char* description = base->GetDescription();
  const char* type = base->GetNameOfClass();
  if (strcmp(itkVersion, ITK_SOURCE_VERSION) != 0)
    {
    std::cout << "[FAILED] Did not report version correctly" << std::endl;
    }
  else
    {
    std::cout << "[SUCCESS] Reported version correctly as " << itkVersion << std::endl;
    }
  if (strcmp(description, "Transform FactoryBase") != 0)
    {
    std::cout << "[FAILED] Did not report description correctly" << std::endl;
    }
  else
    {
    std::cout << "[SUCCESS] Reported description correctly as " << description << std::endl;
    }
  if (strcmp(type, "TransformFactoryBase") != 0)
    {
    std::cout << "[FAILED] Did not report type correctly" << std::endl;
    }
  else
    {
    std::cout << "[SUCCESS] Reported type correctly as " << type << std::endl;
    }

  // return successfully
  return EXIT_SUCCESS;

}
<|endoftext|>


<commit_before>/*************************************************************************
* Copyright(c) 1998-2008, ALICE Experiment at CERN, All rights reserved. *
*                                                                        *
* Author: The ALICE Off-line Project.                                    *
* Contributors are mentioned in the code where appropriate.              *
*                                                                        *
* Permission to use, copy, modify and distribute this software and its   *
* documentation strictly for non-commercial purposes is hereby granted   *
* without fee, provided that the above copyright notice appears in all   *
* copies and that both the copyright notice and this permission notice   *
* appear in the supporting documentation. The authors make no claims     *
* about the suitability of this software for any purpose. It is          *
* provided "as is" without express or implied warranty.                  *
**************************************************************************/

/**********************************
 * create an event and perform    *
 * flow analysis 'on the fly'     *
 *                                *
 * authors: Raimond Snellings     *
 *           (snelling@nikhef.nl) *
 *          Ante Bilandzic        *
 *           (anteb@nikhef.nl)    *
 *********************************/

#include "Riostream.h"
#include "TMath.h"
#include "TF1.h"
#include "TRandom3.h"

#include "AliFlowEventSimpleMakerOnTheFly.h"
#include "AliFlowEventSimple.h"
#include "AliFlowTrackSimple.h"

ClassImp(AliFlowEventSimpleMakerOnTheFly)

//========================================================================

AliFlowEventSimpleMakerOnTheFly::AliFlowEventSimpleMakerOnTheFly(UInt_t iseed):
  fMultiplicityOfRP(0),
  fMultiplicitySpreadOfRP(0.),
  fV1RP(0.),
  fV1SpreadRP(0.),
  fV2RP(0.),
  fV2SpreadRP(0.),
  fPtSpectra(NULL),
  fPhiDistribution(NULL),
  fMyTRandom3(NULL),
  fCount(0),
  fNoOfLoops(1)
 {
  // constructor
   fMyTRandom3 = new TRandom3(iseed);
 }

//========================================================================

AliFlowEventSimpleMakerOnTheFly::~AliFlowEventSimpleMakerOnTheFly()
{
 // destructor
  if (fPtSpectra) delete fPtSpectra;
  if (fPhiDistribution) delete fPhiDistribution;
  if (fMyTRandom3) delete  fMyTRandom3;
}

//========================================================================

AliFlowEventSimple* AliFlowEventSimpleMakerOnTheFly::CreateEventOnTheFly()
{
  // method to create event on the fly

  AliFlowEventSimple* pEvent = new AliFlowEventSimple(fMultiplicityOfRP);

  //reaction plane
  Double_t fMCReactionPlaneAngle = fMyTRandom3->Uniform(0.,TMath::TwoPi());

  // pt:
  Double_t dPtMin = 0.; // to be improved
  Double_t dPtMax = 10.; // to be improved

  fPtSpectra = new TF1("fPtSpectra","[0]*x*TMath::Exp(-x*x)",dPtMin,dPtMax);
  fPtSpectra->SetParName(0,"Multiplicity of RPs");
  // sampling the multiplicity:
  Int_t fNewMultiplicityOfRP = fMyTRandom3->Gaus(fMultiplicityOfRP,fMultiplicitySpreadOfRP);
  fPtSpectra->SetParameter(0,fNewMultiplicityOfRP);

  // phi:
  Double_t dPhiMin = 0.; // to be improved
  Double_t dPhiMax = TMath::TwoPi(); // to be improved

  fPhiDistribution = new TF1("fPhiDistribution","1+2.*[0]*TMath::Cos(x)+2.*[1]*TMath::Cos(2*x)",dPhiMin,dPhiMax);

  // sampling the V1:
  fPhiDistribution->SetParName(0,"directed flow");
  Double_t fNewV1RP=0.;
  if(fV1RP>0.0) {fNewV1RP = fMyTRandom3->Gaus(fV1RP,fV1SpreadRP);}
  fPhiDistribution->SetParameter(0,fNewV1RP);

  // sampling the V2:
  fPhiDistribution->SetParName(1,"elliptic flow");
  Double_t fNewV2RP = fMyTRandom3->Gaus(fV2RP,fV2SpreadRP);
  fPhiDistribution->SetParameter(1,fNewV2RP);

  // eta:
  Double_t dEtaMin = -1.; // to be improved
  Double_t dEtaMax = 1.; // to be improved

  Int_t iGoodTracks = 0;
  Int_t iSelParticlesRP = 0;
  Int_t iSelParticlesPOI = 0;
  Double_t fTmpPt =0;
  Double_t fTmpEta =0;
  Double_t fTmpPhi =0;
  for(Int_t i=0;i<fNewMultiplicityOfRP;i++) {
    fTmpPt = fPtSpectra->GetRandom();
    fTmpEta = fMyTRandom3->Uniform(dEtaMin,dEtaMax);
    fTmpPhi = fPhiDistribution->GetRandom()+fMCReactionPlaneAngle;
    for(Int_t d=0;d<fNoOfLoops;d++) {
      AliFlowTrackSimple* pTrack = new AliFlowTrackSimple();
      pTrack->SetPt(fTmpPt);
      pTrack->SetEta(fTmpEta);
      pTrack->SetPhi(fTmpPhi);
      pTrack->SetForRPSelection(kTRUE);
      iSelParticlesRP++;
      pTrack->SetForPOISelection(kTRUE);
      iSelParticlesPOI++;
      pEvent->TrackCollection()->Add(pTrack);
      iGoodTracks++;
    }
  }

  pEvent->SetEventNSelTracksRP(iSelParticlesRP);
  pEvent->SetNumberOfTracks(iGoodTracks);//tracks used either for RP or for POI selection
  pEvent->SetMCReactionPlaneAngle(fMCReactionPlaneAngle);

  if (!fMCReactionPlaneAngle == 0) cout<<" MC Reaction Plane Angle = "<<  fMCReactionPlaneAngle << endl;
  else cout<<" MC Reaction Plane Angle = unknown "<< endl;

  cout<<" iGoodTracks = "<< iGoodTracks << endl;
  cout<<" # of RP selected tracks = "<<iSelParticlesRP<<endl;
  cout<<" # of POI selected tracks = "<<iSelParticlesPOI<<endl;
  cout << "# " << ++fCount << " events processed" << endl;

  delete fPhiDistribution;
  delete fPtSpectra;
  return pEvent;

} // end of CreateEventOnTheFly()

<commit_msg>fix random distribution<commit_after>/*************************************************************************
* Copyright(c) 1998-2008, ALICE Experiment at CERN, All rights reserved. *
*                                                                        *
* Author: The ALICE Off-line Project.                                    *
* Contributors are mentioned in the code where appropriate.              *
*                                                                        *
* Permission to use, copy, modify and distribute this software and its   *
* documentation strictly for non-commercial purposes is hereby granted   *
* without fee, provided that the above copyright notice appears in all   *
* copies and that both the copyright notice and this permission notice   *
* appear in the supporting documentation. The authors make no claims     *
* about the suitability of this software for any purpose. It is          *
* provided "as is" without express or implied warranty.                  *
**************************************************************************/

/**********************************
 * create an event and perform    *
 * flow analysis 'on the fly'     *
 *                                *
 * authors: Raimond Snellings     *
 *           (snelling@nikhef.nl) *
 *          Ante Bilandzic        *
 *           (anteb@nikhef.nl)    *
 *********************************/

#include "Riostream.h"
#include "TMath.h"
#include "TF1.h"
#include "TRandom3.h"

#include "AliFlowEventSimpleMakerOnTheFly.h"
#include "AliFlowEventSimple.h"
#include "AliFlowTrackSimple.h"

ClassImp(AliFlowEventSimpleMakerOnTheFly)

//========================================================================

AliFlowEventSimpleMakerOnTheFly::AliFlowEventSimpleMakerOnTheFly(UInt_t iseed):
  fMultiplicityOfRP(0),
  fMultiplicitySpreadOfRP(0.),
  fV1RP(0.),
  fV1SpreadRP(0.),
  fV2RP(0.),
  fV2SpreadRP(0.),
  fPtSpectra(NULL),
  fPhiDistribution(NULL),
  fMyTRandom3(NULL),
  fCount(0),
  fNoOfLoops(1)
 {
  // constructor
   fMyTRandom3 = new TRandom3(iseed);
 }

//========================================================================

AliFlowEventSimpleMakerOnTheFly::~AliFlowEventSimpleMakerOnTheFly()
{
 // destructor
  if (fPtSpectra) delete fPtSpectra;
  if (fPhiDistribution) delete fPhiDistribution;
  if (fMyTRandom3) delete  fMyTRandom3;
}

//========================================================================

AliFlowEventSimple* AliFlowEventSimpleMakerOnTheFly::CreateEventOnTheFly()
{
  // method to create event on the fly

  AliFlowEventSimple* pEvent = new AliFlowEventSimple(fMultiplicityOfRP);

  // pt:
  Double_t dPtMin = 0.; // to be improved
  Double_t dPtMax = 10.; // to be improved

  fPtSpectra = new TF1("fPtSpectra","[0]*x*TMath::Exp(-x*x)",dPtMin,dPtMax);
  fPtSpectra->SetParName(0,"Multiplicity of RPs");
  // sampling the multiplicity:
  Int_t fNewMultiplicityOfRP = fMyTRandom3->Gaus(fMultiplicityOfRP,fMultiplicitySpreadOfRP);
  fPtSpectra->SetParameter(0,fNewMultiplicityOfRP);

  // phi:
  Double_t dPhiMin = 0.; // to be improved
  Double_t dPhiMax = TMath::TwoPi(); // to be improved

  fPhiDistribution = new TF1("fPhiDistribution","1+2.*[0]*TMath::Cos(x-[2])+2.*[1]*TMath::Cos(2*(x-[2]))",dPhiMin,dPhiMax);

  // samling the reaction plane
  Double_t fMCReactionPlaneAngle = fMyTRandom3->Uniform(0.,TMath::TwoPi());
  fPhiDistribution->SetParName(2,"Reaction Plane");
  fPhiDistribution->SetParameter(2,fMCReactionPlaneAngle);

  // sampling the V1:
  fPhiDistribution->SetParName(0,"directed flow");
  Double_t fNewV1RP=fV1RP;
  if(fV1SpreadRP>0.0) {fNewV1RP = fMyTRandom3->Gaus(fV1RP,fV1SpreadRP);}
  fPhiDistribution->SetParameter(0,fNewV1RP);

  // sampling the V2:
  fPhiDistribution->SetParName(1,"elliptic flow");
  Double_t fNewV2RP = fV2RP;
  if(fV2SpreadRP>0.0) fNewV2RP = fMyTRandom3->Gaus(fV2RP,fV2SpreadRP);
  fPhiDistribution->SetParameter(1,fNewV2RP);

  // eta:
  Double_t dEtaMin = -1.; // to be improved
  Double_t dEtaMax = 1.; // to be improved

  Int_t iGoodTracks = 0;
  Int_t iSelParticlesRP = 0;
  Int_t iSelParticlesPOI = 0;
  Double_t fTmpPt =0;
  Double_t fTmpEta =0;
  Double_t fTmpPhi =0;

  for(Int_t i=0;i<fNewMultiplicityOfRP;i++) {
    fTmpPt = fPtSpectra->GetRandom();
    fTmpEta = fMyTRandom3->Uniform(dEtaMin,dEtaMax);
    fTmpPhi = fPhiDistribution->GetRandom();
    for(Int_t d=0;d<fNoOfLoops;d++) {
      AliFlowTrackSimple* pTrack = new AliFlowTrackSimple();
      pTrack->SetPt(fTmpPt);
      pTrack->SetEta(fTmpEta);
      pTrack->SetPhi(fTmpPhi);
      pTrack->SetForRPSelection(kTRUE);
      iSelParticlesRP++;
      pTrack->SetForPOISelection(kTRUE);
      iSelParticlesPOI++;
      pEvent->TrackCollection()->Add(pTrack);
      iGoodTracks++;
    }
  }

  pEvent->SetEventNSelTracksRP(iSelParticlesRP);
  pEvent->SetNumberOfTracks(iGoodTracks);//tracks used either for RP or for POI selection
  pEvent->SetMCReactionPlaneAngle(fMCReactionPlaneAngle);

  if (!fMCReactionPlaneAngle == 0) cout<<" MC Reaction Plane Angle = "<<  fMCReactionPlaneAngle << endl;
  else cout<<" MC Reaction Plane Angle = unknown "<< endl;

  cout<<" iGoodTracks = "<< iGoodTracks << endl;
  cout<<" # of RP selected tracks = "<<iSelParticlesRP<<endl;
  cout<<" # of POI selected tracks = "<<iSelParticlesPOI<<endl;
  cout << "# " << ++fCount << " events processed" << endl;

  delete fPhiDistribution;
  delete fPtSpectra;
  return pEvent;

} // end of CreateEventOnTheFly()

<|endoftext|>


<commit_before>{
  {
    mode: "dorian",
    progression: "1,2,1,5,5,2,2,4,5,2",
    origin: "white stripes - little apple blossom"
  },
  {
    mode: "dorian",
    progression: "1,7,4,4",
    origin: "depeche mode - never let me down"
  },
  {
    mode: "minor",
    progression: "1,7,4,6",
    origin: "cure - the figurehead"
  },
  {
    mode: "minor",
    progression: "1,3,6,4",
    origin: "??"
  },
  {
    mode: "minor",
    progression: "1,4,6,4",
    origin: "??"
  },
  {
    mode: "harmonic_minor",
    progression: "1,4,6,57",
    origin: "amy whinehouse - back to black"
  },
  {
    mode: "minor",
    progression: "1,3,7,1,7,5,1,1",
    origin: "dolly parton - jolene"
  },
  {
    mode: "dorian",
    progression: "1,5,1,5,1,5,3,4,7,7",
    origin: "beatles - and I love her"
  },
  {
    mode: "major",
    progression: "1,3,5,5",
    origin: "queen of the stone age - go with the flow"
  }
  {
    mode: "major",
    progression: "5,5,1,4,5,1,4,bIII"
  }
}
<commit_msg>more progression<commit_after>{
  {
    mode: "dorian",
    progression: "1,2,1,5,5,2,2,4,5,2",
    origin: "white stripes - little apple blossom"
  },
  {
    mode: "dorian",
    progression: "1,7,4,4",
    origin: "depeche mode - never let me down"
  },
  {
    mode: "minor",
    progression: "1,7,4,6",
    origin: "cure - the figurehead"
  },
  {
    mode: "minor",
    progression: "1,3,6,4",
    origin: "??"
  },
  {
    mode: "minor",
    progression: "1,4,6,4",
    origin: "??"
  },
  {
    mode: "harmonic_minor",
    progression: "1,4,6,57",
    origin: "amy whinehouse - back to black"
  },
  {
    mode: "minor",
    progression: "1,3,7,1,7,5,1,1",
    origin: "dolly parton - jolene"
  },
  {
    mode: "dorian",
    progression: "1,5,1,5,1,5,3,4,7,7",
    origin: "beatles - and I love her"
  },
  {
    mode: "major",
    progression: "1,3,5,5",
    origin: "queen of the stone age - go with the flow"
  }
  {
    mode: "major",
    progression: "5,5,1,4,5,1,4,bIII".
    origin: "kinks - lola"
  }
  {
    mode: "minor",
    progression: "1, 7m, 3m, 3m",
    origin: "rob - maniac (altered)"
  }
}
<|endoftext|>


<commit_before>/*
 * File:  deletions.cpp
 * Copyright (C) 2004 The Institute for System Programming of the Russian Academy of Sciences (ISP RAS)
 */

#include "common/sedna.h"

#include "tr/updates/updates.h"
#include "tr/executor/base/xptr_sequence.h"
#include "tr/mo/micro.h"
#include "tr/auth/auc.h"
#ifdef SE_ENABLE_TRIGGERS
#include "tr/triggers/triggers.h"
#endif

void delete_undeep(PPOpIn arg)
{
	// Creating the first sequence (different validity tests+ indirection deref)
	tuple t(arg.ts);
	xptr_sequence argseq;
	arg.op->next(t);
	while (!t.is_eos())
	{
		if (t.cells[0].is_node())
		{
			xptr node=t.cells[0].get_node();
			CHECKP(node);
			if (is_node_persistent(node)&& !is_node_document(node))
			{
				//xptr indir=((n_dsc*)XADDR(node))->indir;
				argseq.add(node);
			}
#ifndef IGNORE_UPDATE_ERRORS
			else
			{
				throw USER_EXCEPTION(SE2010);
			}
#endif
		}
#ifndef IGNORE_UPDATE_ERRORS
			else
			{
				throw USER_EXCEPTION(SE2011);
			}
#endif
		arg.op->next(t);
	}

	//Sort in document order
	if (argseq.size()<=0) return;
	argseq.sort();
	// INDIR
	xptr_sequence::iterator it=argseq.begin();
	xptr node;
	while (it!=argseq.end())
	{
		node=*it;
		CHECKP(node);
		xptr indir=((n_dsc*)XADDR(node))->indir;
		argseq.set(indir,it);
		it++;
	}
	// Checking authorization
	if (is_auth_check_needed(DELETE_STATEMENT))
		auth_for_update(&argseq, DELETE_STATEMENT, false);

	//  cycle on  sequence
#ifdef SE_ENABLE_FTSEARCH
	clear_ft_sequences();
#endif
#ifdef SE_ENABLE_TRIGGERS
	apply_per_statement_triggers(&argseq, false, NULL, false, TRIGGER_BEFORE, TRIGGER_DELETE_EVENT);
#endif
	it=argseq.end();
	do
	{
		--it;
		xptr node=removeIndirection(*it);
		CHECKP(node);
		{
			t_item type=GETTYPE((GETBLOCKBYNODE(node))->snode);
			switch(type)
			{
			case attribute: case text: case comment: case pr_ins:
				{
				 delete_node(node);
				 break;
				}
			case element:
				{
					xptr indir=*it;
					//1.INSERT
					xptr parent=removeIndirection(((n_dsc*)XADDR(node))->pdsc);
					copy_content(parent,node,node);
					//2.DELETE
					CHECKP(indir);
					delete_node(*((xptr*)XADDR(indir)));
				}
			}
		}

		if (it==argseq.begin()) break;
	}
	while (true);
#ifdef SE_ENABLE_FTSEARCH
	execute_modifications();
#endif
#ifdef SE_ENABLE_TRIGGERS
    apply_per_statement_triggers(NULL, false, NULL, false, TRIGGER_AFTER, TRIGGER_DELETE_EVENT);
#endif
}
void delete_deep(PPOpIn arg)
{
	// Creating the first sequence (different validity tests+ indirection deref)
	/*xptr blk(0,(void*)0x33fd0000);
	CHECKP(blk)
	{shft hh_size=HHSIZE(blk);
		for (int i=0; i<hh_size; i++)
		{
			hh_slot* tmp = (hh_slot*)HH_ADDR(blk, i);
			if (tmp->hole_shft+ tmp->hole_size==SSB(blk) )
			{
				throw SYSTEM_EXCEPTION("[pstr_deallocate()] string can not be adjacent with with SS tail and with some hole on the right simultaneously");
			}
		}
	}*/
	tuple t(arg.ts);
	xptr_sequence argseq;
	arg.op->next(t);
	while (!t.is_eos())
	{
		if (t.cells[0].is_node())
		{
			xptr node=t.cells[0].get_node();
//			node.print();
			CHECKP(node);
			if (is_node_persistent(node) ) argseq.add(node);
#ifndef IGNORE_UPDATE_ERRORS
			else
			{
				throw USER_EXCEPTION(SE2012);
			}
#endif
		}
#ifndef IGNORE_UPDATE_ERRORS
			else
			{
				throw USER_EXCEPTION(SE2011);
			}
#endif
		arg.op->next(t);
	}

	// Checking authorization
	if (is_auth_check_needed(DELETE_STATEMENT))
		auth_for_update(&argseq, DELETE_STATEMENT, true);

	//Sort in document order
	if (argseq.size()<=0) return;

	//!!! debug
	/*
	xptr_sequence::iterator my_it;
	for (my_it = argseq.begin(); my_it != argseq.end(); my_it++)
	{
		xptr p = argseq.get(my_it);
		p.print();
	}
	*/
#ifdef SE_ENABLE_FTSEARCH
	clear_ft_sequences();
#endif
#ifdef SE_ENABLE_TRIGGERS
	apply_per_statement_triggers(&argseq, true, NULL, false, TRIGGER_BEFORE, TRIGGER_DELETE_EVENT);
#endif

	argseq.sort();
	//  cycle on  sequence
	xptr_sequence::iterator it=argseq.begin();
	bool mark=false;
    xptr tmp_node, parent;
	do
	{
		xptr node=*it;
		do
		{
			if (it+1==argseq.end()) {mark=true; break;}
			++it;
		}
		while (nid_ancestor(node,*it));
/*#ifdef SE_ENABLE_TRIGGERS
        tmp_node = copy_to_temp(node);
		schema_node* scm_node=GETSCHEMENODEX(node);
        parent=removeIndirection(((n_dsc*)XADDR(node))->pdsc);

        if (apply_per_node_triggers(XNULL, node, XNULL, NULL, TRIGGER_BEFORE, TRIGGER_DELETE_EVENT) != XNULL)
    	{
        	delete_node(node);
            apply_per_node_triggers(XNULL, tmp_node, parent, scm_node, TRIGGER_AFTER, TRIGGER_DELETE_EVENT);
        }
#else
        delete_node(node);
#endif*/
        delete_node(node);
		if (mark) break;
	}
	while (true);
#ifdef SE_ENABLE_FTSEARCH
	execute_modifications();
#endif
#ifdef SE_ENABLE_TRIGGERS
    apply_per_statement_triggers(NULL, false, NULL, false, TRIGGER_AFTER, TRIGGER_DELETE_EVENT);
#endif
}<commit_msg>delete fix<commit_after>/*
 * File:  deletions.cpp
 * Copyright (C) 2004 The Institute for System Programming of the Russian Academy of Sciences (ISP RAS)
 */

#include "common/sedna.h"

#include "tr/updates/updates.h"
#include "tr/executor/base/xptr_sequence.h"
#include "tr/mo/micro.h"
#include "tr/auth/auc.h"
#ifdef SE_ENABLE_TRIGGERS
#include "tr/triggers/triggers.h"
#endif

void delete_undeep(PPOpIn arg)
{
	// Creating the first sequence (different validity tests+ indirection deref)
	tuple t(arg.ts);
	xptr_sequence argseq;
	arg.op->next(t);
	while (!t.is_eos())
	{
		if (t.cells[0].is_node())
		{
			xptr node=t.cells[0].get_node();
			CHECKP(node);
			if (is_node_persistent(node)&& !is_node_document(node))
			{
				//xptr indir=((n_dsc*)XADDR(node))->indir;
				argseq.add(node);
			}
#ifndef IGNORE_UPDATE_ERRORS
			else
			{
				throw USER_EXCEPTION(SE2010);
			}
#endif
		}
#ifndef IGNORE_UPDATE_ERRORS
			else
			{
				throw USER_EXCEPTION(SE2011);
			}
#endif
		arg.op->next(t);
	}

	//Sort in document order
	if (argseq.size()<=0) return;
	argseq.sort();
	// INDIR
	xptr_sequence::iterator it=argseq.begin();
	xptr node;
	while (it!=argseq.end())
	{
		node=*it;
		CHECKP(node);
		xptr indir=((n_dsc*)XADDR(node))->indir;
		argseq.set(indir,it);
		it++;
	}
	// Checking authorization
	if (is_auth_check_needed(DELETE_STATEMENT))
		auth_for_update(&argseq, DELETE_STATEMENT, false);

	//  cycle on  sequence
#ifdef SE_ENABLE_FTSEARCH
	clear_ft_sequences();
#endif
#ifdef SE_ENABLE_TRIGGERS
	apply_per_statement_triggers(&argseq, false, NULL, false, TRIGGER_BEFORE, TRIGGER_DELETE_EVENT);
#endif
	it=argseq.end();
	do
	{
		--it;
		xptr node=removeIndirection(*it);
		CHECKP(node);
		{
			t_item type=GETTYPE((GETBLOCKBYNODE(node))->snode);
			switch(type)
			{
			case attribute: case text: case comment: case pr_ins:
				{
				 delete_node(node);
				 break;
				}
			case element:
				{
					xptr indir=*it;
					//1.INSERT
					xptr parent=removeIndirection(((n_dsc*)XADDR(node))->pdsc);
					copy_content(parent,node,node);
					//2.DELETE
					CHECKP(indir);
					delete_node(*((xptr*)XADDR(indir)));
				}
			}
		}

		if (it==argseq.begin()) break;
	}
	while (true);
#ifdef SE_ENABLE_FTSEARCH
	execute_modifications();
#endif
#ifdef SE_ENABLE_TRIGGERS
    apply_per_statement_triggers(NULL, false, NULL, false, TRIGGER_AFTER, TRIGGER_DELETE_EVENT);
#endif
}
void delete_deep(PPOpIn arg)
{
	// Creating the first sequence (different validity tests+ indirection deref)
	/*xptr blk(0,(void*)0x33fd0000);
	CHECKP(blk)
	{shft hh_size=HHSIZE(blk);
		for (int i=0; i<hh_size; i++)
		{
			hh_slot* tmp = (hh_slot*)HH_ADDR(blk, i);
			if (tmp->hole_shft+ tmp->hole_size==SSB(blk) )
			{
				throw SYSTEM_EXCEPTION("[pstr_deallocate()] string can not be adjacent with with SS tail and with some hole on the right simultaneously");
			}
		}
	}*/
	tuple t(arg.ts);
	xptr_sequence argseq;
	arg.op->next(t);
	while (!t.is_eos())
	{
		if (t.cells[0].is_node())
		{
			xptr node=t.cells[0].get_node();
//			node.print();
			CHECKP(node);
			if (is_node_persistent(node) ) argseq.add(node);
#ifndef IGNORE_UPDATE_ERRORS
			else
			{
				throw USER_EXCEPTION(SE2012);
			}
#endif
		}
#ifndef IGNORE_UPDATE_ERRORS
			else
			{
				throw USER_EXCEPTION(SE2011);
			}
#endif
		arg.op->next(t);
	}

	// Checking authorization
	if (is_auth_check_needed(DELETE_STATEMENT))
		auth_for_update(&argseq, DELETE_STATEMENT, true);

	//Sort in document order
	if (argseq.size()<=0) return;

	//!!! debug
	/*
	xptr_sequence::iterator my_it;
	for (my_it = argseq.begin(); my_it != argseq.end(); my_it++)
	{
		xptr p = argseq.get(my_it);
		p.print();
	}
	*/
#ifdef SE_ENABLE_FTSEARCH
	clear_ft_sequences();
#endif
#ifdef SE_ENABLE_TRIGGERS
	apply_per_statement_triggers(&argseq, true, NULL, false, TRIGGER_BEFORE, TRIGGER_DELETE_EVENT);
#endif

	argseq.sort();
	//  cycle on  sequence
	xptr_sequence::iterator it=argseq.begin();
	bool mark=false;
    xptr tmp_node, parent;
	do
	{
		xptr node=*it;
		do
		{
			if (it+1==argseq.end()) {mark=true; break;}
			++it;
		}
		while ((node == *it) || nid_ancestor(node,*it));
/*#ifdef SE_ENABLE_TRIGGERS
        tmp_node = copy_to_temp(node);
		schema_node* scm_node=GETSCHEMENODEX(node);
        parent=removeIndirection(((n_dsc*)XADDR(node))->pdsc);

        if (apply_per_node_triggers(XNULL, node, XNULL, NULL, TRIGGER_BEFORE, TRIGGER_DELETE_EVENT) != XNULL)
    	{
        	delete_node(node);
            apply_per_node_triggers(XNULL, tmp_node, parent, scm_node, TRIGGER_AFTER, TRIGGER_DELETE_EVENT);
        }
#else
        delete_node(node);
#endif*/
        	delete_node(node);
		if (mark) break;
	}
	while (true);
#ifdef SE_ENABLE_FTSEARCH
	execute_modifications();
#endif
#ifdef SE_ENABLE_TRIGGERS
    apply_per_statement_triggers(NULL, false, NULL, false, TRIGGER_AFTER, TRIGGER_DELETE_EVENT);
#endif
}
<|endoftext|>


<commit_before>#include <kdebug.h>

#include "certificatewizardimpl.h"

/*
 *  Constructs a CertificateWizardImpl which is a child of 'parent', with the
 *  name 'name' and widget flags set to 'f'
 *
 *  The wizard will by default be modeless, unless you set 'modal' to
 *  TRUE to construct a modal wizard.
 */
CertificateWizardImpl::CertificateWizardImpl( QWidget* parent,  const char* name, bool modal, WFlags fl )
    : CertificateWizard( parent, name, modal, fl )
{
}

/*
 *  Destroys the object and frees any allocated resources
 */
CertificateWizardImpl::~CertificateWizardImpl()
{
    // no need to delete child widgets, Qt does it all for us
}

/*
 * protected slot
 */
void CertificateWizardImpl::slotCreatePSE()
{
    kdWarning() << "CertificateWizardImpl::slotCreatePSE() not yet implemented!" << endl;
}

#include "certificatewizardimpl.moc"
<commit_msg>CVS_SILENT yet another diff massage<commit_after>#include "certificatewizardimpl.h"
#include <kdebug.h>
/*
 *  Constructs a CertificateWizardImpl which is a child of 'parent', with the
 *  name 'name' and widget flags set to 'f'
 *
 *  The wizard will by default be modeless, unless you set 'modal' to
 *  TRUE to construct a modal wizard.
 */
CertificateWizardImpl::CertificateWizardImpl( QWidget* parent,  const char* name, bool modal, WFlags fl )
    : CertificateWizard( parent, name, modal, fl )
{
}

/*
 *  Destroys the object and frees any allocated resources
 */
CertificateWizardImpl::~CertificateWizardImpl()
{
    // no need to delete child widgets, Qt does it all for us
}

/*
 * protected slot
 */
void CertificateWizardImpl::slotCreatePSE()
{
    kdWarning() << "CertificateWizardImpl::slotCreatePSE() not yet implemented!" << endl;
}

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


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

#include "config.h"
#include "bindings/core/v8/CustomElementConstructorBuilder.h"

#include "bindings/core/v8/CustomElementBinding.h"
#include "bindings/core/v8/DOMWrapperWorld.h"
#include "bindings/core/v8/ExceptionState.h"
#include "bindings/core/v8/V8Binding.h"
#include "bindings/core/v8/V8Document.h"
#include "bindings/core/v8/V8HTMLElement.h"
#include "bindings/core/v8/V8HiddenValue.h"
#include "bindings/core/v8/V8PerContextData.h"
#include "bindings/core/v8/V8SVGElement.h"
#include "core/HTMLNames.h"
#include "core/SVGNames.h"
#include "core/dom/Document.h"
#include "core/dom/ElementRegistrationOptions.h"
#include "core/dom/custom/CustomElementDefinition.h"
#include "core/dom/custom/CustomElementDescriptor.h"
#include "core/dom/custom/CustomElementException.h"
#include "core/dom/custom/CustomElementProcessingStack.h"
#include "wtf/Assertions.h"

namespace blink {

static void constructCustomElement(const v8::FunctionCallbackInfo<v8::Value>&);

CustomElementConstructorBuilder::CustomElementConstructorBuilder(ScriptState* scriptState, const ElementRegistrationOptions& options)
    : m_scriptState(scriptState)
    , m_options(options)
{
    ASSERT(m_scriptState->context() == m_scriptState->isolate()->GetCurrentContext());
}

bool CustomElementConstructorBuilder::isFeatureAllowed() const
{
    return m_scriptState->world().isMainWorld();
}

bool CustomElementConstructorBuilder::validateOptions(const AtomicString& type, QualifiedName& tagName, ExceptionState& exceptionState)
{
    ASSERT(m_prototype.IsEmpty());

    v8::TryCatch tryCatch;

    if (!m_scriptState->perContextData()) {
        // FIXME: This should generate an InvalidContext exception at a later point.
        CustomElementException::throwException(CustomElementException::ContextDestroyedCheckingPrototype, type, exceptionState);
        tryCatch.ReThrow();
        return false;
    }

    if (m_options.hasPrototype()) {
        ASSERT(m_options.prototype().isObject());
        m_prototype = m_options.prototype().v8Value().As<v8::Object>();
    } else {
        m_prototype = v8::Object::New(m_scriptState->isolate());
        v8::Local<v8::Object> basePrototype = m_scriptState->perContextData()->prototypeForType(&V8HTMLElement::wrapperTypeInfo);
        if (!basePrototype.IsEmpty())
            m_prototype->SetPrototype(basePrototype);
    }

    AtomicString namespaceURI = HTMLNames::xhtmlNamespaceURI;
    if (hasValidPrototypeChainFor(&V8SVGElement::wrapperTypeInfo))
        namespaceURI = SVGNames::svgNamespaceURI;

    ASSERT(!tryCatch.HasCaught());

    AtomicString localName;

    if (m_options.hasExtends()) {
        localName = AtomicString(m_options.extends().lower());

        if (!Document::isValidName(localName)) {
            CustomElementException::throwException(CustomElementException::ExtendsIsInvalidName, type, exceptionState);
            tryCatch.ReThrow();
            return false;
        }
        if (CustomElement::isValidName(localName)) {
            CustomElementException::throwException(CustomElementException::ExtendsIsCustomElementName, type, exceptionState);
            tryCatch.ReThrow();
            return false;
        }
    } else {
        if (namespaceURI == SVGNames::svgNamespaceURI) {
            CustomElementException::throwException(CustomElementException::ExtendsIsInvalidName, type, exceptionState);
            tryCatch.ReThrow();
            return false;
        }
        localName = type;
    }

    ASSERT(!tryCatch.HasCaught());
    tagName = QualifiedName(nullAtom, localName, namespaceURI);
    return true;
}

PassRefPtrWillBeRawPtr<CustomElementLifecycleCallbacks> CustomElementConstructorBuilder::createCallbacks()
{
    ASSERT(!m_prototype.IsEmpty());

    v8::TryCatch exceptionCatcher;
    exceptionCatcher.SetVerbose(true);

    v8::Isolate* isolate = m_scriptState->isolate();
    v8::Handle<v8::Function> created = retrieveCallback(isolate, "createdCallback");
    v8::Handle<v8::Function> attached = retrieveCallback(isolate, "attachedCallback");
    v8::Handle<v8::Function> detached = retrieveCallback(isolate, "detachedCallback");
    v8::Handle<v8::Function> attributeChanged = retrieveCallback(isolate, "attributeChangedCallback");

    m_callbacks = V8CustomElementLifecycleCallbacks::create(m_scriptState.get(), m_prototype, created, attached, detached, attributeChanged);
    return m_callbacks.get();
}

v8::Handle<v8::Function> CustomElementConstructorBuilder::retrieveCallback(v8::Isolate* isolate, const char* name)
{
    v8::Handle<v8::Value> value = m_prototype->Get(v8String(isolate, name));
    if (value.IsEmpty() || !value->IsFunction())
        return v8::Handle<v8::Function>();
    return value.As<v8::Function>();
}

bool CustomElementConstructorBuilder::createConstructor(Document* document, CustomElementDefinition* definition, ExceptionState& exceptionState)
{
    ASSERT(!m_prototype.IsEmpty());
    ASSERT(m_constructor.IsEmpty());
    ASSERT(document);

    v8::Isolate* isolate = m_scriptState->isolate();

    if (!prototypeIsValid(definition->descriptor().type(), exceptionState))
        return false;

    v8::Local<v8::FunctionTemplate> constructorTemplate = v8::FunctionTemplate::New(isolate);
    constructorTemplate->SetCallHandler(constructCustomElement);
    m_constructor = constructorTemplate->GetFunction();
    if (m_constructor.IsEmpty()) {
        CustomElementException::throwException(CustomElementException::ContextDestroyedRegisteringDefinition, definition->descriptor().type(), exceptionState);
        return false;
    }

    const CustomElementDescriptor& descriptor = definition->descriptor();

    v8::Handle<v8::String> v8TagName = v8String(isolate, descriptor.localName());
    v8::Handle<v8::Value> v8Type;
    if (descriptor.isTypeExtension())
        v8Type = v8String(isolate, descriptor.type());
    else
        v8Type = v8::Null(isolate);

    m_constructor->SetName(v8Type->IsNull() ? v8TagName : v8Type.As<v8::String>());

    V8HiddenValue::setHiddenValue(isolate, m_constructor, V8HiddenValue::customElementDocument(isolate), toV8(document, m_scriptState->context()->Global(), isolate));
    V8HiddenValue::setHiddenValue(isolate, m_constructor, V8HiddenValue::customElementNamespaceURI(isolate), v8String(isolate, descriptor.namespaceURI()));
    V8HiddenValue::setHiddenValue(isolate, m_constructor, V8HiddenValue::customElementTagName(isolate), v8TagName);
    V8HiddenValue::setHiddenValue(isolate, m_constructor, V8HiddenValue::customElementType(isolate), v8Type);

    v8::Handle<v8::String> prototypeKey = v8String(isolate, "prototype");
    ASSERT(m_constructor->HasOwnProperty(prototypeKey));
    // This sets the property *value*; calling Set is safe because
    // "prototype" is a non-configurable data property so there can be
    // no side effects.
    m_constructor->Set(prototypeKey, m_prototype);
    // This *configures* the property. ForceSet of a function's
    // "prototype" does not affect the value, but can reconfigure the
    // property.
    m_constructor->ForceSet(prototypeKey, m_prototype, v8::PropertyAttribute(v8::ReadOnly | v8::DontEnum | v8::DontDelete));

    V8HiddenValue::setHiddenValue(isolate, m_prototype, V8HiddenValue::customElementIsInterfacePrototypeObject(isolate), v8::True(isolate));
    m_prototype->ForceSet(v8String(isolate, "constructor"), m_constructor, v8::DontEnum);

    return true;
}

bool CustomElementConstructorBuilder::prototypeIsValid(const AtomicString& type, ExceptionState& exceptionState) const
{
    if (m_prototype->InternalFieldCount() || !V8HiddenValue::getHiddenValue(m_scriptState->isolate(), m_prototype, V8HiddenValue::customElementIsInterfacePrototypeObject(m_scriptState->isolate())).IsEmpty()) {
        CustomElementException::throwException(CustomElementException::PrototypeInUse, type, exceptionState);
        return false;
    }

    if (m_prototype->GetPropertyAttributes(v8String(m_scriptState->isolate(), "constructor")) & v8::DontDelete) {
        CustomElementException::throwException(CustomElementException::ConstructorPropertyNotConfigurable, type, exceptionState);
        return false;
    }

    return true;
}

bool CustomElementConstructorBuilder::didRegisterDefinition(CustomElementDefinition* definition) const
{
    ASSERT(!m_constructor.IsEmpty());

    return m_callbacks->setBinding(definition, CustomElementBinding::create(m_scriptState->isolate(), m_prototype));
}

ScriptValue CustomElementConstructorBuilder::bindingsReturnValue() const
{
    return ScriptValue(m_scriptState.get(), m_constructor);
}

bool CustomElementConstructorBuilder::hasValidPrototypeChainFor(const WrapperTypeInfo* type) const
{
    v8::Handle<v8::Object> elementPrototype = m_scriptState->perContextData()->prototypeForType(type);
    if (elementPrototype.IsEmpty())
        return false;

    v8::Handle<v8::Value> chain = m_prototype;
    while (!chain.IsEmpty() && chain->IsObject()) {
        if (chain == elementPrototype)
            return true;
        chain = chain.As<v8::Object>()->GetPrototype();
    }

    return false;
}

static void constructCustomElement(const v8::FunctionCallbackInfo<v8::Value>& info)
{
    v8::Isolate* isolate = info.GetIsolate();

    if (!info.IsConstructCall()) {
        V8ThrowException::throwTypeError(isolate, "DOM object constructor cannot be called as a function.");
        return;
    }

    if (info.Length() > 0) {
        V8ThrowException::throwTypeError(isolate, "This constructor should be called without arguments.");
        return;
    }

    Document* document = V8Document::toImpl(V8HiddenValue::getHiddenValue(info.GetIsolate(), info.Callee(), V8HiddenValue::customElementDocument(isolate)).As<v8::Object>());
    TOSTRING_VOID(V8StringResource<>, namespaceURI, V8HiddenValue::getHiddenValue(isolate, info.Callee(), V8HiddenValue::customElementNamespaceURI(isolate)));
    TOSTRING_VOID(V8StringResource<>, tagName, V8HiddenValue::getHiddenValue(isolate, info.Callee(), V8HiddenValue::customElementTagName(isolate)));
    v8::Handle<v8::Value> maybeType = V8HiddenValue::getHiddenValue(info.GetIsolate(), info.Callee(), V8HiddenValue::customElementType(isolate));
    TOSTRING_VOID(V8StringResource<>, type, maybeType);

    ExceptionState exceptionState(ExceptionState::ConstructionContext, "CustomElement", info.Holder(), info.GetIsolate());
    CustomElementProcessingStack::CallbackDeliveryScope deliveryScope;
    RefPtrWillBeRawPtr<Element> element = document->createElementNS(namespaceURI, tagName, maybeType->IsNull() ? nullAtom : type, exceptionState);
    if (exceptionState.throwIfNeeded())
        return;
    v8SetReturnValueFast(info, element.release(), document);
}

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

#include "config.h"
#include "bindings/core/v8/CustomElementConstructorBuilder.h"

#include "bindings/core/v8/CustomElementBinding.h"
#include "bindings/core/v8/DOMWrapperWorld.h"
#include "bindings/core/v8/ExceptionState.h"
#include "bindings/core/v8/V8Binding.h"
#include "bindings/core/v8/V8Document.h"
#include "bindings/core/v8/V8HTMLElement.h"
#include "bindings/core/v8/V8HiddenValue.h"
#include "bindings/core/v8/V8PerContextData.h"
#include "bindings/core/v8/V8SVGElement.h"
#include "core/HTMLNames.h"
#include "core/SVGNames.h"
#include "core/dom/Document.h"
#include "core/dom/ElementRegistrationOptions.h"
#include "core/dom/custom/CustomElementDefinition.h"
#include "core/dom/custom/CustomElementDescriptor.h"
#include "core/dom/custom/CustomElementException.h"
#include "core/dom/custom/CustomElementProcessingStack.h"
#include "wtf/Assertions.h"

namespace blink {

static void constructCustomElement(const v8::FunctionCallbackInfo<v8::Value>&);

CustomElementConstructorBuilder::CustomElementConstructorBuilder(ScriptState* scriptState, const ElementRegistrationOptions& options)
    : m_scriptState(scriptState)
    , m_options(options)
{
    ASSERT(m_scriptState->context() == m_scriptState->isolate()->GetCurrentContext());
}

bool CustomElementConstructorBuilder::isFeatureAllowed() const
{
    return m_scriptState->world().isMainWorld();
}

bool CustomElementConstructorBuilder::validateOptions(const AtomicString& type, QualifiedName& tagName, ExceptionState& exceptionState)
{
    ASSERT(m_prototype.IsEmpty());

    v8::TryCatch tryCatch;

    if (!m_scriptState->perContextData()) {
        // FIXME: This should generate an InvalidContext exception at a later point.
        CustomElementException::throwException(CustomElementException::ContextDestroyedCheckingPrototype, type, exceptionState);
        tryCatch.ReThrow();
        return false;
    }

    if (m_options.hasPrototype()) {
        ASSERT(m_options.prototype().isObject());
        m_prototype = m_options.prototype().v8Value().As<v8::Object>();
    } else {
        m_prototype = v8::Object::New(m_scriptState->isolate());
        v8::Local<v8::Object> basePrototype = m_scriptState->perContextData()->prototypeForType(&V8HTMLElement::wrapperTypeInfo);
        if (!basePrototype.IsEmpty())
            m_prototype->SetPrototype(basePrototype);
    }

    AtomicString namespaceURI = HTMLNames::xhtmlNamespaceURI;
    if (hasValidPrototypeChainFor(&V8SVGElement::wrapperTypeInfo))
        namespaceURI = SVGNames::svgNamespaceURI;

    ASSERT(!tryCatch.HasCaught());

    AtomicString localName;

    if (m_options.hasExtends()) {
        localName = AtomicString(m_options.extends().lower());

        if (!Document::isValidName(localName)) {
            CustomElementException::throwException(CustomElementException::ExtendsIsInvalidName, type, exceptionState);
            tryCatch.ReThrow();
            return false;
        }
        if (CustomElement::isValidName(localName)) {
            CustomElementException::throwException(CustomElementException::ExtendsIsCustomElementName, type, exceptionState);
            tryCatch.ReThrow();
            return false;
        }
    } else {
        if (namespaceURI == SVGNames::svgNamespaceURI) {
            CustomElementException::throwException(CustomElementException::ExtendsIsInvalidName, type, exceptionState);
            tryCatch.ReThrow();
            return false;
        }
        localName = type;
    }

    ASSERT(!tryCatch.HasCaught());
    tagName = QualifiedName(nullAtom, localName, namespaceURI);
    return true;
}

PassRefPtrWillBeRawPtr<CustomElementLifecycleCallbacks> CustomElementConstructorBuilder::createCallbacks()
{
    ASSERT(!m_prototype.IsEmpty());

    v8::TryCatch exceptionCatcher;
    exceptionCatcher.SetVerbose(true);

    v8::Isolate* isolate = m_scriptState->isolate();
    v8::Handle<v8::Function> created = retrieveCallback(isolate, "createdCallback");
    v8::Handle<v8::Function> attached = retrieveCallback(isolate, "attachedCallback");
    v8::Handle<v8::Function> detached = retrieveCallback(isolate, "detachedCallback");
    v8::Handle<v8::Function> attributeChanged = retrieveCallback(isolate, "attributeChangedCallback");

    m_callbacks = V8CustomElementLifecycleCallbacks::create(m_scriptState.get(), m_prototype, created, attached, detached, attributeChanged);
    return m_callbacks.get();
}

v8::Handle<v8::Function> CustomElementConstructorBuilder::retrieveCallback(v8::Isolate* isolate, const char* name)
{
    v8::Handle<v8::Value> value = m_prototype->Get(v8String(isolate, name));
    if (value.IsEmpty() || !value->IsFunction())
        return v8::Handle<v8::Function>();
    return value.As<v8::Function>();
}

bool CustomElementConstructorBuilder::createConstructor(Document* document, CustomElementDefinition* definition, ExceptionState& exceptionState)
{
    ASSERT(!m_prototype.IsEmpty());
    ASSERT(m_constructor.IsEmpty());
    ASSERT(document);

    v8::Isolate* isolate = m_scriptState->isolate();

    if (!prototypeIsValid(definition->descriptor().type(), exceptionState))
        return false;

    v8::Local<v8::FunctionTemplate> constructorTemplate = v8::FunctionTemplate::New(isolate);
    constructorTemplate->SetCallHandler(constructCustomElement);
    m_constructor = constructorTemplate->GetFunction();
    if (m_constructor.IsEmpty()) {
        CustomElementException::throwException(CustomElementException::ContextDestroyedRegisteringDefinition, definition->descriptor().type(), exceptionState);
        return false;
    }

    const CustomElementDescriptor& descriptor = definition->descriptor();

    v8::Handle<v8::String> v8TagName = v8String(isolate, descriptor.localName());
    v8::Handle<v8::Value> v8Type;
    if (descriptor.isTypeExtension())
        v8Type = v8String(isolate, descriptor.type());
    else
        v8Type = v8::Null(isolate);

    m_constructor->SetName(v8Type->IsNull() ? v8TagName : v8Type.As<v8::String>());

    V8HiddenValue::setHiddenValue(isolate, m_constructor, V8HiddenValue::customElementDocument(isolate), toV8(document, m_scriptState->context()->Global(), isolate));
    V8HiddenValue::setHiddenValue(isolate, m_constructor, V8HiddenValue::customElementNamespaceURI(isolate), v8String(isolate, descriptor.namespaceURI()));
    V8HiddenValue::setHiddenValue(isolate, m_constructor, V8HiddenValue::customElementTagName(isolate), v8TagName);
    V8HiddenValue::setHiddenValue(isolate, m_constructor, V8HiddenValue::customElementType(isolate), v8Type);

    v8::Handle<v8::String> prototypeKey = v8String(isolate, "prototype");
    ASSERT(m_constructor->HasOwnProperty(prototypeKey));
    // This sets the property *value*; calling Set is safe because
    // "prototype" is a non-configurable data property so there can be
    // no side effects.
    m_constructor->Set(prototypeKey, m_prototype);
    // This *configures* the property. ForceSet of a function's
    // "prototype" does not affect the value, but can reconfigure the
    // property.
    m_constructor->ForceSet(prototypeKey, m_prototype, v8::PropertyAttribute(v8::ReadOnly | v8::DontEnum | v8::DontDelete));

    V8HiddenValue::setHiddenValue(isolate, m_prototype, V8HiddenValue::customElementIsInterfacePrototypeObject(isolate), v8::True(isolate));
    m_prototype->ForceSet(v8String(isolate, "constructor"), m_constructor, v8::DontEnum);

    return true;
}

bool CustomElementConstructorBuilder::prototypeIsValid(const AtomicString& type, ExceptionState& exceptionState) const
{
    if (m_prototype->InternalFieldCount() || !V8HiddenValue::getHiddenValue(m_scriptState->isolate(), m_prototype, V8HiddenValue::customElementIsInterfacePrototypeObject(m_scriptState->isolate())).IsEmpty()) {
        CustomElementException::throwException(CustomElementException::PrototypeInUse, type, exceptionState);
        return false;
    }

    v8::PropertyAttribute propertyAttribute;
    if (!getValueFromMaybe(m_prototype->GetPropertyAttributes(m_scriptState->isolate()->GetCurrentContext(), v8String(m_scriptState->isolate(), "constructor")), propertyAttribute) || (propertyAttribute & v8::DontDelete)) {
        CustomElementException::throwException(CustomElementException::ConstructorPropertyNotConfigurable, type, exceptionState);
        return false;
    }

    return true;
}

bool CustomElementConstructorBuilder::didRegisterDefinition(CustomElementDefinition* definition) const
{
    ASSERT(!m_constructor.IsEmpty());

    return m_callbacks->setBinding(definition, CustomElementBinding::create(m_scriptState->isolate(), m_prototype));
}

ScriptValue CustomElementConstructorBuilder::bindingsReturnValue() const
{
    return ScriptValue(m_scriptState.get(), m_constructor);
}

bool CustomElementConstructorBuilder::hasValidPrototypeChainFor(const WrapperTypeInfo* type) const
{
    v8::Handle<v8::Object> elementPrototype = m_scriptState->perContextData()->prototypeForType(type);
    if (elementPrototype.IsEmpty())
        return false;

    v8::Handle<v8::Value> chain = m_prototype;
    while (!chain.IsEmpty() && chain->IsObject()) {
        if (chain == elementPrototype)
            return true;
        chain = chain.As<v8::Object>()->GetPrototype();
    }

    return false;
}

static void constructCustomElement(const v8::FunctionCallbackInfo<v8::Value>& info)
{
    v8::Isolate* isolate = info.GetIsolate();

    if (!info.IsConstructCall()) {
        V8ThrowException::throwTypeError(isolate, "DOM object constructor cannot be called as a function.");
        return;
    }

    if (info.Length() > 0) {
        V8ThrowException::throwTypeError(isolate, "This constructor should be called without arguments.");
        return;
    }

    Document* document = V8Document::toImpl(V8HiddenValue::getHiddenValue(info.GetIsolate(), info.Callee(), V8HiddenValue::customElementDocument(isolate)).As<v8::Object>());
    TOSTRING_VOID(V8StringResource<>, namespaceURI, V8HiddenValue::getHiddenValue(isolate, info.Callee(), V8HiddenValue::customElementNamespaceURI(isolate)));
    TOSTRING_VOID(V8StringResource<>, tagName, V8HiddenValue::getHiddenValue(isolate, info.Callee(), V8HiddenValue::customElementTagName(isolate)));
    v8::Handle<v8::Value> maybeType = V8HiddenValue::getHiddenValue(info.GetIsolate(), info.Callee(), V8HiddenValue::customElementType(isolate));
    TOSTRING_VOID(V8StringResource<>, type, maybeType);

    ExceptionState exceptionState(ExceptionState::ConstructionContext, "CustomElement", info.Holder(), info.GetIsolate());
    CustomElementProcessingStack::CallbackDeliveryScope deliveryScope;
    RefPtrWillBeRawPtr<Element> element = document->createElementNS(namespaceURI, tagName, maybeType->IsNull() ? nullAtom : type, exceptionState);
    if (exceptionState.throwIfNeeded())
        return;
    v8SetReturnValueFast(info, element.release(), document);
}

} // namespace blink
<|endoftext|>