<commit_before>/*

Copyright (c) 2008, Arvid Norberg
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 the author 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 "libtorrent/session.hpp"
#include "libtorrent/hasher.hpp"
#include "libtorrent/thread.hpp"
#include <boost/tuple/tuple.hpp>

#include "test.hpp"
#include "setup_transfer.hpp"
#include "libtorrent/extensions/metadata_transfer.hpp"
#include "libtorrent/extensions/ut_metadata.hpp"
#include <iostream>

using boost::tuples::ignore;

enum flags_t
{
	clear_files = 1,
	disconnect = 2,
	full_encryption = 4,
	reverse = 8
};

void test_transfer(int flags
	, boost::shared_ptr<libtorrent::torrent_plugin> (*constructor)(libtorrent::torrent*, void*)
	, int timeout)
{
	using namespace libtorrent;

	fprintf(stderr, "test transfer: timeout=%d %s%s%s\n"
		, timeout
		, (flags & clear_files) ? "clear-files " : ""
		, (flags & disconnect) ? "disconnect " : ""
		, (flags & full_encryption) ? "encryption " : "");

	// these are declared before the session objects
	// so that they are destructed last. This enables
	// the sessions to destruct in parallel
	session_proxy p1;
	session_proxy p2;

	// TODO: it would be nice to test reversing
	// which session is making the connection as well
	session ses1(fingerprint("LT", 0, 1, 0, 0), std::make_pair(48100, 49000), "0.0.0.0", 0);
	session ses2(fingerprint("LT", 0, 1, 0, 0), std::make_pair(49100, 50000), "0.0.0.0", 0);
	ses1.add_extension(constructor);
	ses2.add_extension(constructor);
	torrent_handle tor1;
	torrent_handle tor2;
#ifndef TORRENT_DISABLE_ENCRYPTION
	pe_settings pes;
	pes.prefer_rc4 = (flags & full_encryption);
	pes.out_enc_policy = pe_settings::forced;
	pes.in_enc_policy = pe_settings::forced;
	ses1.set_pe_settings(pes);
	ses2.set_pe_settings(pes);
#endif

	session* downloader = &ses2;
	session* seed = &ses1;

	if (flags & reverse)
	{
		std::swap(downloader, seed);
	}

	boost::tie(tor1, tor2, ignore) = setup_transfer(seed, downloader, NULL, flags & clear_files, true, true, "_meta");

	for (int i = 0; i < timeout * 10; ++i)
	{
		// make sure this function can be called on
		// torrents without metadata
		if ((flags & disconnect) == 0) tor2.status();
		print_alerts(*seed, "seed", false, true);
		print_alerts(*downloader, "downloader", false, true);

		if ((flags & disconnect) && tor2.is_valid()) downloader->remove_torrent(tor2);
		if ((flags & disconnect) == 0
			&& tor2.status().has_metadata) break;
		test_sleep(100);
	}

	if (flags & disconnect) goto done;

	TEST_CHECK(tor2.status().has_metadata);
	std::cerr << "waiting for transfer to complete\n";

	for (int i = 0; i < timeout * 10; ++i)
	{
		torrent_status st1 = tor1.status();
		torrent_status st2 = tor2.status();

		print_alerts(*seed, "seed", false, true);
		print_alerts(*downloader, "downloader", false, true);

		print_ses_rate(i / 10.f, &st1, &st2);
		if (st2.is_seeding) break;
		test_sleep(100);
	}

	TEST_CHECK(tor2.status().is_seeding);
	if (tor2.status().is_seeding) std::cerr << "done\n";

done:

	// this allows shutting down the sessions in parallel
	p1 = seed->abort();
	p2 = downloader->abort();

	error_code ec;
	remove_all("tmp1_meta", ec);
	remove_all("tmp2_meta", ec);
}

int test_main()
{
	using namespace libtorrent;

#ifdef TORRENT_USE_VALGRIND
	const int timeout = 8;
#else
	const int timeout = 3;
#endif

	test_transfer(full_encryption | reverse, &create_ut_metadata_plugin, 2);
	test_transfer(reverse, &create_ut_metadata_plugin, 2);

	for (int f = 0; f <= (clear_files | disconnect | full_encryption); ++f)
		test_transfer(f, &create_metadata_plugin, timeout * 2);

	for (int f = 0; f <= (clear_files | disconnect | full_encryption); ++f)
		test_transfer(f, &create_ut_metadata_plugin, timeout);

	error_code ec;
	remove_all("tmp1", ec);
	remove_all("tmp2", ec);

	return 0;
}

<commit_msg>fix valgrind run of test_metadata_extension<commit_after>/*

Copyright (c) 2008, Arvid Norberg
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 the author 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 "libtorrent/session.hpp"
#include "libtorrent/hasher.hpp"
#include "libtorrent/thread.hpp"
#include <boost/tuple/tuple.hpp>

#include "test.hpp"
#include "setup_transfer.hpp"
#include "libtorrent/extensions/metadata_transfer.hpp"
#include "libtorrent/extensions/ut_metadata.hpp"
#include <iostream>

using boost::tuples::ignore;

enum flags_t
{
	clear_files = 1,
	disconnect = 2,
	full_encryption = 4,
	reverse = 8
};

void test_transfer(int flags
	, boost::shared_ptr<libtorrent::torrent_plugin> (*constructor)(libtorrent::torrent*, void*)
	, int timeout)
{
	using namespace libtorrent;

	fprintf(stderr, "test transfer: timeout=%d %s%s%s\n"
		, timeout
		, (flags & clear_files) ? "clear-files " : ""
		, (flags & disconnect) ? "disconnect " : ""
		, (flags & full_encryption) ? "encryption " : "");

	// these are declared before the session objects
	// so that they are destructed last. This enables
	// the sessions to destruct in parallel
	session_proxy p1;
	session_proxy p2;

	// TODO: it would be nice to test reversing
	// which session is making the connection as well
	session ses1(fingerprint("LT", 0, 1, 0, 0), std::make_pair(48100, 49000), "0.0.0.0", 0);
	session ses2(fingerprint("LT", 0, 1, 0, 0), std::make_pair(49100, 50000), "0.0.0.0", 0);
	ses1.add_extension(constructor);
	ses2.add_extension(constructor);
	torrent_handle tor1;
	torrent_handle tor2;
#ifndef TORRENT_DISABLE_ENCRYPTION
	pe_settings pes;
	pes.prefer_rc4 = (flags & full_encryption);
	pes.out_enc_policy = pe_settings::forced;
	pes.in_enc_policy = pe_settings::forced;
	ses1.set_pe_settings(pes);
	ses2.set_pe_settings(pes);
#endif

	session* downloader = &ses2;
	session* seed = &ses1;

	if (flags & reverse)
	{
		std::swap(downloader, seed);
	}

	boost::tie(tor1, tor2, ignore) = setup_transfer(seed, downloader, NULL, flags & clear_files, true, true, "_meta");

	for (int i = 0; i < timeout * 10; ++i)
	{
		// make sure this function can be called on
		// torrents without metadata
		if ((flags & disconnect) == 0) tor2.status();
		print_alerts(*seed, "seed", false, true);
		print_alerts(*downloader, "downloader", false, true);

		if ((flags & disconnect) && tor2.is_valid()) downloader->remove_torrent(tor2);
		if ((flags & disconnect) == 0
			&& tor2.status().has_metadata) break;
		test_sleep(100);
	}

	if (flags & disconnect) goto done;

	TEST_CHECK(tor2.status().has_metadata);
	std::cerr << "waiting for transfer to complete\n";

	for (int i = 0; i < timeout * 10; ++i)
	{
		torrent_status st1 = tor1.status();
		torrent_status st2 = tor2.status();

		print_alerts(*seed, "seed", false, true);
		print_alerts(*downloader, "downloader", false, true);

		print_ses_rate(i / 10.f, &st1, &st2);
		if (st2.is_seeding) break;
		test_sleep(100);
	}

	TEST_CHECK(tor2.status().is_seeding);
	if (tor2.status().is_seeding) std::cerr << "done\n";

done:

	// this allows shutting down the sessions in parallel
	p1 = seed->abort();
	p2 = downloader->abort();

	error_code ec;
	remove_all("tmp1_meta", ec);
	remove_all("tmp2_meta", ec);
}

int test_main()
{
	using namespace libtorrent;

#ifdef TORRENT_USE_VALGRIND
	const int timeout = 8;
#else
	const int timeout = 3;
#endif

	test_transfer(full_encryption | reverse, &create_ut_metadata_plugin, timeout);
	test_transfer(reverse, &create_ut_metadata_plugin, timeout);

	for (int f = 0; f <= (clear_files | disconnect | full_encryption); ++f)
		test_transfer(f, &create_metadata_plugin, timeout * 2);

	for (int f = 0; f <= (clear_files | disconnect | full_encryption); ++f)
		test_transfer(f, &create_ut_metadata_plugin, timeout);

	error_code ec;
	remove_all("tmp1", ec);
	remove_all("tmp2", ec);

	return 0;
}

<|endoftext|>


<commit_before>#include "BasicExample.h"

#include "btBulletDynamicsCommon.h"
#define ARRAY_SIZE_Y 5
#define ARRAY_SIZE_X 5
#define ARRAY_SIZE_Z 5

#include "LinearMath/btVector3.h"
#include "LinearMath/btAlignedObjectArray.h"

#include "CommonInterfaces/CommonRigidBodyBase.h"
#ifndef M_PI
#define M_PI       3.14159265358979323846
#endif

#include "LinearHypothesis.h"
#include "ActionRecorder.h"

LinearHypothesis lh;
ActionRecorder AR;
bool needStuding = true;

int num = 0;
short collisionFilterGroup = short(btBroadphaseProxy::CharacterFilter);
short collisionFilterMask = short(btBroadphaseProxy::AllFilter ^ (btBroadphaseProxy::CharacterFilter));
static btScalar radius(0.2);

struct BasicExample : public CommonRigidBodyBase
{
	bool m_once;
	btAlignedObjectArray<btJointFeedback*> m_jointFeedback;
	btHingeConstraint* hinge;
	btRigidBody* linkBody;
	btVector3 groundOrigin_target;
	btRigidBody* body;
	btBoxShape* box;
	BasicExample(struct GUIHelperInterface* helper);
	virtual ~BasicExample();
	virtual void initPhysics();

	virtual void stepSimulation(float deltaTime);
	void lockLiftHinge(void);

	virtual bool keyboardCallback(int key, int state);
	virtual void resetCamera()
	{

		float dist = 5;
		float pitch = 270;
		float yaw = 21;
		float targetPos[3] = { -1.34,3.4,-0.44 };
		m_guiHelper->resetCamera(dist, pitch, yaw, targetPos[0], targetPos[1], targetPos[2]);
	}
};

BasicExample::BasicExample(struct GUIHelperInterface* helper)
	:CommonRigidBodyBase(helper),
	m_once(true)
{
}

BasicExample::~BasicExample()
{
	for (int i = 0; i<m_jointFeedback.size(); i++)
	{
		delete m_jointFeedback[i];
	}

}

/********************************************************************************************
* start custom Functions
*********************************************************************************************/

void initState(BasicExample* target) {
	target->m_guiHelper->removeAllGraphicsInstances();
	target->initPhysics();
}

void moveLeft(btHingeConstraint *target) {
	target->setLimit(-M_PI / 1.2f, M_PI / 1.2f);
	target->enableAngularMotor(true, -15.0, 4000.f);

}

void moveRight(btHingeConstraint *target) {
	target->setLimit(-M_PI / 1.2f, M_PI / 1.2f);
	target->enableAngularMotor(true, 15.0, 4000.f);
}

/********************************************************************************************
* end custom Functions
*********************************************************************************************/

void BasicExample::stepSimulation(float deltaTime)
{
	if (0)//m_once)
	{
		m_once = false;
		btHingeConstraint* hinge = (btHingeConstraint*)m_dynamicsWorld->getConstraint(0);

		btRigidBody& bodyA = hinge->getRigidBodyA();
		btTransform trA = bodyA.getWorldTransform();
		btVector3 hingeAxisInWorld = trA.getBasis()*hinge->getFrameOffsetA().getBasis().getColumn(2);
		hinge->getRigidBodyA().applyTorque(-hingeAxisInWorld * 10);
		hinge->getRigidBodyB().applyTorque(hingeAxisInWorld * 10);

	}

	//get distance
	btScalar distance = sqrt(pow((body->getCenterOfMassPosition().getZ() - linkBody->getCenterOfMassPosition().getZ()), 2) + pow((body->getCenterOfMassPosition().getY() - linkBody->getCenterOfMassPosition().getY()), 2)) - 0.225;
	//b3Printf("distance = %f\n", distance);

	//collison check
	int numManifolds = m_dynamicsWorld->getDispatcher()->getNumManifolds();
	for (int i = 0; i < numManifolds; i++)
	{
		if (m_dynamicsWorld->getDispatcher()->getNumManifolds() == 0) continue;
		btPersistentManifold* contactManifold = m_dynamicsWorld->getDispatcher()->getManifoldByIndexInternal(i);
		const btCollisionObject* obA = contactManifold->getBody0();
		const btCollisionObject* obB = contactManifold->getBody1();

		int numContacts = contactManifold->getNumContacts();
		for (int j = 0; j < numContacts; j++)
		{
			btManifoldPoint& pt = contactManifold->getContactPoint(j);
			if (pt.getDistance() < 0.f)
			{
				const btVector3& ptA = pt.getPositionWorldOnA();
				const btVector3& ptB = pt.getPositionWorldOnB();
				const btVector3& normalOnB = pt.m_normalWorldOnB;
				initState(this);
				b3Printf("check\n");

				/********************************************************************************************
				* start RL
				*********************************************************************************************/

				float lr = 0.5f;

				// LR
				for (int t = 0; t < 10000; t++) {
					for (int i = 0; i < AR.memory.num_elements; i++) {
						float a = (float)AR.memory.moved_array[i];
						float b = AR.memory.reward_array[i];

						const float error = b - lh.getY(a);
						const float sqr_error = 0.5 * error * error;

						const float da = 2.0 * error * -a;
						const float db = 2.0 * error * -1;

						lh.a -= da * lr;
						lh.b -= db * lr;
					}
				}

				needStuding = false;

				AR.clearHistory();

				/********************************************************************************************
				* end RL
				*********************************************************************************************/
			}
		}
	}

	/********************************************************************************************
	* start select Move
	*********************************************************************************************/

	int thisMoved = -1;

	if (needStuding) {
		// random move
		thisMoved = ((int)rand() % 2 == 0) ? (1) : (0);
	}
	else {
		// learned move
		thisMoved = (lh.getY(distance) >= 0.5) ? (0) : (1);
	}

	// moving
	if (thisMoved == ACT_MOVE_LEFT) {
		moveLeft(hinge);
	}
	else {
		moveRight(hinge);
	}

	// check current
	b3Printf("moved = %d\tdistance=%f\ttcurrent Y = %f\n", thisMoved, distance, lh.getY(distance));

	// Memory
	AR.recordHistory(thisMoved, distance);

	/********************************************************************************************
	* end select RL
	*********************************************************************************************/

	m_dynamicsWorld->stepSimulation(1. / 240, 0);

	static int count = 0;
}

void BasicExample::initPhysics()
{
	int upAxis = 1;
	m_guiHelper->setUpAxis(upAxis);

	createEmptyDynamicsWorld();
	m_dynamicsWorld->getSolverInfo().m_splitImpulse = false;

	m_dynamicsWorld->setGravity(btVector3(0, 0, -10));

	m_guiHelper->createPhysicsDebugDrawer(m_dynamicsWorld);
	int mode = btIDebugDraw::DBG_DrawWireframe
		+ btIDebugDraw::DBG_DrawConstraints
		+ btIDebugDraw::DBG_DrawConstraintLimits;
	m_dynamicsWorld->getDebugDrawer()->setDebugMode(mode);

	{ // create a door using hinge constraint attached to the world

		int numLinks = 2;
		bool spherical = false;					//set it ot false -to use 1DoF hinges instead of 3DoF sphericals
		bool canSleep = false;
		bool selfCollide = false;

		btVector3 baseHalfExtents(0.05, 0.37, 0.1);
		btVector3 linkHalfExtents(0.05, 0.37, 0.1);

		btBoxShape* baseBox = new btBoxShape(baseHalfExtents);
		btVector3 basePosition = btVector3(-0.4f, 4.f, 0.f);
		btTransform baseWorldTrans;
		baseWorldTrans.setIdentity();
		baseWorldTrans.setOrigin(basePosition);

		//mbC->forceMultiDof();							//if !spherical, you can comment this line to check the 1DoF algorithm
		//init the base
		btVector3 baseInertiaDiag(0.f, 0.f, 0.f);
		float baseMass = 0.f;
		float linkMass = 1.f;

		btRigidBody* base = createRigidBody(baseMass, baseWorldTrans, baseBox);
		m_dynamicsWorld->removeRigidBody(base);
		base->setDamping(0, 0);
		m_dynamicsWorld->addRigidBody(base, collisionFilterGroup, collisionFilterMask);
		btBoxShape* linkBox1 = new btBoxShape(linkHalfExtents);
		btSphereShape* linkSphere = new btSphereShape(radius);

		btRigidBody* prevBody = base;

		for (int i = 0; i<numLinks; i++)
		{
			btTransform linkTrans;
			linkTrans = baseWorldTrans;

			linkTrans.setOrigin(basePosition - btVector3(0, linkHalfExtents[1] * 2.f*(i + 1), 0));

			btCollisionShape* colOb = 0;

			if (i == 0)
			{
				colOb = linkBox1;
			}
			else
			{
				colOb = linkSphere;
			}
			linkBody = createRigidBody(linkMass, linkTrans, colOb);
			m_dynamicsWorld->removeRigidBody(linkBody);
			m_dynamicsWorld->addRigidBody(linkBody, collisionFilterGroup, collisionFilterMask);
			linkBody->setDamping(0, 0);
			btTypedConstraint* con = 0;

			if (i == 0)
			{
				//create a hinge constraint
				btVector3 pivotInA(0, -linkHalfExtents[1], 0);
				btVector3 pivotInB(0, linkHalfExtents[1], 0);
				btVector3 axisInA(1, 0, 0);
				btVector3 axisInB(1, 0, 0);
				bool useReferenceA = true;
				hinge = new btHingeConstraint(*prevBody, *linkBody,
					pivotInA, pivotInB,
					axisInA, axisInB, useReferenceA);
				hinge->setLimit(0.0f, 0.0f);
				m_dynamicsWorld->addConstraint(hinge, true);
				con = hinge;
			}
			else
			{
				btTransform pivotInA(btQuaternion::getIdentity(), btVector3(0, -radius, 0));						//par body's COM to cur body's COM offset
				btTransform pivotInB(btQuaternion::getIdentity(), btVector3(0, radius, 0));							//cur body's COM to cur body's PIV offset
				btGeneric6DofSpring2Constraint* fixed = new btGeneric6DofSpring2Constraint(*prevBody, *linkBody,
					pivotInA, pivotInB);
				fixed->setLinearLowerLimit(btVector3(0, 0, 0));
				fixed->setLinearUpperLimit(btVector3(0, 0, 0));
				fixed->setAngularLowerLimit(btVector3(0, 0, 0));
				fixed->setAngularUpperLimit(btVector3(0, 0, 0));

				con = fixed;

			}
			btAssert(con);
			if (con)
			{
				btJointFeedback* fb = new btJointFeedback();
				m_jointFeedback.push_back(fb);
				con->setJointFeedback(fb);

				m_dynamicsWorld->addConstraint(con, true);
			}
			prevBody = linkBody;

		}

	}

	if (1)
	{
		btVector3 groundHalfExtents(0.4, 0.0, 0.4);
		groundHalfExtents[upAxis] = 0.025f;
		btBoxShape* box = new btBoxShape(groundHalfExtents);
		box->initializePolyhedralFeatures();

		btTransform start; start.setIdentity();
		groundOrigin_target = btVector3(-0.4f, 3.9f, -0.77f);
		/*	btVector3 basePosition = btVector3(-0.4f, 3.f, 0.f);
		btQuaternion groundOrn(btVector3(0, 1, 0), 0.25*SIMD_PI);*/

		start.setOrigin(groundOrigin_target);
		body = createRigidBody(0, start, box);

		body->setFriction(0);

	}
	m_guiHelper->autogenerateGraphicsObjects(m_dynamicsWorld);
}

bool BasicExample::keyboardCallback(int key, int state)
{
	bool handled = false;
	if (state)
	{
		switch (key)
		{
		case B3G_HOME:
		{
			// b3Printf("Rest.\n");
			initState(this);
			break;
		}
		case B3G_LEFT_ARROW:
		{
			// b3Printf("left.\n");
			moveLeft(hinge);
			handled = true;
			break;

		}
		case B3G_RIGHT_ARROW:
		{
			// b3Printf("right.\n");
			moveRight(hinge);
			handled = true;
			break;
		}
		case B3G_UP_ARROW:
		{
			// b3Printf("left.\n");

			btVector3 basePosition = btVector3(0.0, 0.0f,1.54f);
			body->translate(basePosition);

			break;

		}
		case B3G_DOWN_ARROW:
		{
			// b3Printf("left.\n");

			btVector3 basePosition = btVector3(0.0, 0.0f, -0.77f);
			body->translate(basePosition);

			break;

		}
		}
	}
	else
	{
		switch (key)
		{
		case B3G_LEFT_ARROW:
		case B3G_RIGHT_ARROW:
		{

			lockLiftHinge();
			handled = true;
			break;
		}
		default:

			break;
		}
	}
	return handled;
}

void BasicExample::lockLiftHinge(void)
{
	btScalar hingeAngle = hinge->getHingeAngle();
	btScalar lowLim = hinge->getLowerLimit();
	btScalar hiLim = hinge->getUpperLimit();
	hinge->enableAngularMotor(false, 0, 0);

	if (hingeAngle < lowLim)
	{
		//		m_liftHinge->setLimit(lowLim, lowLim + LIFT_EPS);
		hinge->setLimit(lowLim, lowLim);
	}
	else if (hingeAngle > hiLim)
	{
		//		m_liftHinge->setLimit(hiLim - LIFT_EPS, hiLim);
		hinge->setLimit(hiLim, hiLim);
	}
	else
	{
		//		m_liftHinge->setLimit(hingeAngle - LIFT_EPS, hingeAngle + LIFT_EPS);
		hinge->setLimit(hingeAngle, hingeAngle);
	}
	return;
}

CommonExampleInterface*    BasicExampleCreateFunc(CommonExampleOptions& options)
{
	return new BasicExample(options.m_guiHelper);

}

B3_STANDALONE_EXAMPLE(BasicExampleCreateFunc)<commit_msg>check the distance<commit_after>#include "BasicExample.h"

#include "btBulletDynamicsCommon.h"
#define ARRAY_SIZE_Y 5
#define ARRAY_SIZE_X 5
#define ARRAY_SIZE_Z 5

#include "LinearMath/btVector3.h"
#include "LinearMath/btAlignedObjectArray.h"

#include "CommonInterfaces/CommonRigidBodyBase.h"
#ifndef M_PI
#define M_PI       3.14159265358979323846
#endif

#include "LinearHypothesis.h"
#include "ActionRecorder.h"

LinearHypothesis lh;
ActionRecorder AR;
bool needStuding = true;

int num = 0;
short collisionFilterGroup = short(btBroadphaseProxy::CharacterFilter);
short collisionFilterMask = short(btBroadphaseProxy::AllFilter ^ (btBroadphaseProxy::CharacterFilter));
static btScalar radius(0.2);

struct BasicExample : public CommonRigidBodyBase
{
	bool m_once;
	btScalar distance;
	btAlignedObjectArray<btJointFeedback*> m_jointFeedback;
	btHingeConstraint* hinge;
	btRigidBody* linkBody;
	btVector3 groundOrigin_target;
	btRigidBody* body;
	btBoxShape* box;
	BasicExample(struct GUIHelperInterface* helper);
	virtual ~BasicExample();
	virtual void initPhysics();

	virtual void stepSimulation(float deltaTime);
	void lockLiftHinge(void);

	virtual bool keyboardCallback(int key, int state);
	virtual void resetCamera()
	{

		float dist = 5;
		float pitch = 270;
		float yaw = 21;
		float targetPos[3] = { -1.34,3.4,-0.44 };
		m_guiHelper->resetCamera(dist, pitch, yaw, targetPos[0], targetPos[1], targetPos[2]);
	}
};

BasicExample::BasicExample(struct GUIHelperInterface* helper)
	:CommonRigidBodyBase(helper),
	m_once(true)
{
}

BasicExample::~BasicExample()
{
	for (int i = 0; i<m_jointFeedback.size(); i++)
	{
		delete m_jointFeedback[i];
	}

}

/********************************************************************************************
* start custom Functions
*********************************************************************************************/

void initState(BasicExample* target) {
	target->m_guiHelper->removeAllGraphicsInstances();
	target->initPhysics();
}

void moveLeft(btHingeConstraint *target) {
	target->setLimit(-M_PI / 1.2f, M_PI / 1.2f);
	target->enableAngularMotor(true, -15.0, 4000.f);

}

void moveRight(btHingeConstraint *target) {
	target->setLimit(-M_PI / 1.2f, M_PI / 1.2f);
	target->enableAngularMotor(true, 15.0, 4000.f);
}

/********************************************************************************************
* end custom Functions
*********************************************************************************************/

void BasicExample::stepSimulation(float deltaTime)
{
	if (0)//m_once)
	{
		m_once = false;
		btHingeConstraint* hinge = (btHingeConstraint*)m_dynamicsWorld->getConstraint(0);

		btRigidBody& bodyA = hinge->getRigidBodyA();
		btTransform trA = bodyA.getWorldTransform();
		btVector3 hingeAxisInWorld = trA.getBasis()*hinge->getFrameOffsetA().getBasis().getColumn(2);
		hinge->getRigidBodyA().applyTorque(-hingeAxisInWorld * 10);
		hinge->getRigidBodyB().applyTorque(hingeAxisInWorld * 10);

	}

	//get distance
	//check distance
	if (body->getCenterOfMassPosition().getZ() < 0)
		distance = sqrt(pow((body->getCenterOfMassPosition().getZ() - linkBody->getCenterOfMassPosition().getZ()), 2) + pow((body->getCenterOfMassPosition().getY() - linkBody->getCenterOfMassPosition().getY()), 2)) - 0.225;
	//b3Printf("distance = %f\n", distance);
	else
		distance = -sqrt(pow((body->getCenterOfMassPosition().getZ() - linkBody->getCenterOfMassPosition().getZ()), 2) + pow((body->getCenterOfMassPosition().getY() - linkBody->getCenterOfMassPosition().getY()), 2)) - 0.225;

	//collison check
	int numManifolds = m_dynamicsWorld->getDispatcher()->getNumManifolds();
	for (int i = 0; i < numManifolds; i++)
	{
		if (m_dynamicsWorld->getDispatcher()->getNumManifolds() == 0) continue;
		btPersistentManifold* contactManifold = m_dynamicsWorld->getDispatcher()->getManifoldByIndexInternal(i);
		const btCollisionObject* obA = contactManifold->getBody0();
		const btCollisionObject* obB = contactManifold->getBody1();

		int numContacts = contactManifold->getNumContacts();
		for (int j = 0; j < numContacts; j++)
		{
			btManifoldPoint& pt = contactManifold->getContactPoint(j);
			if (pt.getDistance() < 0.f)
			{
				const btVector3& ptA = pt.getPositionWorldOnA();
				const btVector3& ptB = pt.getPositionWorldOnB();
				const btVector3& normalOnB = pt.m_normalWorldOnB;
				initState(this);
				b3Printf("check\n");

				/********************************************************************************************
				* start RL
				*********************************************************************************************/

				float lr = 0.5f;

				// LR
				for (int t = 0; t < 10000; t++) {
					for (int i = 0; i < AR.memory.num_elements; i++) {
						float a = (float)AR.memory.moved_array[i];
						float b = AR.memory.reward_array[i];

						const float error = b - lh.getY(a);
						const float sqr_error = 0.5 * error * error;

						const float da = 2.0 * error * -a;
						const float db = 2.0 * error * -1;

						lh.a -= da * lr;
						lh.b -= db * lr;
					}
				}

				needStuding = false;

				AR.clearHistory();

				/********************************************************************************************
				* end RL
				*********************************************************************************************/
			}
		}
	}

	/********************************************************************************************
	* start select Move
	*********************************************************************************************/

	int thisMoved = -1;

	if (needStuding) {
		// random move
		thisMoved = ((int)rand() % 2 == 0) ? (1) : (0);
	}
	else {
		// learned move
		thisMoved = (lh.getY(distance) >= 0.5) ? (0) : (1);
	}

	// moving
	if (thisMoved == ACT_MOVE_LEFT) {
		moveLeft(hinge);
	}
	else {
		moveRight(hinge);
	}

	// check current
	b3Printf("moved = %d\tdistance=%f\ttcurrent Y = %f\n", thisMoved, distance, lh.getY(distance));

	// Memory
	AR.recordHistory(thisMoved, distance);

	/********************************************************************************************
	* end select RL
	*********************************************************************************************/

	m_dynamicsWorld->stepSimulation(1. / 240, 0);

	static int count = 0;
}

void BasicExample::initPhysics()
{
	int upAxis = 1;
	m_guiHelper->setUpAxis(upAxis);

	createEmptyDynamicsWorld();
	m_dynamicsWorld->getSolverInfo().m_splitImpulse = false;

	m_dynamicsWorld->setGravity(btVector3(0, 0, -10));

	m_guiHelper->createPhysicsDebugDrawer(m_dynamicsWorld);
	int mode = btIDebugDraw::DBG_DrawWireframe
		+ btIDebugDraw::DBG_DrawConstraints
		+ btIDebugDraw::DBG_DrawConstraintLimits;
	m_dynamicsWorld->getDebugDrawer()->setDebugMode(mode);

	{ // create a door using hinge constraint attached to the world

		int numLinks = 2;
		bool spherical = false;					//set it ot false -to use 1DoF hinges instead of 3DoF sphericals
		bool canSleep = false;
		bool selfCollide = false;

		btVector3 baseHalfExtents(0.05, 0.37, 0.1);
		btVector3 linkHalfExtents(0.05, 0.37, 0.1);

		btBoxShape* baseBox = new btBoxShape(baseHalfExtents);
		btVector3 basePosition = btVector3(-0.4f, 4.f, 0.f);
		btTransform baseWorldTrans;
		baseWorldTrans.setIdentity();
		baseWorldTrans.setOrigin(basePosition);

		//mbC->forceMultiDof();							//if !spherical, you can comment this line to check the 1DoF algorithm
		//init the base
		btVector3 baseInertiaDiag(0.f, 0.f, 0.f);
		float baseMass = 0.f;
		float linkMass = 1.f;

		btRigidBody* base = createRigidBody(baseMass, baseWorldTrans, baseBox);
		m_dynamicsWorld->removeRigidBody(base);
		base->setDamping(0, 0);
		m_dynamicsWorld->addRigidBody(base, collisionFilterGroup, collisionFilterMask);
		btBoxShape* linkBox1 = new btBoxShape(linkHalfExtents);
		btSphereShape* linkSphere = new btSphereShape(radius);

		btRigidBody* prevBody = base;

		for (int i = 0; i<numLinks; i++)
		{
			btTransform linkTrans;
			linkTrans = baseWorldTrans;

			linkTrans.setOrigin(basePosition - btVector3(0, linkHalfExtents[1] * 2.f*(i + 1), 0));

			btCollisionShape* colOb = 0;

			if (i == 0)
			{
				colOb = linkBox1;
			}
			else
			{
				colOb = linkSphere;
			}
			linkBody = createRigidBody(linkMass, linkTrans, colOb);
			m_dynamicsWorld->removeRigidBody(linkBody);
			m_dynamicsWorld->addRigidBody(linkBody, collisionFilterGroup, collisionFilterMask);
			linkBody->setDamping(0, 0);
			btTypedConstraint* con = 0;

			if (i == 0)
			{
				//create a hinge constraint
				btVector3 pivotInA(0, -linkHalfExtents[1], 0);
				btVector3 pivotInB(0, linkHalfExtents[1], 0);
				btVector3 axisInA(1, 0, 0);
				btVector3 axisInB(1, 0, 0);
				bool useReferenceA = true;
				hinge = new btHingeConstraint(*prevBody, *linkBody,
					pivotInA, pivotInB,
					axisInA, axisInB, useReferenceA);
				hinge->setLimit(0.0f, 0.0f);
				m_dynamicsWorld->addConstraint(hinge, true);
				con = hinge;
			}
			else
			{
				btTransform pivotInA(btQuaternion::getIdentity(), btVector3(0, -radius, 0));						//par body's COM to cur body's COM offset
				btTransform pivotInB(btQuaternion::getIdentity(), btVector3(0, radius, 0));							//cur body's COM to cur body's PIV offset
				btGeneric6DofSpring2Constraint* fixed = new btGeneric6DofSpring2Constraint(*prevBody, *linkBody,
					pivotInA, pivotInB);
				fixed->setLinearLowerLimit(btVector3(0, 0, 0));
				fixed->setLinearUpperLimit(btVector3(0, 0, 0));
				fixed->setAngularLowerLimit(btVector3(0, 0, 0));
				fixed->setAngularUpperLimit(btVector3(0, 0, 0));

				con = fixed;

			}
			btAssert(con);
			if (con)
			{
				btJointFeedback* fb = new btJointFeedback();
				m_jointFeedback.push_back(fb);
				con->setJointFeedback(fb);

				m_dynamicsWorld->addConstraint(con, true);
			}
			prevBody = linkBody;

		}

	}

	if (1)
	{
		btVector3 groundHalfExtents(0.4, 0.0, 0.4);
		groundHalfExtents[upAxis] = 0.025f;
		btBoxShape* box = new btBoxShape(groundHalfExtents);
		box->initializePolyhedralFeatures();

		btTransform start; start.setIdentity();
		groundOrigin_target = btVector3(-0.4f, 3.9f, -0.77f);
		/*	btVector3 basePosition = btVector3(-0.4f, 3.f, 0.f);
		btQuaternion groundOrn(btVector3(0, 1, 0), 0.25*SIMD_PI);*/

		start.setOrigin(groundOrigin_target);
		body = createRigidBody(0, start, box);

		body->setFriction(0);

	}
	m_guiHelper->autogenerateGraphicsObjects(m_dynamicsWorld);
}

bool BasicExample::keyboardCallback(int key, int state)
{
	bool handled = false;
	if (state)
	{
		switch (key)
		{
		case B3G_HOME:
		{
			// b3Printf("Rest.\n");
			initState(this);
			break;
		}
		case B3G_LEFT_ARROW:
		{
			// b3Printf("left.\n");
			moveLeft(hinge);
			handled = true;
			break;

		}
		case B3G_RIGHT_ARROW:
		{
			// b3Printf("right.\n");
			moveRight(hinge);
			handled = true;
			break;
		}
		case B3G_UP_ARROW:
		{
			// b3Printf("left.\n");

			btVector3 basePosition = btVector3(0.0, 0.0f,1.54f);
			body->translate(basePosition);

			break;

		}
		case B3G_DOWN_ARROW:
		{
			// b3Printf("left.\n");

			btVector3 basePosition = btVector3(0.0, 0.0f, -1.54f);
			body->translate(basePosition);

			break;

		}
		}
	}
	else
	{
		switch (key)
		{
		case B3G_LEFT_ARROW:
		case B3G_RIGHT_ARROW:
		{

			lockLiftHinge();
			handled = true;
			break;
		}
		default:

			break;
		}
	}
	return handled;
}

void BasicExample::lockLiftHinge(void)
{
	btScalar hingeAngle = hinge->getHingeAngle();
	btScalar lowLim = hinge->getLowerLimit();
	btScalar hiLim = hinge->getUpperLimit();
	hinge->enableAngularMotor(false, 0, 0);

	if (hingeAngle < lowLim)
	{
		//		m_liftHinge->setLimit(lowLim, lowLim + LIFT_EPS);
		hinge->setLimit(lowLim, lowLim);
	}
	else if (hingeAngle > hiLim)
	{
		//		m_liftHinge->setLimit(hiLim - LIFT_EPS, hiLim);
		hinge->setLimit(hiLim, hiLim);
	}
	else
	{
		//		m_liftHinge->setLimit(hingeAngle - LIFT_EPS, hingeAngle + LIFT_EPS);
		hinge->setLimit(hingeAngle, hingeAngle);
	}
	return;
}

CommonExampleInterface*    BasicExampleCreateFunc(CommonExampleOptions& options)
{
	return new BasicExample(options.m_guiHelper);

}

B3_STANDALONE_EXAMPLE(BasicExampleCreateFunc)<|endoftext|>


<commit_before>/*
 * Copyright (C) 2017-present ScyllaDB
 *
 */

/*
 * This file is part of Scylla.
 *
 * Scylla is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * Scylla is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with Scylla.  If not, see <http://www.gnu.org/licenses/>.
 */

#include <seastar/core/coroutine.hh>
#include "table_helper.hh"
#include "cql3/query_processor.hh"
#include "cql3/statements/create_table_statement.hh"
#include "cql3/statements/modification_statement.hh"
#include "replica/database.hh"
#include "service/migration_manager.hh"

future<> table_helper::setup_table(cql3::query_processor& qp, const sstring& create_cql) {
    auto db = qp.db();

    auto parsed = cql3::query_processor::parse_statement(create_cql);

    cql3::statements::raw::cf_statement* parsed_cf_stmt = static_cast<cql3::statements::raw::cf_statement*>(parsed.get());
    (void)parsed_cf_stmt->keyspace(); // This will assert if cql statement did not contain keyspace
    ::shared_ptr<cql3::statements::create_table_statement> statement =
                    static_pointer_cast<cql3::statements::create_table_statement>(
                                    parsed_cf_stmt->prepare(db, qp.get_cql_stats())->statement);
    auto schema = statement->get_cf_meta_data(db);

    if (db.has_schema(schema->ks_name(), schema->cf_name())) {
        return make_ready_future<>();
    }

    // Generate the CF UUID based on its KF names. This is needed to ensure that
    // all Nodes that create it would create it with the same UUID and we don't
    // hit the #420 issue.
    auto uuid = generate_legacy_id(schema->ks_name(), schema->cf_name());

    schema_builder b(schema);
    b.set_uuid(uuid);

    // We don't care it it fails really - this may happen due to concurrent
    // "CREATE TABLE" invocation on different Nodes.
    // The important thing is that it will converge eventually (some traces may
    // be lost in a process but that's ok).
    return qp.get_migration_manager().announce_new_column_family(b.build()).discard_result().handle_exception([] (auto ep) {});;
}

future<> table_helper::cache_table_info(cql3::query_processor& qp, service::query_state& qs) {
    if (!_prepared_stmt) {
        // if prepared statement has been invalidated - drop cached pointers
        _insert_stmt = nullptr;
    } else if (!_is_fallback_stmt) {
        // we've already prepared the non-fallback statement
        return now();
    }

    return qp.prepare(_insert_cql, qs.get_client_state(), false)
            .then([this] (shared_ptr<cql_transport::messages::result_message::prepared> msg_ptr) noexcept {
        _prepared_stmt = std::move(msg_ptr->get_prepared());
        shared_ptr<cql3::cql_statement> cql_stmt = _prepared_stmt->statement;
        _insert_stmt = dynamic_pointer_cast<cql3::statements::modification_statement>(cql_stmt);
        _is_fallback_stmt = false;
    }).handle_exception_type([this, &qs, &qp] (exceptions::invalid_request_exception& eptr) {
        // the non-fallback statement can't be prepared
        if (!_insert_cql_fallback) {
            return make_exception_future(eptr);
        }
        if (_is_fallback_stmt && _prepared_stmt) {
            // we have already prepared the fallback statement
            return now();
        }
        return qp.prepare(_insert_cql_fallback.value(), qs.get_client_state(), false)
                .then([this] (shared_ptr<cql_transport::messages::result_message::prepared> msg_ptr) noexcept {
            _prepared_stmt = std::move(msg_ptr->get_prepared());
            shared_ptr<cql3::cql_statement> cql_stmt = _prepared_stmt->statement;
            _insert_stmt = dynamic_pointer_cast<cql3::statements::modification_statement>(cql_stmt);
            _is_fallback_stmt = true;
        });
    }).handle_exception([this, &qp] (auto eptr) {
        // One of the possible causes for an error here could be the table that doesn't exist.
        //FIXME: discarded future.
        (void)setup_table(qp, _create_cql).discard_result();

        // We throw the bad_column_family exception because the caller
        // expects and accounts this type of errors.
        try {
            std::rethrow_exception(eptr);
        } catch (std::exception& e) {
            throw bad_column_family(_keyspace, _name, e);
        } catch (...) {
            throw bad_column_family(_keyspace, _name);
        }
    });
}

future<> table_helper::insert(cql3::query_processor& qp, service::query_state& qs, noncopyable_function<cql3::query_options ()> opt_maker) {
    return cache_table_info(qp, qs).then([this, &qp, &qs, opt_maker = std::move(opt_maker)] () mutable {
        return do_with(opt_maker(), [this, &qp, &qs] (auto& opts) {
            opts.prepare(_prepared_stmt->bound_names);
            return _insert_stmt->execute(qp, qs, opts);
        });
    }).discard_result();
}

future<> table_helper::setup_keyspace(cql3::query_processor& qp, std::string_view keyspace_name, sstring replication_factor, service::query_state& qs, std::vector<table_helper*> tables) {
    if (this_shard_id() != 0) {
        co_return;
    }

    if (std::any_of(tables.begin(), tables.end(), [&] (table_helper* t) { return t->_keyspace != keyspace_name; })) {
        throw std::invalid_argument("setup_keyspace called with table_helper for different keyspace");
    }

    data_dictionary::database db = qp.db();

    // Create a keyspace
    if (!db.has_keyspace(keyspace_name)) {
        std::map<sstring, sstring> opts;
        opts["replication_factor"] = replication_factor;
        auto ksm = keyspace_metadata::new_keyspace(keyspace_name, "org.apache.cassandra.locator.SimpleStrategy", std::move(opts), true);
        co_await qp.get_migration_manager().announce_new_keyspace(ksm);
    }

    qs.get_client_state().set_keyspace(db.real_database(), keyspace_name);

    // Create tables
    co_await parallel_for_each(tables, [&qp] (table_helper* t) {
        return table_helper::setup_table(qp, t->_create_cql);
    });
}
<commit_msg>table_helper: move schema creation code to use raft<commit_after>/*
 * Copyright (C) 2017-present ScyllaDB
 *
 */

/*
 * This file is part of Scylla.
 *
 * Scylla is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * Scylla is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with Scylla.  If not, see <http://www.gnu.org/licenses/>.
 */

#include <seastar/core/coroutine.hh>
#include "table_helper.hh"
#include "cql3/query_processor.hh"
#include "cql3/statements/create_table_statement.hh"
#include "cql3/statements/modification_statement.hh"
#include "replica/database.hh"
#include "service/migration_manager.hh"

future<> table_helper::setup_table(cql3::query_processor& qp, const sstring& create_cql) {
    auto db = qp.db();

    auto parsed = cql3::query_processor::parse_statement(create_cql);

    cql3::statements::raw::cf_statement* parsed_cf_stmt = static_cast<cql3::statements::raw::cf_statement*>(parsed.get());
    (void)parsed_cf_stmt->keyspace(); // This will assert if cql statement did not contain keyspace
    ::shared_ptr<cql3::statements::create_table_statement> statement =
                    static_pointer_cast<cql3::statements::create_table_statement>(
                                    parsed_cf_stmt->prepare(db, qp.get_cql_stats())->statement);
    auto schema = statement->get_cf_meta_data(db);

    if (db.has_schema(schema->ks_name(), schema->cf_name())) {
        co_return;
    }

    auto& mm = qp.get_migration_manager();

    co_await mm.schema_read_barrier();

    if (db.has_schema(schema->ks_name(), schema->cf_name())) { // re-check after read barrier
        co_return;
    }

    // Generate the CF UUID based on its KF names. This is needed to ensure that
    // all Nodes that create it would create it with the same UUID and we don't
    // hit the #420 issue.
    auto uuid = generate_legacy_id(schema->ks_name(), schema->cf_name());

    schema_builder b(schema);
    b.set_uuid(uuid);

    // We don't care it it fails really - this may happen due to concurrent
    // "CREATE TABLE" invocation on different Nodes.
    // The important thing is that it will converge eventually (some traces may
    // be lost in a process but that's ok).
    try {
        co_return co_await mm.announce(co_await mm.prepare_new_column_family_announcement(b.build()));
    } catch (...) {}
}

future<> table_helper::cache_table_info(cql3::query_processor& qp, service::query_state& qs) {
    if (!_prepared_stmt) {
        // if prepared statement has been invalidated - drop cached pointers
        _insert_stmt = nullptr;
    } else if (!_is_fallback_stmt) {
        // we've already prepared the non-fallback statement
        return now();
    }

    return qp.prepare(_insert_cql, qs.get_client_state(), false)
            .then([this] (shared_ptr<cql_transport::messages::result_message::prepared> msg_ptr) noexcept {
        _prepared_stmt = std::move(msg_ptr->get_prepared());
        shared_ptr<cql3::cql_statement> cql_stmt = _prepared_stmt->statement;
        _insert_stmt = dynamic_pointer_cast<cql3::statements::modification_statement>(cql_stmt);
        _is_fallback_stmt = false;
    }).handle_exception_type([this, &qs, &qp] (exceptions::invalid_request_exception& eptr) {
        // the non-fallback statement can't be prepared
        if (!_insert_cql_fallback) {
            return make_exception_future(eptr);
        }
        if (_is_fallback_stmt && _prepared_stmt) {
            // we have already prepared the fallback statement
            return now();
        }
        return qp.prepare(_insert_cql_fallback.value(), qs.get_client_state(), false)
                .then([this] (shared_ptr<cql_transport::messages::result_message::prepared> msg_ptr) noexcept {
            _prepared_stmt = std::move(msg_ptr->get_prepared());
            shared_ptr<cql3::cql_statement> cql_stmt = _prepared_stmt->statement;
            _insert_stmt = dynamic_pointer_cast<cql3::statements::modification_statement>(cql_stmt);
            _is_fallback_stmt = true;
        });
    }).handle_exception([this, &qp] (auto eptr) {
        // One of the possible causes for an error here could be the table that doesn't exist.
        //FIXME: discarded future.
        (void)qp.container().invoke_on(0, [create_cql = _create_cql] (cql3::query_processor& qp) -> future<> {
            co_return co_await table_helper::setup_table(qp, create_cql);
        });

        // We throw the bad_column_family exception because the caller
        // expects and accounts this type of errors.
        try {
            std::rethrow_exception(eptr);
        } catch (std::exception& e) {
            throw bad_column_family(_keyspace, _name, e);
        } catch (...) {
            throw bad_column_family(_keyspace, _name);
        }
    });
}

future<> table_helper::insert(cql3::query_processor& qp, service::query_state& qs, noncopyable_function<cql3::query_options ()> opt_maker) {
    return cache_table_info(qp, qs).then([this, &qp, &qs, opt_maker = std::move(opt_maker)] () mutable {
        return do_with(opt_maker(), [this, &qp, &qs] (auto& opts) {
            opts.prepare(_prepared_stmt->bound_names);
            return _insert_stmt->execute(qp, qs, opts);
        });
    }).discard_result();
}

future<> table_helper::setup_keyspace(cql3::query_processor& qp, std::string_view keyspace_name, sstring replication_factor, service::query_state& qs, std::vector<table_helper*> tables) {
    if (this_shard_id() != 0) {
        co_return;
    }

    if (std::any_of(tables.begin(), tables.end(), [&] (table_helper* t) { return t->_keyspace != keyspace_name; })) {
        throw std::invalid_argument("setup_keyspace called with table_helper for different keyspace");
    }

    data_dictionary::database db = qp.db();
    auto& mm = qp.get_migration_manager();

    if (!db.has_keyspace(keyspace_name)) {
        co_await mm.schema_read_barrier();

        // Create a keyspace
        if (!db.has_keyspace(keyspace_name)) {
            std::map<sstring, sstring> opts;
            opts["replication_factor"] = replication_factor;
            auto ksm = keyspace_metadata::new_keyspace(keyspace_name, "org.apache.cassandra.locator.SimpleStrategy", std::move(opts), true);
            co_await mm.announce(mm.prepare_new_keyspace_announcement(ksm));
        }
    }

    qs.get_client_state().set_keyspace(db.real_database(), keyspace_name);

    // Create tables
    co_await parallel_for_each(tables, [&qp] (table_helper* t) {
        return table_helper::setup_table(qp, t->_create_cql);
    });
}
<|endoftext|>


<commit_before>#include "LinearRegression.h"
#include <armadillo>
#include <assert.h>
#include <iostream>

using namespace arma;

LinearRegression::LinearRegression(mat &x, vec &y)
    : x{x}, y{y}, trained{false} {
  assert(x.n_rows == y.n_rows);

  // Create bias column and append at the end of  x
  mat bias = ones<mat>(this->ExampleNumber(), 1);
  this->x.insert_cols(this->x.n_cols, bias);
}

LinearRegression::~LinearRegression() {}

void LinearRegression::AddData(mat &extraX, vec &extraY) {
  assert(extraX.n_rows == extraY.n_rows);
  // Add 1 because x has a bias column
  assert((extraX.n_cols + 1) == this->x.n_cols);

  this->trained = false;
  // Add Bias column to latest added input
  mat bias = ones<mat>(extraX.n_rows, 1);
  mat inputX = extraX;
  inputX.insert_cols(inputX.n_cols, bias);
  this->x.insert_rows(this->x.n_rows, inputX);
  this->y.insert_rows(this->y.n_rows, extraY);
}

void LinearRegression::Train(bool NormEqu, double alpha, unsigned int iters) {
  if (NormEqu) {
    this->NormalEquation();
  } else {
    this->GradientDescent(alpha, iters);
  }
}

void LinearRegression::NormalEquation() {
  mat xtx = (this->x.t() * this->x);
  // Check if xtx is full-rank matrix
  if (rank(xtx) == xtx.n_rows) {
    this->theta = pinv(xtx) * this->x.t() * this->y;
    this->trained = true;
  } else {
    std::cerr << "you have to regularize your data set" << std::endl;
  }
}

uword LinearRegression::ExampleNumber() { return this->x.n_rows; }

double LinearRegression::Predict(vec &x) {
  if (!this->trained) {
    std::cerr << "This model hasn't been trained" << std::endl;
    return 0.0;
  }
  vec bias = vec("1");
  vec input = x;
  input.insert_rows(x.n_rows, bias);
  return (input.t() * this->theta).eval()(0, 0);
}

vec LinearRegression::CostDerivative() {
  vec deriv = (((this->x * this->theta) - this->y).t() * this->x).t();
  return 1 / (float)this->ExampleNumber() * deriv;
}

void LinearRegression::GradientDescent(double alpha, unsigned int iters) {
  if (this->trained != true) {
    // Initialize Theta
    this->theta = ones<vec>(this->x.n_cols);
  }
  for (unsigned int i = 0; i < iters; i++) {
    this->theta = this->theta - (alpha * this->CostDerivative());
  }

  this->trained = true;
}
<commit_msg>Modified if statement of Gradient Descent<commit_after>#include "LinearRegression.h"
#include <armadillo>
#include <assert.h>
#include <iostream>

using namespace arma;

LinearRegression::LinearRegression(mat &x, vec &y)
    : x{x}, y{y}, trained{false} {
  assert(x.n_rows == y.n_rows);

  // Create bias column and append at the end of  x
  mat bias = ones<mat>(this->ExampleNumber(), 1);
  this->x.insert_cols(this->x.n_cols, bias);
}

LinearRegression::~LinearRegression() {}

void LinearRegression::AddData(mat &extraX, vec &extraY) {
  assert(extraX.n_rows == extraY.n_rows);
  // Add 1 because x has a bias column
  assert((extraX.n_cols + 1) == this->x.n_cols);

  this->trained = false;
  // Add Bias column to latest added input
  mat bias = ones<mat>(extraX.n_rows, 1);
  mat inputX = extraX;
  inputX.insert_cols(inputX.n_cols, bias);
  this->x.insert_rows(this->x.n_rows, inputX);
  this->y.insert_rows(this->y.n_rows, extraY);
}

void LinearRegression::Train(bool NormEqu, double alpha, unsigned int iters) {
  if (NormEqu) {
    this->NormalEquation();
  } else {
    this->GradientDescent(alpha, iters);
  }
}

void LinearRegression::NormalEquation() {
  mat xtx = (this->x.t() * this->x);
  // Check if xtx is full-rank matrix
  if (rank(xtx) == xtx.n_rows) {
    this->theta = pinv(xtx) * this->x.t() * this->y;
    this->trained = true;
  } else {
    std::cerr << "you have to regularize your data set" << std::endl;
  }
}

uword LinearRegression::ExampleNumber() { return this->x.n_rows; }

double LinearRegression::Predict(vec &x) {
  if (!this->trained) {
    std::cerr << "This model hasn't been trained" << std::endl;
    return 0.0;
  }
  vec bias = vec("1");
  vec input = x;
  input.insert_rows(x.n_rows, bias);
  return (input.t() * this->theta).eval()(0, 0);
}

vec LinearRegression::CostDerivative() {
  vec deriv = (((this->x * this->theta) - this->y).t() * this->x).t();
  return 1 / (float)this->ExampleNumber() * deriv;
}

void LinearRegression::GradientDescent(double alpha, unsigned int iters) {
  if (this->trained != true || this->theta.n_rows != this->x.n_cols) {
    // Initialize Theta
    this->theta = ones<vec>(this->x.n_cols);
  }
  for (unsigned int i = 0; i < iters; i++) {
    this->theta = this->theta - (alpha * this->CostDerivative());
  }

  this->trained = true;
}
<|endoftext|>


<commit_before>/***************************************************************************
* Copyright (c) Wolf Vollprecht, Johan Mabille and Sylvain Corlay          *
* Copyright (c) QuantStack                                                 *
*                                                                          *
* Distributed under the terms of the BSD 3-Clause License.                 *
*                                                                          *
* The full license is in the file LICENSE, distributed with this software. *
****************************************************************************/

#include "gtest/gtest.h"

#include "xtensor-python/pyarray.hpp"

namespace xt
{
    namespace testing
    {
        class pyarray_traits: public ::testing::Test
        {
        protected:

            using dynamic_type = xt::pyarray<double>;
            using row_major_type = xt::pyarray<double, xt::layout_type::row_major>;
            using column_major_type = xt::pyarray<double, xt::layout_type::column_major>;

            dynamic_type d1 = {{0., 1.}, {0., 10.}, {0., 100.}};
            dynamic_type d2 = {{0., 2.}, {0., 20.}, {0., 200.}};

            row_major_type r1 = {{0., 1.}, {0., 10.}, {0., 100.}};
            row_major_type r2 = {{0., 2.}, {0., 20.}, {0., 200.}};

            column_major_type c1 = {{0., 1.}, {0., 10.}, {0., 100.}};
            column_major_type c2 = {{0., 2.}, {0., 20.}, {0., 200.}};

            template <class T>
            bool test_has_strides(T const&)
            {
                return xt::has_strides<T>::value;
            }

            template <class T>
            xt::layout_type test_result_layout(T const& a1, T const& a2)
            {
                auto tmp1 = pow(sin((a2 - a1) / 2.), 2.);
                auto tmp2 = cos(a1);
                return (tmp1 + tmp2).layout();
            }

            template <class T>
            bool test_linear_assign(T const& a1, T const& a2)
            {
                auto tmp1 = pow(sin((a2 - a1) / 2.), 2.);
                auto tmp2 = cos(a1);
                T res = tmp1 + tmp2;
                return xt::xassign_traits<T, decltype(tmp1 + tmp2)>::linear_assign(res, tmp1 + tmp2, true);
            }

            template <class T>
            bool test_simd_linear_assign(T const& a1, T const& a2)
            {
                auto tmp1 = pow(sin((a2 - a1) / 2.), 2.);
                auto tmp2 = cos(a1);
                return xt::xassign_traits<T, decltype(tmp2)>::simd_linear_assign();
            }

            template <class T>
            bool test_linear_static_layout(T const& a1, T const& a2)
            {
                auto tmp1 = pow(sin((a2 - a1) / 2.), 2.);
                auto tmp2 = cos(a1);
                return xt::detail::linear_static_layout<decltype(tmp1), decltype(tmp2)>();
            }

            template <class T>
            bool test_contiguous_layout(T const& a1, T const& a2)
            {
                auto tmp1 = pow(sin((a2 - a1) / 2.), 2.);
                auto tmp2 = cos(a1);
                return decltype(tmp1)::contiguous_layout && decltype(tmp2)::contiguous_layout;
            }
        };

        TEST_F(pyarray_traits, result_layout)
        {
            EXPECT_TRUE(d1.layout() == layout_type::row_major);
            EXPECT_TRUE(test_result_layout(d1, d2) == layout_type::row_major);

            EXPECT_TRUE(r1.layout() == layout_type::row_major);
            EXPECT_TRUE(test_result_layout(r1, r2) == layout_type::row_major);

            EXPECT_TRUE(c1.layout() == layout_type::column_major);
            EXPECT_TRUE(test_result_layout(c1, c2) == layout_type::column_major);
        }

        TEST_F(pyarray_traits, has_strides)
        {
            EXPECT_TRUE(test_has_strides(d1));
            EXPECT_TRUE(test_has_strides(r1));
            EXPECT_TRUE(test_has_strides(c1));
        }

        TEST_F(pyarray_traits, has_linear_assign)
        {
            EXPECT_TRUE(d2.has_linear_assign(d1.strides()));
            EXPECT_TRUE(r2.has_linear_assign(r1.strides()));
            EXPECT_TRUE(c2.has_linear_assign(c1.strides()));
        }

        TEST_F(pyarray_traits, linear_assign)
        {
            EXPECT_TRUE(test_linear_assign(d1, d2));
            EXPECT_TRUE(test_linear_assign(r1, r2));
            EXPECT_TRUE(test_linear_assign(c1, c2));
        }

        TEST_F(pyarray_traits, simd_linear_assign)
        {
#ifdef XTENSOR_USE_XSIMD
            EXPECT_FALSE(test_simd_linear_assign(d1, d2));
            EXPECT_TRUE(test_simd_linear_assign(r1, r2));
            EXPECT_TRUE(test_simd_linear_assign(c1, c2));
#else
            EXPECT_FALSE(test_simd_linear_assign(d1, d2));
            EXPECT_FALSE(test_simd_linear_assign(r1, r2));
            EXPECT_FALSE(test_simd_linear_assign(c1, c2));
#endif
        }

        TEST_F(pyarray_traits, linear_static_layout)
        {
            EXPECT_FALSE(test_linear_static_layout(d1, d2));
            EXPECT_TRUE(test_linear_static_layout(r1, r2));
            EXPECT_TRUE(test_linear_static_layout(c1, c2));
        }

        TEST_F(pyarray_traits, contiguous_layout)
        {
            EXPECT_FALSE(test_contiguous_layout(d1, d2));
            EXPECT_TRUE(test_contiguous_layout(r1, r2));
            EXPECT_TRUE(test_contiguous_layout(c1, c2));
        }
    }
}
<commit_msg>test both static and dynamic simd linear assign<commit_after>/***************************************************************************
* Copyright (c) Wolf Vollprecht, Johan Mabille and Sylvain Corlay          *
* Copyright (c) QuantStack                                                 *
*                                                                          *
* Distributed under the terms of the BSD 3-Clause License.                 *
*                                                                          *
* The full license is in the file LICENSE, distributed with this software. *
****************************************************************************/

#include "gtest/gtest.h"

#include "xtensor-python/pyarray.hpp"

namespace xt
{
    namespace testing
    {
        class pyarray_traits: public ::testing::Test
        {
        protected:

            using dynamic_type = xt::pyarray<double>;
            using row_major_type = xt::pyarray<double, xt::layout_type::row_major>;
            using column_major_type = xt::pyarray<double, xt::layout_type::column_major>;

            dynamic_type d1 = {{0., 1.}, {0., 10.}, {0., 100.}};
            dynamic_type d2 = {{0., 2.}, {0., 20.}, {0., 200.}};

            row_major_type r1 = {{0., 1.}, {0., 10.}, {0., 100.}};
            row_major_type r2 = {{0., 2.}, {0., 20.}, {0., 200.}};

            column_major_type c1 = {{0., 1.}, {0., 10.}, {0., 100.}};
            column_major_type c2 = {{0., 2.}, {0., 20.}, {0., 200.}};

            template <class T>
            bool test_has_strides(T const&)
            {
                return xt::has_strides<T>::value;
            }

            template <class T>
            xt::layout_type test_result_layout(T const& a1, T const& a2)
            {
                auto tmp1 = pow(sin((a2 - a1) / 2.), 2.);
                auto tmp2 = cos(a1);
                return (tmp1 + tmp2).layout();
            }

            template <class T>
            bool test_linear_assign(T const& a1, T const& a2)
            {
                auto tmp1 = pow(sin((a2 - a1) / 2.), 2.);
                auto tmp2 = cos(a1);
                T res = tmp1 + tmp2;
                return xt::xassign_traits<T, decltype(tmp1 + tmp2)>::linear_assign(res, tmp1 + tmp2, true);
            }

            template <class T>
            bool test_static_simd_linear_assign(T const& a1, T const& a2)
            {
                auto tmp1 = pow(sin((a2 - a1) / 2.), 2.);
                auto tmp2 = cos(a1);
                return xt::xassign_traits<T, decltype(tmp2)>::simd_linear_assign();
            }

            template <class T>
            bool test_dynamic_simd_linear_assign(T const& a1, T const& a2)
            {
                auto tmp1 = pow(sin((a2 - a1) / 2.), 2.);
                auto tmp2 = cos(a1);
                return xt::xassign_traits<T, decltype(tmp2)>::simd_linear_assign(a1, tmp2);
            }

            template <class T>
            bool test_linear_static_layout(T const& a1, T const& a2)
            {
                auto tmp1 = pow(sin((a2 - a1) / 2.), 2.);
                auto tmp2 = cos(a1);
                return xt::detail::linear_static_layout<decltype(tmp1), decltype(tmp2)>();
            }

            template <class T>
            bool test_contiguous_layout(T const& a1, T const& a2)
            {
                auto tmp1 = pow(sin((a2 - a1) / 2.), 2.);
                auto tmp2 = cos(a1);
                return decltype(tmp1)::contiguous_layout && decltype(tmp2)::contiguous_layout;
            }
        };

        TEST_F(pyarray_traits, result_layout)
        {
            EXPECT_TRUE(d1.layout() == layout_type::row_major);
            EXPECT_TRUE(test_result_layout(d1, d2) == layout_type::row_major);

            EXPECT_TRUE(r1.layout() == layout_type::row_major);
            EXPECT_TRUE(test_result_layout(r1, r2) == layout_type::row_major);

            EXPECT_TRUE(c1.layout() == layout_type::column_major);
            EXPECT_TRUE(test_result_layout(c1, c2) == layout_type::column_major);
        }

        TEST_F(pyarray_traits, has_strides)
        {
            EXPECT_TRUE(test_has_strides(d1));
            EXPECT_TRUE(test_has_strides(r1));
            EXPECT_TRUE(test_has_strides(c1));
        }

        TEST_F(pyarray_traits, has_linear_assign)
        {
            EXPECT_TRUE(d2.has_linear_assign(d1.strides()));
            EXPECT_TRUE(r2.has_linear_assign(r1.strides()));
            EXPECT_TRUE(c2.has_linear_assign(c1.strides()));
        }

        TEST_F(pyarray_traits, linear_assign)
        {
            EXPECT_TRUE(test_linear_assign(d1, d2));
            EXPECT_TRUE(test_linear_assign(r1, r2));
            EXPECT_TRUE(test_linear_assign(c1, c2));
        }

        TEST_F(pyarray_traits, static_simd_linear_assign)
        {
#ifdef XTENSOR_USE_XSIMD
            EXPECT_FALSE(test_static_simd_linear_assign(d1, d2));
            EXPECT_TRUE(test_static_simd_linear_assign(r1, r2));
            EXPECT_TRUE(test_static_simd_linear_assign(c1, c2));
#else
            EXPECT_FALSE(test_static_simd_linear_assign(d1, d2));
            EXPECT_FALSE(test_static_simd_linear_assign(r1, r2));
            EXPECT_FALSE(test_static_simd_linear_assign(c1, c2));
#endif
        }

        TEST_F(pyarray_traits, dynamic_simd_linear_assign)
        {
#ifdef XTENSOR_USE_XSIMD
            EXPECT_TRUE(test_dynamic_simd_linear_assign(d1, d2));
            EXPECT_TRUE(test_dynamic_simd_linear_assign(r1, r2));
            EXPECT_TRUE(test_dynamic_simd_linear_assign(c1, c2));
#else
            EXPECT_FALSE(test_dynamic_simd_linear_assign(d1, d2));
            EXPECT_FALSE(test_dynamic_simd_linear_assign(r1, r2));
            EXPECT_FALSE(test_dynamic_simd_linear_assign(c1, c2));
#endif
        }

        TEST_F(pyarray_traits, linear_static_layout)
        {
            EXPECT_FALSE(test_linear_static_layout(d1, d2));
            EXPECT_TRUE(test_linear_static_layout(r1, r2));
            EXPECT_TRUE(test_linear_static_layout(c1, c2));
        }

        TEST_F(pyarray_traits, contiguous_layout)
        {
            EXPECT_FALSE(test_contiguous_layout(d1, d2));
            EXPECT_TRUE(test_contiguous_layout(r1, r2));
            EXPECT_TRUE(test_contiguous_layout(c1, c2));
        }
    }
}
<|endoftext|>


<commit_before>/*
    Kopete , The KDE Instant Messenger
    Copyright (c) 2001-2002 by Duncan Mac-Vicar Prett <duncan@kde.org>

    Viva Chile Mierda!
    Started at Wed Dec 26 03:12:10 CLST 2001, Santiago de Chile

    Kopete    (c) 2002-2005 by the Kopete developers  <kopete-devel@kde.org>

    *************************************************************************
    *                                                                       *
    * This program is free software; you can redistribute it and/or modify  *
    * it under the terms of the GNU General Public License as published by  *
    * the Free Software Foundation; either version 2 of the License, or     *
    * (at your option) any later version.                                   *
    *                                                                       *
    *************************************************************************
*/

#include <kcmdlineargs.h>
#include <kaboutdata.h>
#include "kopeteapplication.h"

#include <dcopclient.h>
#include "kopeteiface.h"
#include "kimifaceimpl.h"

#define KOPETE_VERSION "0.10.90 >= 20050522"

static const char description[] =
	I18N_NOOP( "Kopete, the KDE Instant Messenger" );

static KCmdLineOptions options[] =
{
	{ "noplugins",              I18N_NOOP( "Do not load plugins. This option overrides all other options." ), 0 },
	{ "noconnect",              I18N_NOOP( "Disable auto-connection" ), 0 },
	{ "autoconnect <accounts>", I18N_NOOP( "Auto-connect the specified accounts. Use a comma-separated list\n"
		"to auto-connect multiple accounts." ), 0 },
	{ "disable <plugins>",      I18N_NOOP( "Do not load the specified plugin. Use a comma-separated list\n"
		"to disable multiple plugins." ), 0 },
	{ "load-plugins <plugins>", I18N_NOOP( "Load only the specified plugins. Use a comma-separated list\n"
		"to load multiple plugins. This option has no effect when\n"
		"--noplugins is set and overrides all other plugin related\n"
		"command line options." ), 0 },
//	{ "url <url>",              I18N_NOOP( "Load the given Kopete URL" ), 0 },
//	{ "!+[plugin]",            I18N_NOOP( "Load specified plugins" ), 0 },
	{ "!+[URL]",                 I18N_NOOP("URLs to pass to kopete / emoticon themes to install"), 0},
	KCmdLineLastOption
};

int main( int argc, char *argv[] )
{
	KAboutData aboutData( "kopete", I18N_NOOP("Kopete"),
		KOPETE_VERSION, description, KAboutData::License_GPL,
		I18N_NOOP("(c) 2001-2004, Duncan Mac-Vicar Prett\n(c) 2002-2005, Kopete Development Team"), "kopete-devel@kde.org", "http://kopete.kde.org");

	aboutData.addAuthor ( "Duncan Mac-Vicar Prett", I18N_NOOP("Original author, Developer"), "duncan@kde.org", "http://www.mac-vicar.org/~duncan" );
	aboutData.addAuthor ( "Andre Duffeck", I18N_NOOP("Developer, Yahoo"), "andre@duffeck.de" );
	aboutData.addAuthor ( "Till Gerken", I18N_NOOP("Developer, Jabber plugin maintainer"), "till@tantalo.net");
	aboutData.addAuthor ( "Olivier Goffart", I18N_NOOP("Developer, MSN plugin maintainer"), "ogoffart @ kde.org");
	aboutData.addAuthor ( "Andy Goossens", I18N_NOOP("Developer"), "andygoossens@telenet.be" );
	aboutData.addAuthor ( "Chris Howells", I18N_NOOP("Developer, Connection status plugin author"), "howells@kde.org", "http://chrishowells.co.uk");
	aboutData.addAuthor ( "Grzegorz Jaskiewicz", I18N_NOOP("Developer, Gadu plugin maintainer"), "gj@pointblue.com.pl" );
	aboutData.addAuthor ( "Jason Keirstead", I18N_NOOP("Developer, IRC maintainer"), "jason@keirstead.org", "http://www.keirstead.org");
	aboutData.addAuthor ( "Martijn Klingens", I18N_NOOP("Developer"), "klingens@kde.org" );
	aboutData.addAuthor ( "Chetan Reddy", I18N_NOOP("Developer, Yahoo"), "chetan13@gmail.com" );
	aboutData.addAuthor ( "Matt Rogers", I18N_NOOP("Developer, AIM, ICQ, and Yahoo plugin maintainer"), "mattr@kde.org" );
	aboutData.addAuthor ( "Zack Rusin", I18N_NOOP("Developer, original Gadu plugin author"), "zack@kde.org" );
	aboutData.addAuthor ( "Richard Smith", I18N_NOOP("Developer, UI maintainer"), "kde@metafoo.co.uk" );
	aboutData.addAuthor ( "Will Stephenson", I18N_NOOP("Developer, GroupWise maintainer"), "lists@stevello.free-online.co.uk" );
	aboutData.addAuthor ( "Michaël Larouche", I18N_NOOP("Developer, MSN"), "shock@shockdev.ca.tc", "http://mlarouche.blogspot.com" );

	aboutData.addCredit ( "Luciash d' Being", I18N_NOOP("Kopete's icon author") );
	aboutData.addCredit ( "Steve Cable", I18N_NOOP("Sounds") );
	aboutData.addCredit ( "Justin Karneges", I18N_NOOP("Iris Jabber Backend Library") );
	aboutData.addCredit ( "Tom Linsky", I18N_NOOP("OscarSocket author"), "twl6@po.cwru.edu" );
	aboutData.addCredit ( "Olaf Lueg", I18N_NOOP("Kmerlin MSN code") );

	aboutData.addCredit ( "Nick Betcher", I18N_NOOP("Former developer, project co-founder"), "nbetcher@kde.org");
	aboutData.addCredit ( "Ryan Cumming", I18N_NOOP("Former developer"), "ryan@kde.org" );
	aboutData.addCredit ( "Stefan Gehn", I18N_NOOP("Former developer"), "metz@gehn.net", "http://metz.gehn.net" );
	aboutData.addCredit ( "Andres Krapf", I18N_NOOP("Former developer"), "dae@chez.com" );
	aboutData.addCredit ( "Carsten Pfeiffer", I18N_NOOP("Misc bugfixes and enhancements"), "pfeiffer@kde.org" );
	aboutData.addCredit ( "Richard Stellingwerff", I18N_NOOP("Former developer"), "remenic@linuxfromscratch.org");
	aboutData.addCredit ( "Daniel Stone", I18N_NOOP("Former developer, Jabber plugin author"), "daniel@fooishbar.org", "http://fooishbar.org");
	aboutData.addCredit ( "Chris TenHarmsel", I18N_NOOP("Former developer, Oscar plugin"), "tenharmsel@users.sourceforge.net");
	aboutData.addCredit ( "Hendrik vom Lehn", I18N_NOOP("Former developer"), "hennevl@hennevl.de", "http://www.hennevl.de");
	aboutData.addCredit ( "Gav Wood", I18N_NOOP("Former developer and WinPopup maintainer"), "gav@indigoarchive.net" );

	aboutData.setTranslator( I18N_NOOP("_: NAME OF TRANSLATORS\nYour names"),
		I18N_NOOP("_: EMAIL OF TRANSLATORS\nYour emails") );

	KCmdLineArgs::init( argc, argv, &aboutData );
	KCmdLineArgs::addCmdLineOptions( options ); // Add our own options.
	KUniqueApplication::addCmdLineOptions();

	KopeteApplication kopete;
	new KIMIfaceImpl();
	kapp->dcopClient()->registerAs( "kopete", false );
	kapp->dcopClient()->setDefaultObject( (new KopeteIface())->objId() ); // Has to be called before exec

	kopete.exec();
}
// vim: set noet ts=4 sts=4 sw=4:
<commit_msg>credit updates:<commit_after>/*
    Kopete , The KDE Instant Messenger
    Copyright (c) 2001-2002 by Duncan Mac-Vicar Prett <duncan@kde.org>

    Viva Chile Mierda!
    Started at Wed Dec 26 03:12:10 CLST 2001, Santiago de Chile

    Kopete    (c) 2002-2005 by the Kopete developers  <kopete-devel@kde.org>

    *************************************************************************
    *                                                                       *
    * This program is free software; you can redistribute it and/or modify  *
    * it under the terms of the GNU General Public License as published by  *
    * the Free Software Foundation; either version 2 of the License, or     *
    * (at your option) any later version.                                   *
    *                                                                       *
    *************************************************************************
*/

#include <kcmdlineargs.h>
#include <kaboutdata.h>
#include "kopeteapplication.h"

#include <dcopclient.h>
#include "kopeteiface.h"
#include "kimifaceimpl.h"

#define KOPETE_VERSION "0.10.90 >= 20050522"

static const char description[] =
	I18N_NOOP( "Kopete, the KDE Instant Messenger" );

static KCmdLineOptions options[] =
{
	{ "noplugins",              I18N_NOOP( "Do not load plugins. This option overrides all other options." ), 0 },
	{ "noconnect",              I18N_NOOP( "Disable auto-connection" ), 0 },
	{ "autoconnect <accounts>", I18N_NOOP( "Auto-connect the specified accounts. Use a comma-separated list\n"
		"to auto-connect multiple accounts." ), 0 },
	{ "disable <plugins>",      I18N_NOOP( "Do not load the specified plugin. Use a comma-separated list\n"
		"to disable multiple plugins." ), 0 },
	{ "load-plugins <plugins>", I18N_NOOP( "Load only the specified plugins. Use a comma-separated list\n"
		"to load multiple plugins. This option has no effect when\n"
		"--noplugins is set and overrides all other plugin related\n"
		"command line options." ), 0 },
//	{ "url <url>",              I18N_NOOP( "Load the given Kopete URL" ), 0 },
//	{ "!+[plugin]",            I18N_NOOP( "Load specified plugins" ), 0 },
	{ "!+[URL]",                 I18N_NOOP("URLs to pass to kopete / emoticon themes to install"), 0},
	KCmdLineLastOption
};

int main( int argc, char *argv[] )
{
	KAboutData aboutData( "kopete", I18N_NOOP("Kopete"),
		KOPETE_VERSION, description, KAboutData::License_GPL,
		I18N_NOOP("(c) 2001-2004, Duncan Mac-Vicar Prett\n(c) 2002-2005, Kopete Development Team"), "kopete-devel@kde.org", "http://kopete.kde.org");

	aboutData.addAuthor ( "Duncan Mac-Vicar Prett", I18N_NOOP("Original author, Developer"), "duncan@kde.org", "http://www.mac-vicar.org/~duncan" );
	aboutData.addAuthor ( "Andre Duffeck", I18N_NOOP("Developer, Yahoo plugin maintainer"), "andre@duffeck.de" );
	aboutData.addAuthor ( "Till Gerken", I18N_NOOP("Developer, Jabber plugin maintainer"), "till@tantalo.net");
	aboutData.addAuthor ( "Olivier Goffart", I18N_NOOP("Developer, MSN plugin maintainer"), "ogoffart @ kde.org");
	aboutData.addAuthor ( "Andy Goossens", I18N_NOOP("Developer"), "andygoossens@telenet.be" );
	aboutData.addAuthor ( "Michel Hermier", I18N_NOOP("IRC plugin maintainer"), "michel.hermier@wanadoo.fr" );
	aboutData.addAuthor ( "Chris Howells", I18N_NOOP("Developer, Connection status plugin author"), "howells@kde.org", "http://chrishowells.co.uk");
	aboutData.addAuthor ( "Grzegorz Jaskiewicz", I18N_NOOP("Developer, Gadu plugin maintainer"), "gj@pointblue.com.pl" );
	aboutData.addAuthor ( "Jason Keirstead", I18N_NOOP("Developer"), "jason@keirstead.org", "http://www.keirstead.org");
	aboutData.addAuthor ( "Chetan Reddy", I18N_NOOP("Developer, Yahoo"), "chetan13@gmail.com" );
	aboutData.addAuthor ( "Matt Rogers", I18N_NOOP("Developer, AIM and ICQ plugin maintainer"), "mattr@kde.org" );
	aboutData.addAuthor ( "Richard Smith", I18N_NOOP("Developer, UI maintainer"), "kde@metafoo.co.uk" );
	aboutData.addAuthor ( "Will Stephenson", I18N_NOOP("Developer, GroupWise maintainer"), "lists@stevello.free-online.co.uk" );
	aboutData.addAuthor ( "Michaël Larouche", I18N_NOOP("Developer, MSN"), "shock@shockdev.ca.tc", "http://mlarouche.blogspot.com" );

	aboutData.addCredit ( "Luciash d' Being", I18N_NOOP("Kopete's icon author") );
	aboutData.addCredit ( "Steve Cable", I18N_NOOP("Sounds") );
	aboutData.addCredit ( "Justin Karneges", I18N_NOOP("Iris Jabber Backend Library") );
	aboutData.addCredit ( "Tom Linsky", I18N_NOOP("OscarSocket author"), "twl6@po.cwru.edu" );
	aboutData.addCredit ( "Olaf Lueg", I18N_NOOP("Kmerlin MSN code") );

	aboutData.addCredit ( "Nick Betcher", I18N_NOOP("Former developer, project co-founder"), "nbetcher@kde.org");
	aboutData.addCredit ( "Ryan Cumming", I18N_NOOP("Former developer"), "ryan@kde.org" );
	aboutData.addCredit ( "Stefan Gehn", I18N_NOOP("Former developer"), "metz@gehn.net", "http://metz.gehn.net" );
	aboutData.addCredit ( "Martijn Klingens", I18N_NOOP("Former developer"), "klingens@kde.org" );
	aboutData.addCredit ( "Andres Krapf", I18N_NOOP("Former developer"), "dae@chez.com" );
	aboutData.addCredit ( "Carsten Pfeiffer", I18N_NOOP("Misc bugfixes and enhancements"), "pfeiffer@kde.org" );
	aboutData.addCredit ( "Zack Rusin", I18N_NOOP("Former developer, original Gadu plugin author"), "zack@kde.org" );
	aboutData.addCredit ( "Richard Stellingwerff", I18N_NOOP("Former developer"), "remenic@linuxfromscratch.org");
	aboutData.addCredit ( "Daniel Stone", I18N_NOOP("Former developer, Jabber plugin author"), "daniel@fooishbar.org", "http://fooishbar.org");
	aboutData.addCredit ( "Chris TenHarmsel", I18N_NOOP("Former developer, Oscar plugin"), "tenharmsel@users.sourceforge.net");
	aboutData.addCredit ( "Hendrik vom Lehn", I18N_NOOP("Former developer"), "hennevl@hennevl.de", "http://www.hennevl.de");
	aboutData.addCredit ( "Gav Wood", I18N_NOOP("Former developer and WinPopup maintainer"), "gav@indigoarchive.net" );

	aboutData.setTranslator( I18N_NOOP("_: NAME OF TRANSLATORS\nYour names"),
		I18N_NOOP("_: EMAIL OF TRANSLATORS\nYour emails") );

	KCmdLineArgs::init( argc, argv, &aboutData );
	KCmdLineArgs::addCmdLineOptions( options ); // Add our own options.
	KUniqueApplication::addCmdLineOptions();

	KopeteApplication kopete;
	new KIMIfaceImpl();
	kapp->dcopClient()->registerAs( "kopete", false );
	kapp->dcopClient()->setDefaultObject( (new KopeteIface())->objId() ); // Has to be called before exec

	kopete.exec();
}
// vim: set noet ts=4 sts=4 sw=4:
<|endoftext|>


<commit_before>void Config()
{
  // 7-DEC-2000 09:00
  // Switch on Transition Radiation simulation. 6/12/00 18:00
  // iZDC=1  7/12/00 09:00
  // ThetaRange is (0., 180.). It was (0.28,179.72) 7/12/00 09:00

  new AliGeant3("C++ Interface to Geant3");

  if (!gSystem->Getenv("CONFIG_FILE")) {
    TFile *rootfile = new TFile("galice.root","recreate");
    rootfile->SetCompressionLevel(2);
  }

  TGeant3 *geant3 = (TGeant3*)gMC;
  //
  // Set External decayer
  AliDecayer* decayer = new AliDecayerPythia();
  decayer->SetForceDecay(kAll);
  decayer->Init();
  gMC->SetExternalDecayer(decayer);
  //
  //
  //=======================================================================
  // ******* GEANT STEERING parameters FOR ALICE SIMULATION *******
  geant3->SetTRIG(1); //Number of events to be processed
  geant3->SetSWIT(4,10);
  geant3->SetDEBU(0,0,1);
  //geant3->SetSWIT(2,2);
  geant3->SetDCAY(1);
  geant3->SetPAIR(1);
  geant3->SetCOMP(1);
  geant3->SetPHOT(1);
  geant3->SetPFIS(0);
  geant3->SetDRAY(0);
  geant3->SetANNI(1);
  geant3->SetBREM(1);
  geant3->SetMUNU(1);
  geant3->SetCKOV(1);
  geant3->SetHADR(1); //Select pure GEANH (HADR 1) or GEANH/NUCRIN (HADR 3)
  geant3->SetLOSS(2);
  geant3->SetMULS(1);
  geant3->SetRAYL(1);
  geant3->SetAUTO(1); //Select automatic STMIN etc... calc. (AUTO 1) or manual (AUTO 0)
  geant3->SetABAN(0); //Restore 3.16 behaviour for abandoned tracks
  geant3->SetOPTI(2); //Select optimisation level for GEANT geometry searches (0,1,2)
  geant3->SetERAN(5.e-7);

  Float_t cut    = 1.e-3; // 1MeV cut by default
  Float_t tofmax = 1.e10;
  //             GAM ELEC NHAD CHAD MUON EBREM MUHAB EDEL MUDEL MUPA TOFMAX
  geant3->SetCUTS(cut,cut, cut, cut, cut, cut,  cut,  cut, cut,  cut, tofmax);
  //
  //=======================================================================
  // ************* STEERING parameters FOR ALICE SIMULATION **************
  // --- Specify event type to be tracked through the ALICE setup
  // --- All positions are in cm, angles in degrees, and P and E in GeV
  if (gSystem->Getenv("CONFIG_NPARTICLES")) {
    int nParticles = atoi(gSystem->Getenv("CONFIG_NPARTICLES"));
  } else {
    int nParticles = 50;
  }
  AliGenHIJINGpara *gener = new AliGenHIJINGpara(nParticles);

  gener->SetMomentumRange(0,999);
  gener->SetPhiRange(0,360);
  //  gener->SetThetaRange(0.28,179.72);
  gener->SetThetaRange(0.,180.);
  gener->SetOrigin(0,0,0);        //vertex position
  gener->SetSigma(0,0,0);         //Sigma in (X,Y,Z) (cm) on IP position
  gener->Init();
  //
  // Activate this line if you want the vertex smearing to happen
  // track by track
  //
  //gener->SetVertexSmear(perTrack);

  gAlice->SetField(-999,2);    //Specify maximum magnetic field in Tesla (neg. ==> default field)

  Int_t iABSO=1;
  Int_t iCASTOR=1;
  Int_t iDIPO=1;
  Int_t iFMD=1;
  Int_t iFRAME=1;
  Int_t iHALL=1;
  Int_t iITS=1;
  Int_t iMAG=1;
  Int_t iMUON=1;
  Int_t iPHOS=1;
  Int_t iPIPE=1;
  Int_t iPMD=1;
  Int_t iRICH=1;
  Int_t iSHIL=1;
  Int_t iSTART=1;
  Int_t iTOF=1;
  Int_t iTPC=1;
  Int_t iTRD=1;
  Int_t iZDC=1;

  //=================== Alice BODY parameters =============================
  AliBODY *BODY = new AliBODY("BODY","Alice envelop");

  if(iMAG) {
    //=================== MAG parameters ============================
    // --- Start with Magnet since detector layouts may be depending ---
    // --- on the selected Magnet dimensions ---
    AliMAG *MAG  = new AliMAG("MAG","Magnet");
  }

  if(iABSO) {
    //=================== ABSO parameters ============================
    AliABSO *ABSO  = new AliABSOv0("ABSO","Muon Absorber");
  }

  if(iDIPO) {
    //=================== DIPO parameters ============================

    AliDIPO *DIPO  = new AliDIPOv2("DIPO","Dipole version 2");
  }

  if(iHALL) {
    //=================== HALL parameters ============================

    AliHALL *HALL  = new AliHALL("HALL","Alice Hall");
  }

  if(iFRAME) {
    //=================== FRAME parameters ============================

    AliFRAME *FRAME  = new AliFRAMEv2("FRAME","Space Frame");

  }

  if(iSHIL) {
    //=================== SHIL parameters ============================

    AliSHIL *SHIL  = new AliSHILv0("SHIL","Shielding");
  }

  if(iPIPE) {
    //=================== PIPE parameters ============================

    AliPIPE *PIPE  = new AliPIPEv0("PIPE","Beam Pipe");
  }

  if(iITS) {

//=================== ITS parameters ============================
    //
    // As the innermost detector in ALICE, the Inner Tracking System "impacts" on
    // almost all other detectors. This involves the fact that the ITS geometry
    // still has several options to be followed in parallel in order to determine
    // the best set-up which minimizes the induced background. All the geometries
    // available to date are described in the following. Read carefully the comments
    // and use the default version (the only one uncommented) unless you are making
    // comparisons and you know what you are doing. In this case just uncomment the
    // ITS geometry you want to use and run Aliroot.
    //
    // Detailed geometries:

    //
    //
    //AliITS *ITS  = new AliITSv3("ITS","Old ITS detailed version as of the ALICE TP");
    //
    //AliITS *ITS  = new AliITSv5("ITS","Current ITS detailed version used for the ITS TDR");
    //
    //AliITS *ITS  = new AliITSv5symm("ITS","Updated ITS TDR detailed version with symmetric services");
    //
    AliITS *ITS  = new AliITSv5asymm("ITS","Updates ITS TDR detailed version with asymmetric services");
    //
    //AliITSvPPRasymm *ITS  = new AliITSvPPRasymm("ITS","New ITS PPR detailed version with asymmetric services");
    //ITS->SetMinorVersion(2);
    //ITS->SetReadDet(kFALSE);
    //ITS->SetWriteDet("$ALICE_ROOT/ITS/ITSgeometry_vPPRasymm2.det");
    //ITS->SetThicknessDet1(300.);   // detector thickness on layer 1 must be in the range [100,300]
    //ITS->SetThicknessDet2(300.);   // detector thickness on layer 2 must be in the range [100,300]
    //ITS->SetThicknessChip1(300.);  // chip thickness on layer 1 must be in the range [150,300]
    //ITS->SetThicknessChip2(300.);  // chip thickness on layer 2 must be in the range [150,300]
    //ITS->SetRails(1);              // 1 --> rails in ; 0 --> rails out
    //ITS->SetCoolingFluid(1);       // 1 --> water ; 0 --> freon
    //
    //AliITSvPPRsymm *ITS  = new AliITSvPPRsymm("ITS","New ITS PPR detailed version with symmetric services");
    //ITS->SetMinorVersion(2);

    //ITS->SetReadDet(kFALSE);
    //ITS->SetWriteDet("$ALICE_ROOT/ITS/ITSgeometry_vPPRsymm2.det");
    //ITS->SetThicknessDet1(300.);   // detector thickness on layer 1 must be in the range [100,300]
    //ITS->SetThicknessDet2(300.);   // detector thickness on layer 2 must be in the range [100,300]
    //ITS->SetThicknessChip1(300.);  // chip thickness on layer 1 must be in the range [150,300]
    //ITS->SetThicknessChip2(300.);  // chip thickness on layer 2 must be in the range [150,300]
    //ITS->SetRails(1);              // 1 --> rails in ; 0 --> rails out
    //ITS->SetCoolingFluid(1);       // 1 --> water ; 0 --> freon
    //
    //
    // Coarse geometries (warning: no hits are produced with these coarse geometries and they unuseful
    // for reconstruction !):
    //
    //
    //
    //AliITS *ITS  = new AliITSv1("ITS","Old ITS coarse version as of the ALICE TP");
    //
    //AliITSvPPRcoarseasymm *ITS  = new AliITSvPPRcoarseasymm("ITS","New ITS coarse version with asymmetric services");
    //ITS->SetRails(1);                // 1 --> rails in ; 0 --> rails out
    //ITS->SetSupportMaterial(0);      // 0 --> Copper ; 1 --> Aluminum ; 2 --> Carbon
    //
    //AliITS *ITS  = new AliITSvPPRcoarsesymm("ITS","New ITS coarse version with symmetric services");
    //ITS->SetRails(1);                // 1 --> rails in ; 0 --> rails out
    //ITS->SetSupportMaterial(0);      // 0 --> Copper ; 1 --> Aluminum ; 2 --> Carbon
    //
    //
    //
    // Geant3 <-> EUCLID conversion
    // ============================
    //
    // SetEUCLID is a flag to output (=1) or not to output (=0) both geometry and
    // media to two ASCII files (called by default ITSgeometry.euc and
    // ITSgeometry.tme) in a format understandable to the CAD system EUCLID.
    // The default (=0) means that you dont want to use this facility.
    //
    ITS->SetEUCLID(0);
  }

  if(iTPC) {
    //============================ TPC parameters ================================
    // --- This allows the user to specify sectors for the SLOW (TPC geometry 2)
    // --- Simulator. SecAL (SecAU) <0 means that ALL lower (upper)
    // --- sectors are specified, any value other than that requires at least one
    // --- sector (lower or upper)to be specified!
    // --- Reminder: sectors 1-24 are lower sectors (1-12 -> z>0, 13-24 -> z<0)
    // ---           sectors 25-72 are the upper ones (25-48 -> z>0, 49-72 -> z<0)
    // --- SecLows - number of lower sectors specified (up to 6)
    // --- SecUps - number of upper sectors specified (up to 12)
    // --- Sens - sensitive strips for the Slow Simulator !!!
    // --- This does NOT work if all S or L-sectors are specified, i.e.
    // --- if SecAL or SecAU < 0
    //
    //
    //-----------------------------------------------------------------------------

    //  gROOT->LoadMacro("SetTPCParam.C");
    //  AliTPCParam *param = SetTPCParam();
    AliTPC *TPC  = new AliTPCv2("TPC","Default");
    // All sectors included
    TPC->SetSecAL(-1);
    TPC->SetSecAU(-1);

  }

  if(iTOF) {
    //=================== TOF parameters ============================
    AliTOF *TOF  = new AliTOFv2("TOF","normal TOF");
  }

  if(iRICH) {
    //=================== RICH parameters ===========================
    AliRICH *RICH  = new AliRICHv1("RICH","normal RICH");

  }

  if(iZDC) {
    //=================== ZDC parameters ============================

    AliZDC *ZDC  = new AliZDCv1("ZDC","normal ZDC");
  }

  if(iCASTOR) {
    //=================== CASTOR parameters ============================

    AliCASTOR *CASTOR  = new AliCASTORv1("CASTOR","normal CASTOR");
  }

  if(iTRD) {
    //=================== TRD parameters ============================

    AliTRD *TRD  = new AliTRDv1("TRD","TRD slow simulator");

    // Select the gas mixture (0: 97% Xe + 3% isobutane, 1: 90% Xe + 10% CO2)
    TRD->SetGasMix(1);

    // With hole in front of PHOS
    TRD->SetPHOShole();
    // With hole in front of RICH
    TRD->SetRICHhole();
    // Switch on TR
    AliTRDsim *TRDsim = TRD->CreateTR();
  }

  if(iFMD) {
    //=================== FMD parameters ============================

    AliFMD *FMD  = new AliFMDv0("FMD","normal FMD");
  }

  if(iMUON) {
    //=================== MUON parameters ===========================

    AliMUON *MUON  = new AliMUONv1("MUON","default");
  }

  //=================== PHOS parameters ===========================

  if(iPHOS) {
    AliPHOS *PHOS  = new AliPHOSv1("PHOS","GPS2");
  }

  if(iPMD) {
    //=================== PMD parameters ============================

    AliPMD *PMD  = new AliPMDv1("PMD","normal PMD");
    PMD->SetPAR(1., 1., 0.8, 0.02);
    PMD->SetIN(6., 18., -580., 27., 27.);
    PMD->SetGEO(0.0, 0.2, 4.);
    PMD->SetPadSize(0.8, 1.0, 1.0, 1.5);

  }

  if(iSTART) {
    //=================== START parameters ============================
    AliSTART *START  = new AliSTARTv1("START","START Detector");
  }

}

<commit_msg>Minor changes (R.Barbera)<commit_after>void Config()
{
  // 7-DEC-2000 09:00
  // Switch on Transition Radiation simulation. 6/12/00 18:00
  // iZDC=1  7/12/00 09:00
  // ThetaRange is (0., 180.). It was (0.28,179.72) 7/12/00 09:00

  new AliGeant3("C++ Interface to Geant3");

  if (!gSystem->Getenv("CONFIG_FILE")) {
    TFile *rootfile = new TFile("galice.root","recreate");
    rootfile->SetCompressionLevel(2);
  }

  TGeant3 *geant3 = (TGeant3*)gMC;
  //
  // Set External decayer
  AliDecayer* decayer = new AliDecayerPythia();
  decayer->SetForceDecay(kAll);
  decayer->Init();
  gMC->SetExternalDecayer(decayer);
  //
  //
  //=======================================================================
  // ******* GEANT STEERING parameters FOR ALICE SIMULATION *******
  geant3->SetTRIG(1); //Number of events to be processed
  geant3->SetSWIT(4,10);
  geant3->SetDEBU(0,0,1);
  //geant3->SetSWIT(2,2);
  geant3->SetDCAY(1);
  geant3->SetPAIR(1);
  geant3->SetCOMP(1);
  geant3->SetPHOT(1);
  geant3->SetPFIS(0);
  geant3->SetDRAY(0);
  geant3->SetANNI(1);
  geant3->SetBREM(1);
  geant3->SetMUNU(1);
  geant3->SetCKOV(1);
  geant3->SetHADR(1); //Select pure GEANH (HADR 1) or GEANH/NUCRIN (HADR 3)
  geant3->SetLOSS(2);
  geant3->SetMULS(1);
  geant3->SetRAYL(1);
  geant3->SetAUTO(1); //Select automatic STMIN etc... calc. (AUTO 1) or manual (AUTO 0)
  geant3->SetABAN(0); //Restore 3.16 behaviour for abandoned tracks
  geant3->SetOPTI(2); //Select optimisation level for GEANT geometry searches (0,1,2)
  geant3->SetERAN(5.e-7);

  Float_t cut    = 1.e-3; // 1MeV cut by default
  Float_t tofmax = 1.e10;
  //             GAM ELEC NHAD CHAD MUON EBREM MUHAB EDEL MUDEL MUPA TOFMAX
  geant3->SetCUTS(cut,cut, cut, cut, cut, cut,  cut,  cut, cut,  cut, tofmax);
  //
  //=======================================================================
  // ************* STEERING parameters FOR ALICE SIMULATION **************
  // --- Specify event type to be tracked through the ALICE setup
  // --- All positions are in cm, angles in degrees, and P and E in GeV
  if (gSystem->Getenv("CONFIG_NPARTICLES")) {
    int nParticles = atoi(gSystem->Getenv("CONFIG_NPARTICLES"));
  } else {
    int nParticles = 50;
  }
  AliGenHIJINGpara *gener = new AliGenHIJINGpara(nParticles);

  gener->SetMomentumRange(0,999);
  gener->SetPhiRange(0,360);
  //  gener->SetThetaRange(0.28,179.72);
  gener->SetThetaRange(0.,180.);
  gener->SetOrigin(0,0,0);        //vertex position
  gener->SetSigma(0,0,0);         //Sigma in (X,Y,Z) (cm) on IP position
  gener->Init();
  //
  // Activate this line if you want the vertex smearing to happen
  // track by track
  //
  //gener->SetVertexSmear(perTrack);

  gAlice->SetField(-999,2);    //Specify maximum magnetic field in Tesla (neg. ==> default field)

  Int_t iABSO=1;
  Int_t iCASTOR=1;
  Int_t iDIPO=1;
  Int_t iFMD=1;
  Int_t iFRAME=1;
  Int_t iHALL=1;
  Int_t iITS=1;
  Int_t iMAG=1;
  Int_t iMUON=1;
  Int_t iPHOS=1;
  Int_t iPIPE=1;
  Int_t iPMD=1;
  Int_t iRICH=1;
  Int_t iSHIL=1;
  Int_t iSTART=1;
  Int_t iTOF=1;
  Int_t iTPC=1;
  Int_t iTRD=1;
  Int_t iZDC=1;

  //=================== Alice BODY parameters =============================
  AliBODY *BODY = new AliBODY("BODY","Alice envelop");

  if(iMAG) {
    //=================== MAG parameters ============================
    // --- Start with Magnet since detector layouts may be depending ---
    // --- on the selected Magnet dimensions ---
    AliMAG *MAG  = new AliMAG("MAG","Magnet");
  }

  if(iABSO) {
    //=================== ABSO parameters ============================
    AliABSO *ABSO  = new AliABSOv0("ABSO","Muon Absorber");
  }

  if(iDIPO) {
    //=================== DIPO parameters ============================

    AliDIPO *DIPO  = new AliDIPOv2("DIPO","Dipole version 2");
  }

  if(iHALL) {
    //=================== HALL parameters ============================

    AliHALL *HALL  = new AliHALL("HALL","Alice Hall");
  }

  if(iFRAME) {
    //=================== FRAME parameters ============================

    AliFRAME *FRAME  = new AliFRAMEv2("FRAME","Space Frame");

  }

  if(iSHIL) {
    //=================== SHIL parameters ============================

    AliSHIL *SHIL  = new AliSHILv0("SHIL","Shielding");
  }

  if(iPIPE) {
    //=================== PIPE parameters ============================

    AliPIPE *PIPE  = new AliPIPEv0("PIPE","Beam Pipe");
  }

  if(iITS) {

//=================== ITS parameters ============================
    //
    // As the innermost detector in ALICE, the Inner Tracking System "impacts" on
    // almost all other detectors. This involves the fact that the ITS geometry
    // still has several options to be followed in parallel in order to determine
    // the best set-up which minimizes the induced background. All the geometries
    // available to date are described in the following. Read carefully the comments
    // and use the default version (the only one uncommented) unless you are making
    // comparisons and you know what you are doing. In this case just uncomment the
    // ITS geometry you want to use and run Aliroot.
    //
    // Detailed geometries:
    //
    //
    //
    //AliITS *ITS  = new AliITSv5symm("ITS","Updated ITS TDR detailed version with symmetric services");
    //
    AliITS *ITS  = new AliITSv5asymm("ITS","Updates ITS TDR detailed version with asymmetric services");
    //
    //AliITSvPPRasymm *ITS  = new AliITSvPPRasymm("ITS","New ITS PPR detailed version with asymmetric services");
    //ITS->SetMinorVersion(2);
    //ITS->SetReadDet(kFALSE);
    //ITS->SetWriteDet("$ALICE_ROOT/ITS/ITSgeometry_vPPRasymm2.det");
    //ITS->SetThicknessDet1(300.);   // detector thickness on layer 1 must be in the range [100,300]
    //ITS->SetThicknessDet2(300.);   // detector thickness on layer 2 must be in the range [100,300]
    //ITS->SetThicknessChip1(300.);  // chip thickness on layer 1 must be in the range [150,300]
    //ITS->SetThicknessChip2(300.);  // chip thickness on layer 2 must be in the range [150,300]
    //ITS->SetRails(1);		   // 1 --> rails in ; 0 --> rails out
    //ITS->SetCoolingFluid(1);	   // 1 --> water ; 0 --> freon
    //
    //AliITSvPPRsymm *ITS  = new AliITSvPPRsymm("ITS","New ITS PPR detailed version with symmetric services");
    //ITS->SetMinorVersion(2);
    //ITS->SetReadDet(kFALSE);
    //ITS->SetWriteDet("$ALICE_ROOT/ITS/ITSgeometry_vPPRsymm2.det");
    //ITS->SetThicknessDet1(300.);   // detector thickness on layer 1 must be in the range [100,300]
    //ITS->SetThicknessDet2(300.);   // detector thickness on layer 2 must be in the range [100,300]
    //ITS->SetThicknessChip1(300.);  // chip thickness on layer 1 must be in the range [150,300]
    //ITS->SetThicknessChip2(300.);  // chip thickness on layer 2 must be in the range [150,300]
    //ITS->SetRails(1);              // 1 --> rails in ; 0 --> rails out
    //ITS->SetCoolingFluid(1);       // 1 --> water ; 0 --> freon
    //
    //
    // Coarse geometries (warning: no hits are produced with these coarse geometries and they unuseful
    // for reconstruction !):
    //
    //
    //
    //AliITSvPPRcoarseasymm *ITS  = new AliITSvPPRcoarseasymm("ITS","New ITS coarse version with asymmetric services");
    //ITS->SetRails(1);                // 1 --> rails in ; 0 --> rails out
    //ITS->SetSupportMaterial(0);      // 0 --> Copper ; 1 --> Aluminum ; 2 --> Carbon
    //
    //AliITS *ITS  = new AliITSvPPRcoarsesymm("ITS","New ITS coarse version with symmetric services");
    //ITS->SetRails(1);                // 1 --> rails in ; 0 --> rails out
    //ITS->SetSupportMaterial(0);      // 0 --> Copper ; 1 --> Aluminum ; 2 --> Carbon
    //
    //
    //
    // Geant3 <-> EUCLID conversion
    // ============================
    //
    // SetEUCLID is a flag to output (=1) or not to output (=0) both geometry and
    // media to two ASCII files (called by default ITSgeometry.euc and
    // ITSgeometry.tme) in a format understandable to the CAD system EUCLID.
    // The default (=0) means that you dont want to use this facility.
    //
    ITS->SetEUCLID(0);
  }

  if(iTPC) {
    //============================ TPC parameters ================================
    // --- This allows the user to specify sectors for the SLOW (TPC geometry 2)
    // --- Simulator. SecAL (SecAU) <0 means that ALL lower (upper)
    // --- sectors are specified, any value other than that requires at least one
    // --- sector (lower or upper)to be specified!
    // --- Reminder: sectors 1-24 are lower sectors (1-12 -> z>0, 13-24 -> z<0)
    // ---           sectors 25-72 are the upper ones (25-48 -> z>0, 49-72 -> z<0)
    // --- SecLows - number of lower sectors specified (up to 6)
    // --- SecUps - number of upper sectors specified (up to 12)
    // --- Sens - sensitive strips for the Slow Simulator !!!
    // --- This does NOT work if all S or L-sectors are specified, i.e.
    // --- if SecAL or SecAU < 0
    //
    //
    //-----------------------------------------------------------------------------

    //  gROOT->LoadMacro("SetTPCParam.C");
    //  AliTPCParam *param = SetTPCParam();
    AliTPC *TPC  = new AliTPCv2("TPC","Default");
    // All sectors included
    TPC->SetSecAL(-1);
    TPC->SetSecAU(-1);

  }

  if(iTOF) {
    //=================== TOF parameters ============================
    AliTOF *TOF  = new AliTOFv2("TOF","normal TOF");
  }

  if(iRICH) {
    //=================== RICH parameters ===========================
    AliRICH *RICH  = new AliRICHv1("RICH","normal RICH");

  }

  if(iZDC) {
    //=================== ZDC parameters ============================

    AliZDC *ZDC  = new AliZDCv1("ZDC","normal ZDC");
  }

  if(iCASTOR) {
    //=================== CASTOR parameters ============================

    AliCASTOR *CASTOR  = new AliCASTORv1("CASTOR","normal CASTOR");
  }

  if(iTRD) {
    //=================== TRD parameters ============================

    AliTRD *TRD  = new AliTRDv1("TRD","TRD slow simulator");

    // Select the gas mixture (0: 97% Xe + 3% isobutane, 1: 90% Xe + 10% CO2)
    TRD->SetGasMix(1);

    // With hole in front of PHOS
    TRD->SetPHOShole();
    // With hole in front of RICH
    TRD->SetRICHhole();
    // Switch on TR
    AliTRDsim *TRDsim = TRD->CreateTR();
  }

  if(iFMD) {
    //=================== FMD parameters ============================

    AliFMD *FMD  = new AliFMDv0("FMD","normal FMD");
  }

  if(iMUON) {
    //=================== MUON parameters ===========================

    AliMUON *MUON  = new AliMUONv1("MUON","default");
  }

  //=================== PHOS parameters ===========================

  if(iPHOS) {
    AliPHOS *PHOS  = new AliPHOSv1("PHOS","GPS2");
  }

  if(iPMD) {
    //=================== PMD parameters ============================

    AliPMD *PMD  = new AliPMDv1("PMD","normal PMD");
    PMD->SetPAR(1., 1., 0.8, 0.02);
    PMD->SetIN(6., 18., -580., 27., 27.);
    PMD->SetGEO(0.0, 0.2, 4.);
    PMD->SetPadSize(0.8, 1.0, 1.0, 1.5);

  }

  if(iSTART) {
    //=================== START parameters ============================
    AliSTART *START  = new AliSTARTv1("START","START Detector");
  }

}

<|endoftext|>