예제 #1
0
파일: tdmTesting.cpp 프로젝트: avitase/rabi
void testTDM(void) {
  std::default_random_engine generator;
  std::uniform_real_distribution<double> distribution(-1000., 1000.);
  auto rnd = std::bind(distribution, generator);

  std::size_t N = 10;

  vec a(N, 0.);
  vec a2(N, 0.);
  vec b(N, 0.);
  vec b2(N, 0.);
  vec c(N-1, 0);
  vec c2(N-1, 0);

  b[0] = rnd();
  c[0] = rnd();
  for (std::size_t i=1; i<N-1; i++) {
    a[i] = rnd();
    a2[i] = rnd();
    b[i] = rnd();
    b2[i] = rnd();
    c[i] = rnd();
    c2[i] = rnd();
  }
  a[N-1] = rnd();
  b[N-1] = rnd();
  TDM tdm(a, b, c);
  const TDM tdm2(a2, b2, c2);
  tdm.add(tdm2);
  vtype s = rnd();
  tdm.scale(s);

  auto a3 = tdm.get(TDM::Diagonal::A);
  auto a4 = tdm.get(TDM::Diagonal::A, true);
  auto b3 = tdm.get(TDM::Diagonal::B);
  auto b4 = tdm.get(TDM::Diagonal::B, true);
  auto c3 = tdm.get(TDM::Diagonal::C);
  auto c4 = tdm.get(TDM::Diagonal::C, true);

  a4.insert(a4.begin(), 0.);

  assert(a3.size() == a4.size());
  assert(a4.size() == b3.size());
  assert(b3.size() == b4.size());
  assert(b4.size() == c3.size()+1);
  assert(c3.size() == c4.size());
  assert(c4.size()+1 == N);

  for (size_t i=0; i<N; i++) {
    assert(std::abs(a3[i] - a4[i]) < 1e-10);
    assert(std::abs(b3[i] - b4[i]) < 1e-10);
    assert(std::abs(c3[i] - c4[i]) < 1e-10);

    assert(std::abs(a3[i] - s*(a[i]+a2[i])) < 1e-10);
    assert(std::abs(b3[i] - s*(b[i]+b2[i])) < 1e-10);
    assert(std::abs(c3[i] - s*(c[i]+c2[i])) < 1e-10);
  }

  vec x(N, 0.);
  for (size_t i=0; i<N; i++) {
    x[i] = rnd();
  }

  const TDM tdm3(tdm);
  auto inverted = tdm3.invert(x);
  auto y = tdm.transform(inverted);

  for (size_t i=0; i<N; i++) {
    assert(std::abs(x[i] - y[i]) < 1e-10);
  }
}
예제 #2
0
// Collision detection for rotated rectangles
k3d::vec2 collide(k3d::vec2 pos1, const k3d::vec2 & hw1, const k3d::vec2 & v1,
                  const k3d::vec2 & pos2, const k3d::vec2 & hw2, const k3d::vec2 & v2, bool & collided)
{
    k3d::vec2 vn1(-v1.y, v1.x);
    k3d::vec2 a1((pos1 + (hw1.x*v1)) - (hw1.y*vn1));
    k3d::vec2 b1((pos1 + (hw1.x*v1)) + (hw1.y*vn1));
    k3d::vec2 c1((pos1 - (hw1.x*v1)) + (hw1.y*vn1));
    k3d::vec2 d1((pos1 - (hw1.x*v1)) - (hw1.y*vn1));

    k3d::vec2 vn2(-v2.y, v2.x);
    k3d::vec2 a2((pos2 + (hw2.x*v2)) - (hw2.y*vn2));
    k3d::vec2 b2((pos2 + (hw2.x*v2)) + (hw2.y*vn2));
    k3d::vec2 c2((pos2 - (hw2.x*v2)) + (hw2.y*vn2));
    k3d::vec2 d2((pos2 - (hw2.x*v2)) - (hw2.y*vn2));

    collided = true;

    if (intersect(a1, b1, a2, b2)) {
        // TODO check if it is enough to go back that distance for the 1st 2 cases (corners) here
        if (intersect(a1, b1, b2, c2)) { //corner
            return pos1 + dist_point_to_line(b2, a1, b1)*((v2 + vn2).normalize());
        }
        if (intersect(a1, b1, a2, d2)) { //corner
            return pos1 + dist_point_to_line(a2, a1, b1)*((v2 - vn2).normalize());
        }
        if (intersect(b1, c1, a2, b2)) {
            return pos1 + dist_point_to_line(b1, a2, b2)*v2;
        }
        if (intersect(a1, d1, a2, b2)) {
            return pos1 + dist_point_to_line(a1, a2, b2)*v2;
        }
        if (intersect(b1, c1, a2, d2)) {
            //return pos1 + a2 - b1; // MAYBE THIS IS BETTER ?
            // FIXME max is actually incorrect here, it should be a weighted sum based on where a2b2 intersects a1b1
            return pos1 - max(dist_point_to_line(a1, a2, d2), dist_point_to_line(b1, a2, d2))*vn2;
        }
        if (intersect(a1, d1, b2, c2)) {
            // FIXME max is actually incorrect here, it should be a weighted sum based on where a2b2 intersects a1b1
            return pos1 + max(dist_point_to_line(a1, b2, c2), dist_point_to_line(b1, b2, c2))*vn2;
        }
    }

    if (intersect(a1, b1, b2, c2)) {
        // a1,b1 and a2,b2 already covered
        // TODO check if it is enough to go back that distance for the 1st case here (corner)
        if (intersect(a1, b1, c2, d2)) { //corner
            return pos1 + dist_point_to_line(c2, a1, b1)*((vn2-v2).normalize());
        }
        if (intersect(b1, c1, b2, c2)) {
            return pos1 + dist_point_to_line(b1, b2, c2)*vn2;
        }
        if (intersect(a1, d1, b2, c2)) {
            return pos1 + dist_point_to_line(a1, b2, c2)*vn2;
        }
        if (intersect(b1, c1, a2, b2)) {
            // FIXME max is actually incorrect here, it should be a weighted sum based on where b2c2 intersects a1b1
            return pos1 + max(dist_point_to_line(b1, a2, b2), dist_point_to_line(a1, a2, b2))*v2;
        }
        if (intersect(a1, d1, c2, d2)) {
            // FIXME max is actually incorrect here, it should be a weighted sum based on where b2c2 intersects a1b1
            return pos1 - max(dist_point_to_line(b1, c2, d2), dist_point_to_line(a1, c2, d2))*v2;
        }
    }

    if (intersect(a1, b1, c2, d2)) {
        // a1,b1 and b2,c2 already covered
        // TODO check if it is enough to go back that distance for the 1st case here (corner)
        if (intersect(a1, b1, a2, d2)) {
            return pos1 + dist_point_to_line(d2, a1, b1)*((-1.0*v2)-vn2);
        }
        if (intersect(b1, c1, c2, d2)) {
            return pos1 - dist_point_to_line(b1, c2, d2)*v2;
        }
        if (intersect(a1, d1, c2, d2)) {
            return pos1 - dist_point_to_line(a1, c2, d2)*v2;
        }
        if (intersect(b1, c1, b2, c2)) {
            // FIXME see above fixme's
            return pos1 + max(dist_point_to_line(b1, b2, c2), dist_point_to_line(a1, b2, c2))*vn2;
        }
        if (intersect(a1, d1, a2, d2)) {
            // FIXME see above fixme's
            return pos1 - max(dist_point_to_line(a1, d2, a2), dist_point_to_line(b1, d2, a2))*vn2;
        }
    }

    if (intersect(a1, b1, d2, a2)) {
        // a1,b1 and c2,d2 already covered and a1,b1 and a2,b2 also already covered
        if (intersect(b1, c1, d2, a2)) {
            return pos1 - dist_point_to_line(b1, d2, a2)*vn2;
        }
        if (intersect(a1, d1, d2, a2)) {
            return pos1 - dist_point_to_line(a1, d2, a2)*vn2;
        }
        if (intersect(b1, c1, c2, d2)) {
            // FIXME see above fixme's
            return pos1 - max(dist_point_to_line(b1, c2, d2), dist_point_to_line(a1, c2, d2))*v2;
        }
        if (intersect(a1, d1, a2, b2)) {
            // FIXME see above fixme's
            return pos1 + max(dist_point_to_line(a1, a2, b2), dist_point_to_line(b1, a2, b2))*v2;
        }
    }

    if (intersect(b1, c1, a2, b2)) {
        return pos1 + dist_point_to_line(b1, a2, b2)*v2;
    }
    if (intersect(b1, c1, b2, c2)) {
        return pos1 + dist_point_to_line(b1, b2, c2)*vn2;
    }
    if (intersect(b1, c1, c2, d2)) {
        return pos1 - dist_point_to_line(b1, c2, d2)*v2;
    }
    if (intersect(b1, c1, d2, a2)) {
        return pos1 - dist_point_to_line(b1, d2, a2)*vn2;
    }

    if (intersect(a1, d1, a2, b2)) {
        return pos1 + dist_point_to_line(a1, a2, b2)*v2;
    }
    if (intersect(a1, d1, b2, c2)) {
        return pos1 + dist_point_to_line(a1, b2, c2)*vn2;
    }
    if (intersect(a1, d1, c2, d2)) {
        return pos1 - dist_point_to_line(a1, c2, d2)*v2;
    }
    if (intersect(a1, d1, d2, a2)) {
        return pos1 - dist_point_to_line(a1, d2, a2)*vn2;
    }

    collided = false;
    return pos1;
}
int main ()	{

	textmode (ATC_TEXT_MODE);
	clrscr();

	Position::MaxX = 30;
	Position::MaxY = 30;



	char pid;

	Position::MaxX = 30;
	Position::MaxY = 30;

	RadarScreen *r;
	Landmarks l;

	Traffic t;
	Plane *p1;
	Gate g (Position  (0,  10), 1, D90);
	Gate g1 (Position (0,  0),  2, D45);
	Gate g2 (Position (10, 0),  3, D0);
	Gate g3 (Position (MAX_X, MAX_Y), 4, D225);
//	Gate g4 (Position (10, 0), 4, D0);
	Airport a1 (Position (5, 5), 1, Heading (D90));
	Airport a2 (Position (10, 12), 2, Heading (D45));
	Beacon b1 (Position (7,13), 1);
	Beacon b2 (Position (1,1), 2);
	FlightPath fp (Position (MIN_FIELD_X, MIN_FIELD_Y),
		Position (MAX_FIELD_X, MAX_FIELD_Y));

	FlightPath fp1 (Position (MIN_FIELD_X, MAX_FIELD_Y),
		Position (MAX_FIELD_X, MIN_FIELD_Y));

	FlightPath fp2 (Position (10, 1), Position (10, MAX_FIELD_Y));

	int i;

	l.AddAirport (&a1);

	l.AddAirport (&a2);
	l.AddBeacon (&b1);
	l.AddBeacon (&b2);
	l.AddGate (&g);
	l.AddGate (&g1);
	l.AddGate (&g2);
	l.AddGate (&g3);
//	l.AddGate (&g4);
	l.AddFlightPath (&fp);
	l.AddFlightPath (&fp1);
	l.AddFlightPath (&fp2);

	r = new RadarScreen (&l);

	Boolean Crashed = False;

	r->Refresh();

	pid = t.NewId();

	p1 = new Plane (pid, g.NewPlaneCoords(), Prop, &g1);

	t.NewAirborne (p1);

	p1 = new Plane (t.NewId(), g1.NewPlaneCoords(), Jet, &g);

	t.NewAirborne (p1);


	p1 = new Plane (t.NewId(), g2.NewPlaneCoords(), Jet, &g);

	t.NewAirborne (p1);

	r->DisplayPlanes (&t);

	for (i = 0; i < 34; i++) {
		delay (500);


		if (i == 17)	{
			t.SearchAirborne ('a');
			t.FoundAirborne() -> AlterTargHeading (D270, AntiClockwise);

			t.SearchAirborne ('b');
			t.FoundAirborne() -> MakeCircle (AntiClockwise);
		}
		r->UnDisplayPlanes (&t);

		if (i % 2 == 0)	{
			t.StepJets();
		} else {
			t.StepAll();
		}

		r->DisplayPlanes (&t);

		if (!Crashed && t.Crashed ())	{
				cout << '\a';
			Crashed = True;
		}

	}

	textmode (C80);
	_setcursortype (_NORMALCURSOR);
	clrscr();

	return 0;
}
예제 #4
0
FCOLLADA_EXPORT void TrickLinker2()
{
	{
		// Exercise ALL the functions of the string builders in order to force their templatizations.
		fm::string s = "1";
		fstring fs = FC("2");
		FUSStringBuilder b1, b2(s), b3(s.c_str()), b4('c', 3), b5(333);
		FUStringBuilder d1, d2(fs), d3(fs.c_str()), d4('c', 4), d5(333);

		b1.clear(); d1.clear(); b1.length(); d1.length();
		b1.append(s); d1.append(fs);
		b1.append('c'); d1.append((fchar) 'c');
		b1.append(b2); d1.append(d2);
		b1.append((int)1); d1.append((int)1);
		b1.append(s.c_str(), 1); d1.append(fs.c_str(), 1);
		b3.append((uint32) 8); d3.append((uint32) 8);
		b4.append((uint64) 8); d4.append((uint64) 8);
		b4.append((int32) -2); d4.append((int32) -2);
		b5.append(1.0f); d5.append(-1.0f);
		b5.append(1.0); d5.append(-1.0);
		b5.append(FMVector2::Zero); d5.append(FMVector2::Zero);
		b5.append(FMVector3::Zero); d5.append(FMVector3::Zero);
		b5.append(FMVector4::Zero); d5.append(FMVector4::Zero);
		b5.back(); d5.back();
		b1.appendLine("Test"); d1.appendLine(FC("Test"));
		b1.appendHex((uint8) 4); d1.appendHex((uint8) 4);
		b1.remove(0); d1.remove(0);
		b2.remove(0, 2); d2.remove(0, 2);
		b3.ToCharPtr(); d3.ToCharPtr();
		b4.index('c'); d4.index('c');
		b4.rindex('c'); d4.rindex('c');
	}

	{
		// Similarly for fm::stringT.
		fm::string a, b(a), c("a"), d("ab", 1), e(3, 'C');
		fstring r, s(r), t(FC("S")), u(FC("SSS"), 1), v(3, 'S');

		size_t x = a.length(), y = r.length();
		a = c.substr(x, y); r = u.substr(x, y);
		a.append("TEST"); r.append(FC("TEST"));
		a.append(d); r.append(v);
		e = a.c_str(); v = u.c_str();
		x = a.find('C', y); y = v.find('S', x);
		x = a.find(d, y); y = u.find(r, x);
		x = a.find("X", y); y = v.find(FC("A"), x);
		x = a.rfind('C', y); y = v.rfind('S', x);
		x = a.rfind(d, y); y = u.rfind(r, x);
		x = a.rfind("X", y); y = v.rfind(FC("A"), x);
		x = a.find_first_of("XSA", y); y = r.find_first_of(FC("DNA"), x);
		x = a.find_last_of("XSA", y); y = r.find_last_of(FC("DNA"), x);
		a.insert(x, "XX"); r.insert(y, FC("XX"));
		a.insert(y, c); r.insert(x, v);
		a.erase(0, fm::string::npos); t.erase(1, fstring::npos);
		a.append('c'); v.append('w');
	}

	extern void TrickLinkerFUUniqueStringMap();
	TrickLinkerFUUniqueStringMap();
	extern void TrickLinkerFUStringConversion();
	TrickLinkerFUStringConversion();
}
Matrix<double> BspCurvBasisFuncSet::CreateMatrixIntegral(int lev, double x1, double x2) const
{
	

	KnotSet kset = KnotSet(*kts,ord,num).CreateKnotSetDeriv(lev);
	
	Matrix<double> mat(kset.GetNum()-(ord-lev),kset.GetNum()-(ord-lev));
	
	BspCurvBasisFuncSet basis(kset.GetKnots(),ord-lev,kset.GetNum());

	// find the first basis function for which the last distinct
	// knot is greater than x1

	int ind1=-1;
	do {
		ind1++;
	} while ((*(basis.b))[ind1].GetKnots()[ord-lev] <= x1);


	// find the last basis function for which the first distinct
	// knot is less than x2

	int ind2=-1;
	do {
		ind2++;
	} while (ind2 < kset.GetNum()-ord+lev && (*(basis.b))[ind2].GetKnots()[0] < x2);


	Matrix<double> mat1(kset.GetNum()-ord+lev,kset.GetNum()-ord+lev,0.0);

	for (int i=ind1; i<=ind2-1; i++)
		for (int j=ind1; j<=i; j++) {
		
			
			// create the two std::sets representing the two knot std::sets
			Vector<double> temp1((*(basis.b))[i].GetKnots());
			Vector<double> temp2((*(basis.b))[j].GetKnots());
			std::set<double> s1(temp1.begin(),temp1.end());
			std::set<double> s2(temp2.begin(),temp2.end());

			if (*(--s2.end()) > *(s1.begin())) {
				// form the intersection
				std::set<double> s3;
				std::set_intersection(s1.begin(),s1.end(),s2.begin(),s2.end(),std::inserter(s3,s3.begin()));
			
				// if there is an intersection
				if (s3.size() > 1) {
					Vector<double> v(s3.size());
					std::set<double>::iterator s = s3.begin();

					// copy the elements into a vector
					for (unsigned int k=0; k<s3.size(); k++) v[k] = *s++;
				
					// create the compbezcurvs
					Vector<BezCurv<double> > vec1(s3.size()-1);
					Vector<BezCurv<double> > vec2(s3.size()-1);

					BspCurv<double> b1((*(basis.b))[i].GetBspCurv()), b2((*(basis.b))[j].GetBspCurv());
				
					// find the segments of intersection
					for (unsigned int k=0; k<s3.size()-1; k++) {
						int segb1 = b1.GetKnotSet().Find_segment(v[k]);
						int segb2 = b2.GetKnotSet().Find_segment(v[k]);
						
						vec1[k] = b1.GetSegment(segb1);
						vec2[k] = b2.GetSegment(segb2);
					}
				
					CompBezCurv<double> cb1(vec1,s3.size()-1,v);
					CompBezCurv<double> cb2(vec2,s3.size()-1,v);
					CompBezCurv<double> prod = cb1.Product(cb2);
				
					mat1[i][j] = prod.ConvertBspCurv().Integrate(x1,x2);
				}
			}
		}
	
	for (int i=ind1; i<=ind2-2; i++)
		for (int j=i+1; j<=ind2-1; j++) mat1[i][j] = mat1[j][i];
	
	return mat1;
}
예제 #6
0
void BasicBundleProvider::mergeBundlesForKit(ProjectExplorer::Kit *kit
        , QmlJS::QmlLanguageBundles &bundles
        , const QHash<QString,QString> &replacements)
{
    typedef QmlJS::Document Doc;
    QHash<QString,QString> myReplacements = replacements;

    bundles.mergeBundleForLanguage(Doc::QmlQbsLanguage, defaultQbsBundle());
    bundles.mergeBundleForLanguage(Doc::QmlTypeInfoLanguage, defaultQmltypesBundle());
    bundles.mergeBundleForLanguage(Doc::QmlProjectLanguage, defaultQmlprojectBundle());

    QtSupport::BaseQtVersion *qtVersion = QtSupport::QtKitInformation::qtVersion(kit);
    if (!qtVersion) {
        QmlBundle b1(defaultQt4QtQuick1Bundle());
        bundles.mergeBundleForLanguage(Doc::QmlLanguage, b1);
        bundles.mergeBundleForLanguage(Doc::QmlQtQuick1Language, b1);
        QmlBundle b11(defaultQt5QtQuick1Bundle());
        bundles.mergeBundleForLanguage(Doc::QmlLanguage, b11);
        bundles.mergeBundleForLanguage(Doc::QmlQtQuick1Language, b11);
        QmlBundle b2(defaultQt5QtQuick2Bundle());
        bundles.mergeBundleForLanguage(Doc::QmlLanguage, b2);
        bundles.mergeBundleForLanguage(Doc::QmlQtQuick2Language, b2);
        return;
    }
    QString qtImportsPath = qtVersion->qmakeProperty("QT_INSTALL_IMPORTS");
    QString qtQmlPath = qtVersion->qmakeProperty("QT_INSTALL_QML");

    Core::FeatureSet features = qtVersion->availableFeatures();
    if (features.contains(Core::Feature(QtSupport::Constants::FEATURE_QT_QUICK))
            || features.contains(Core::Feature(QtSupport::Constants::FEATURE_QT_QUICK_1))
            || features.contains(Core::Feature(QtSupport::Constants::FEATURE_QT_QUICK_1_1))) {
        myReplacements.insert(QLatin1String("$(CURRENT_DIRECTORY)"), qtImportsPath);
        QDir qtQuick1Bundles(qtImportsPath);
        qtQuick1Bundles.setNameFilters(QStringList(QLatin1String("*-bundle.json")));
        QmlBundle qtQuick1Bundle;
        QFileInfoList list = qtQuick1Bundles.entryInfoList();
        for (int i = 0; i < list.size(); ++i) {
            QmlBundle bAtt;
            QStringList errors;
            if (!bAtt.readFrom(list.value(i).filePath(), &errors))
                qWarning() << "BasicBundleProvider: ERROR reading " << list[i].filePath() << " : "
                           << errors;
            qtQuick1Bundle.merge(bAtt);
        }
        if (!qtQuick1Bundle.supportedImports().contains(QLatin1String("QtQuick 1."),
                QmlJS::PersistentTrie::Partial)) {
            if (qtVersion->qtVersion().majorVersion == 4)
                qtQuick1Bundle.merge(defaultQt4QtQuick1Bundle());
            else if (qtVersion->qtVersion().majorVersion > 4)
                qtQuick1Bundle.merge(defaultQt5QtQuick1Bundle());
        }
        qtQuick1Bundle.replaceVars(myReplacements);
        bundles.mergeBundleForLanguage(Doc::QmlLanguage, qtQuick1Bundle);
        bundles.mergeBundleForLanguage(Doc::QmlQtQuick1Language, qtQuick1Bundle);
    }
    if (features.contains(Core::Feature(QtSupport::Constants::FEATURE_QT_QUICK_2))) {
        myReplacements.insert(QLatin1String("$(CURRENT_DIRECTORY)"), qtQmlPath);
        QDir qtQuick2Bundles(qtQmlPath);
        qtQuick2Bundles.setNameFilters(QStringList(QLatin1String("*-bundle.json")));
        QmlBundle qtQuick2Bundle;
        QFileInfoList list = qtQuick2Bundles.entryInfoList();
        for (int i = 0; i < list.size(); ++i) {
            QmlBundle bAtt;
            QStringList errors;
            if (!bAtt.readFrom(list.value(i).filePath(), &errors))
                qWarning() << "BasicBundleProvider: ERROR reading " << list[i].filePath() << " : "
                           << errors;
            qtQuick2Bundle.merge(bAtt);
        }
        if (!qtQuick2Bundle.supportedImports().contains(QLatin1String("QtQuick 2."),
                QmlJS::PersistentTrie::Partial)) {
            qtQuick2Bundle.merge(defaultQt5QtQuick2Bundle());
        }
        qtQuick2Bundle.replaceVars(myReplacements);
        bundles.mergeBundleForLanguage(Doc::QmlLanguage, qtQuick2Bundle);
        bundles.mergeBundleForLanguage(Doc::QmlQtQuick2Language, qtQuick2Bundle);
    }
}
예제 #7
0
void test_extract() {
    int dont_care;
    tbb::flow::graph g;
    tbb::flow::broadcast_node<int> b0(g);
    tbb::flow::broadcast_node<int> b1(g);
    tbb::flow::broadcast_node<int> b2(g);
    tbb::flow::broadcast_node<int> b3(g);
    tbb::flow::broadcast_node<int> b4(g);
    tbb::flow::broadcast_node<int> b5(g);
    tbb::flow::queue_node<int> q0(g);
    tbb::flow::make_edge(b0,b1);
    tbb::flow::make_edge(b0,b2);
    tbb::flow::make_edge(b1,b3);
    tbb::flow::make_edge(b1,b4);
    tbb::flow::make_edge(b2,b4);
    tbb::flow::make_edge(b2,b5);
    tbb::flow::make_edge(b3,q0);
    tbb::flow::make_edge(b4,q0);
    tbb::flow::make_edge(b5,q0);

    /*          b3       */
    /*         /  \      */
    /*        b1   \     */
    /*       / \    \    */
    /*     b0   b4---q0  */
    /*       \ /    /    */
    /*        b2   /     */
    /*         \  /      */
    /*          b5       */

    g.wait_for_all();
    b0.try_put(1);
    g.wait_for_all();
    for( int i = 0; i < 4; ++i ) {
        int j;
        ASSERT(q0.try_get(j) && j == 1, "missing or incorrect message");
    }
    ASSERT(!q0.try_get(dont_care), "extra message in queue");
    ASSERT(b0.predecessor_count() == 0 && b0.successor_count() == 2, "improper count for b0");
    ASSERT(b1.predecessor_count() == 1 && b1.successor_count() == 2, "improper count for b1");
    ASSERT(b2.predecessor_count() == 1 && b2.successor_count() == 2, "improper count for b2");
    ASSERT(b3.predecessor_count() == 1 && b3.successor_count() == 1, "improper count for b3");
    ASSERT(b4.predecessor_count() == 2 && b4.successor_count() == 1, "improper count before extract of b4");
    ASSERT(b5.predecessor_count() == 1 && b5.successor_count() == 1, "improper count for b5");
    b4.extract();  // remove from tree of nodes.
    ASSERT(b0.predecessor_count() == 0 && b0.successor_count() == 2, "improper count for b0 after");
    ASSERT(b1.predecessor_count() == 1 && b1.successor_count() == 1, "improper succ count for b1 after");
    ASSERT(b2.predecessor_count() == 1 && b2.successor_count() == 1, "improper succ count for b2 after");
    ASSERT(b3.predecessor_count() == 1 && b3.successor_count() == 1, "improper succ count for b3 after");
    ASSERT(b4.predecessor_count() == 0 && b4.successor_count() == 0, "improper succ count after extract");
    ASSERT(b5.predecessor_count() == 1 && b5.successor_count() == 1, "improper succ count for b5 after");

    /*          b3       */
    /*         /  \      */
    /*        b1   \     */
    /*       /      \    */
    /*     b0        q0  */
    /*       \      /    */
    /*        b2   /     */
    /*         \  /      */
    /*          b5       */

    b0.try_put(1);
    g.wait_for_all();
    for( int i = 0; i < 2; ++i ) {
        int j;
        ASSERT(q0.try_get(j) && j == 1, "missing or incorrect message");
    }
    ASSERT(!q0.try_get(dont_care), "extra message in queue");
    tbb::flow::make_edge(b0,b4);
    tbb::flow::make_edge(b4,q0);
    g.wait_for_all();
    ASSERT(b0.predecessor_count() == 0 && b0.successor_count() == 3, "improper count for b0 after");
    ASSERT(b1.predecessor_count() == 1 && b1.successor_count() == 1, "improper succ count for b1 after");
    ASSERT(b2.predecessor_count() == 1 && b2.successor_count() == 1, "improper succ count for b2 after");
    ASSERT(b3.predecessor_count() == 1 && b3.successor_count() == 1, "improper succ count for b3 after");
    ASSERT(b4.predecessor_count() == 1 && b4.successor_count() == 1, "improper succ count after extract");
    ASSERT(b5.predecessor_count() == 1 && b5.successor_count() == 1, "improper succ count for b5 after");

    /*          b3       */
    /*         /  \      */
    /*        b1   \     */
    /*       /      \    */
    /*     b0---b4---q0  */
    /*       \      /    */
    /*        b2   /     */
    /*         \  /      */
    /*          b5       */

    b0.try_put(1);
    g.wait_for_all();
    for( int i = 0; i < 3; ++i ) {
        int j;
        ASSERT(q0.try_get(j) && j == 1, "missing or incorrect message");
    }
    ASSERT(!q0.try_get(dont_care), "extra message in queue");
}
예제 #8
0
DrawZone::DrawZone(QWidget *parent,KImageMapEditor* _imageMapEditor)
	: QScrollView(parent)
{
	imageMapEditor=_imageMapEditor;
//	setPicture(QImage());
	currentAction=None;
	currentArea=0L;
	oldArea=0L;
	_zoom=1;
  if (imageMapEditor->isReadWrite()) {
	    viewport()->setMouseTracking(true);
    	viewport()->setAcceptDrops(true);
      this->setAcceptDrops(true);
  }
  else
      viewport()->setMouseTracking(false);

	setDragAutoScroll(true);

	// The cross rectangle cursor
	QBitmap b(32,32,true);
	QBitmap b2(32,32,true);
	QPainter p(&b);
	// the cross
  p.drawLine(0,8,6,8);
  p.drawLine(10,8,16,8);
	p.drawLine(8,0,8,6);
	p.drawLine(8,10,8,16);
	// the rectangle
	p.drawRect(17,17,8,6);

	p.end();

	p.begin(&b2);
	// the cross black lines
  p.drawLine(0,8,6,8);
  p.drawLine(10,8,16,8);
	p.drawLine(8,0,8,6);
	p.drawLine(8,10,8,16);

	// the cross white lines
  p.drawLine(0,7,6,7);
  p.drawLine(10,7,16,7);
	p.drawLine(7,0,7,6);
	p.drawLine(7,10,7,16);

	// the cross white lines
  p.drawLine(0,9,6,9);
  p.drawLine(10,9,16,9);
	p.drawLine(9,0,9,6);
	p.drawLine(9,10,9,16);

	// the rectangles
	p.drawRect(17,17,8,6);	// black
	p.drawRect(18,18,6,4);  // white
	p.drawRect(16,16,10,8); // white

	p.end();

	RectangleCursor = QCursor(b,b2,8,8);


	// The cross circle cursor
	b = QBitmap(32,32,true);
	b2 = QBitmap(32,32,true);
	p.begin(&b);
	// the cross
  p.drawLine(0,8,6,8);
  p.drawLine(10,8,16,8);
	p.drawLine(8,0,8,6);
	p.drawLine(8,10,8,16);
	// the circle
	p.drawEllipse(17,17,8,8);

	p.end();

	p.begin(&b2);
	// the cross black lines
  p.drawLine(0,8,6,8);
  p.drawLine(10,8,16,8);
	p.drawLine(8,0,8,6);
	p.drawLine(8,10,8,16);

	// the cross white lines
  p.drawLine(0,7,6,7);
  p.drawLine(10,7,16,7);
	p.drawLine(7,0,7,6);
	p.drawLine(7,10,7,16);

	// the cross white lines
  p.drawLine(0,9,6,9);
  p.drawLine(10,9,16,9);
	p.drawLine(9,0,9,6);
	p.drawLine(9,10,9,16);

	// the circles
	p.drawEllipse(17,17,8,8);  // black
	p.drawEllipse(16,16,10,10);  // white
	p.drawEllipse(18,18,6,6);  // white

	p.end();

	CircleCursor = QCursor(b,b2,8,8);

	QString path = KGlobal::dirs()->findResourceDir( "data", "kimagemapeditor/polygoncursor.png" ) + "kimagemapeditor/polygoncursor.png";
	PolygonCursor = QCursor(QPixmap(path),8,8);

	path = KGlobal::dirs()->findResourceDir( "data", "kimagemapeditor/freehandcursor.png" ) + "kimagemapeditor/freehandcursor.png";
	FreehandCursor = QCursor(QPixmap(path),8,8);

	path = KGlobal::dirs()->findResourceDir( "data", "kimagemapeditor/addpointcursor.png" ) + "kimagemapeditor/addpointcursor.png";
	AddPointCursor = QCursor(QPixmap(path),8,8);

	path = KGlobal::dirs()->findResourceDir( "data", "kimagemapeditor/removepointcursor.png" ) + "kimagemapeditor/removepointcursor.png";
	RemovePointCursor = QCursor(QPixmap(path),8,8);
}
void Foam::threePhaseInterfaceProperties::correctContactAngle
(
    surfaceVectorField::GeometricBoundaryField& nHatb
) const
{
    const volScalarField::GeometricBoundaryField& alpha1 =
        mixture_.alpha1().boundaryField();
    const volScalarField::GeometricBoundaryField& alpha2 =
        mixture_.alpha2().boundaryField();
    const volScalarField::GeometricBoundaryField& alpha3 =
        mixture_.alpha3().boundaryField();
    const volVectorField::GeometricBoundaryField& U =
        mixture_.U().boundaryField();

    const fvMesh& mesh = mixture_.U().mesh();
    const fvBoundaryMesh& boundary = mesh.boundary();

    forAll(boundary, patchi)
    {
        if (isA<alphaContactAngleFvPatchScalarField>(alpha1[patchi]))
        {
            const alphaContactAngleFvPatchScalarField& a2cap =
                refCast<const alphaContactAngleFvPatchScalarField>
                (alpha2[patchi]);

            const alphaContactAngleFvPatchScalarField& a3cap =
                refCast<const alphaContactAngleFvPatchScalarField>
                (alpha3[patchi]);

            scalarField twoPhaseAlpha2(max(a2cap, scalar(0)));
            scalarField twoPhaseAlpha3(max(a3cap, scalar(0)));

            scalarField sumTwoPhaseAlpha
            (
                twoPhaseAlpha2 + twoPhaseAlpha3 + SMALL
            );

            twoPhaseAlpha2 /= sumTwoPhaseAlpha;
            twoPhaseAlpha3 /= sumTwoPhaseAlpha;

            fvsPatchVectorField& nHatp = nHatb[patchi];

            scalarField theta
            (
                convertToRad
              * (
                   twoPhaseAlpha2*(180 - a2cap.theta(U[patchi], nHatp))
                 + twoPhaseAlpha3*(180 - a3cap.theta(U[patchi], nHatp))
                )
            );

            vectorField nf(boundary[patchi].nf());

            // Reset nHatPatch to correspond to the contact angle

            scalarField a12(nHatp & nf);

            scalarField b1(cos(theta));

            scalarField b2(nHatp.size());

            forAll(b2, facei)
            {
                b2[facei] = cos(acos(a12[facei]) - theta[facei]);
            }

            scalarField det(1.0 - a12*a12);

            scalarField a((b1 - a12*b2)/det);
            scalarField b((b2 - a12*b1)/det);

            nHatp = a*nf + b*nHatp;

            nHatp /= (mag(nHatp) + deltaN_.value());
        }
    }
TEST_SUBMODULE(multiple_inheritance, m) {

    // test_multiple_inheritance_mix1
    // test_multiple_inheritance_mix2
    struct Base1 {
        Base1(int i) : i(i) { }
        int foo() { return i; }
        int i;
    };
    py::class_<Base1> b1(m, "Base1");
    b1.def(py::init<int>())
      .def("foo", &Base1::foo);

    struct Base2 {
        Base2(int i) : i(i) { }
        int bar() { return i; }
        int i;
    };
    py::class_<Base2> b2(m, "Base2");
    b2.def(py::init<int>())
      .def("bar", &Base2::bar);


    // test_multiple_inheritance_cpp
    struct Base12 : Base1, Base2 {
        Base12(int i, int j) : Base1(i), Base2(j) { }
    };
    struct MIType : Base12 {
        MIType(int i, int j) : Base12(i, j) { }
    };
    py::class_<Base12, Base1, Base2>(m, "Base12");
    py::class_<MIType, Base12>(m, "MIType")
        .def(py::init<int, int>());


    // test_multiple_inheritance_python_many_bases
    #define PYBIND11_BASEN(N) py::class_<BaseN<N>>(m, "BaseN" #N).def(py::init<int>()).def("f" #N, [](BaseN<N> &b) { return b.i + N; })
    PYBIND11_BASEN( 1); PYBIND11_BASEN( 2); PYBIND11_BASEN( 3); PYBIND11_BASEN( 4);
    PYBIND11_BASEN( 5); PYBIND11_BASEN( 6); PYBIND11_BASEN( 7); PYBIND11_BASEN( 8);
    PYBIND11_BASEN( 9); PYBIND11_BASEN(10); PYBIND11_BASEN(11); PYBIND11_BASEN(12);
    PYBIND11_BASEN(13); PYBIND11_BASEN(14); PYBIND11_BASEN(15); PYBIND11_BASEN(16);
    PYBIND11_BASEN(17);

    // Uncommenting this should result in a compile time failure (MI can only be specified via
    // template parameters because pybind has to know the types involved; see discussion in #742 for
    // details).
//    struct Base12v2 : Base1, Base2 {
//        Base12v2(int i, int j) : Base1(i), Base2(j) { }
//    };
//    py::class_<Base12v2>(m, "Base12v2", b1, b2)
//        .def(py::init<int, int>());


    // test_multiple_inheritance_virtbase
    // Test the case where not all base classes are specified, and where pybind11 requires the
    // py::multiple_inheritance flag to perform proper casting between types.
    struct Base1a {
        Base1a(int i) : i(i) { }
        int foo() { return i; }
        int i;
    };
    py::class_<Base1a, std::shared_ptr<Base1a>>(m, "Base1a")
        .def(py::init<int>())
        .def("foo", &Base1a::foo);

    struct Base2a {
        Base2a(int i) : i(i) { }
        int bar() { return i; }
        int i;
    };
    py::class_<Base2a, std::shared_ptr<Base2a>>(m, "Base2a")
        .def(py::init<int>())
        .def("bar", &Base2a::bar);

    struct Base12a : Base1a, Base2a {
        Base12a(int i, int j) : Base1a(i), Base2a(j) { }
    };
    py::class_<Base12a, /* Base1 missing */ Base2a,
               std::shared_ptr<Base12a>>(m, "Base12a", py::multiple_inheritance())
        .def(py::init<int, int>());

    m.def("bar_base2a", [](Base2a *b) { return b->bar(); });
    m.def("bar_base2a_sharedptr", [](std::shared_ptr<Base2a> b) { return b->bar(); });

    // test_mi_unaligned_base
    // test_mi_base_return
    // Issue #801: invalid casting to derived type with MI bases
    struct I801B1 { int a = 1; I801B1() = default; I801B1(const I801B1 &) = default; virtual ~I801B1() = default; };
    struct I801B2 { int b = 2; I801B2() = default; I801B2(const I801B2 &) = default; virtual ~I801B2() = default; };
    struct I801C : I801B1, I801B2 {};
    struct I801D : I801C {}; // Indirect MI
    // Unregistered classes:
    struct I801B3 { int c = 3; virtual ~I801B3() = default; };
    struct I801E : I801B3, I801D {};

    py::class_<I801B1, std::shared_ptr<I801B1>>(m, "I801B1").def(py::init<>()).def_readonly("a", &I801B1::a);
    py::class_<I801B2, std::shared_ptr<I801B2>>(m, "I801B2").def(py::init<>()).def_readonly("b", &I801B2::b);
    py::class_<I801C, I801B1, I801B2, std::shared_ptr<I801C>>(m, "I801C").def(py::init<>());
    py::class_<I801D, I801C, std::shared_ptr<I801D>>(m, "I801D").def(py::init<>());

    // Two separate issues here: first, we want to recognize a pointer to a base type as being a
    // known instance even when the pointer value is unequal (i.e. due to a non-first
    // multiple-inheritance base class):
    m.def("i801b1_c", [](I801C *c) { return static_cast<I801B1 *>(c); });
    m.def("i801b2_c", [](I801C *c) { return static_cast<I801B2 *>(c); });
    m.def("i801b1_d", [](I801D *d) { return static_cast<I801B1 *>(d); });
    m.def("i801b2_d", [](I801D *d) { return static_cast<I801B2 *>(d); });

    // Second, when returned a base class pointer to a derived instance, we cannot assume that the
    // pointer is `reinterpret_cast`able to the derived pointer because, like above, the base class
    // pointer could be offset.
    m.def("i801c_b1", []() -> I801B1 * { return new I801C(); });
    m.def("i801c_b2", []() -> I801B2 * { return new I801C(); });
    m.def("i801d_b1", []() -> I801B1 * { return new I801D(); });
    m.def("i801d_b2", []() -> I801B2 * { return new I801D(); });

    // Return a base class pointer to a pybind-registered type when the actual derived type
    // isn't pybind-registered (and uses multiple-inheritance to offset the pybind base)
    m.def("i801e_c", []() -> I801C * { return new I801E(); });
    m.def("i801e_b2", []() -> I801B2 * { return new I801E(); });


    // test_mi_static_properties
    py::class_<Vanilla>(m, "Vanilla")
        .def(py::init<>())
        .def("vanilla", &Vanilla::vanilla);

    py::class_<WithStatic1>(m, "WithStatic1")
        .def(py::init<>())
        .def_static("static_func1", &WithStatic1::static_func1)
        .def_readwrite_static("static_value1", &WithStatic1::static_value1);

    py::class_<WithStatic2>(m, "WithStatic2")
        .def(py::init<>())
        .def_static("static_func2", &WithStatic2::static_func2)
        .def_readwrite_static("static_value2", &WithStatic2::static_value2);

    py::class_<VanillaStaticMix1, Vanilla, WithStatic1, WithStatic2>(
        m, "VanillaStaticMix1")
        .def(py::init<>())
        .def_static("static_func", &VanillaStaticMix1::static_func)
        .def_readwrite_static("static_value", &VanillaStaticMix1::static_value);

    py::class_<VanillaStaticMix2, WithStatic1, Vanilla, WithStatic2>(
        m, "VanillaStaticMix2")
        .def(py::init<>())
        .def_static("static_func", &VanillaStaticMix2::static_func)
        .def_readwrite_static("static_value", &VanillaStaticMix2::static_value);


#if !defined(PYPY_VERSION)
    struct WithDict { };
    struct VanillaDictMix1 : Vanilla, WithDict { };
    struct VanillaDictMix2 : WithDict, Vanilla { };
    py::class_<WithDict>(m, "WithDict", py::dynamic_attr()).def(py::init<>());
    py::class_<VanillaDictMix1, Vanilla, WithDict>(m, "VanillaDictMix1").def(py::init<>());
    py::class_<VanillaDictMix2, WithDict, Vanilla>(m, "VanillaDictMix2").def(py::init<>());
#endif

    // test_diamond_inheritance
    // Issue #959: segfault when constructing diamond inheritance instance
    // All of these have int members so that there will be various unequal pointers involved.
    struct B { int b; B() = default; B(const B&) = default; virtual ~B() = default; };
    struct C0 : public virtual B { int c0; };
    struct C1 : public virtual B { int c1; };
    struct D : public C0, public C1 { int d; };
    py::class_<B>(m, "B")
        .def("b", [](B *self) { return self; });
    py::class_<C0, B>(m, "C0")
        .def("c0", [](C0 *self) { return self; });
    py::class_<C1, B>(m, "C1")
        .def("c1", [](C1 *self) { return self; });
    py::class_<D, C0, C1>(m, "D")
        .def(py::init<>());
}
예제 #11
0
void level_two()
{
		vector<DPipe> DPIPES(44);
	vector<DoublePipe> DOUBPIPES(18);
	vector<CrossPipe> CROSSPIPES(3);

	DPipe background(600,400,1200,800);

	DPipe a0(50,750,100,40);
	DPipe a1(150,650,100,40);
	DPipe a2(150,550,100,40);
	DPipe a3(650,450,100,40);
	DPipe a4(550,550,100,40);
	DPipe a5(450,350,100,40);
	DPipe a6(550,250,100,40);
	DPipe a7(650,250,100,40);
	DPipe a8(750,350,100,40);
	DPipe a9(750,450,100,40);
	DPipe a10(750,550,100,40);
	DPipe a11(650,650,100,40);
	DPipe a12(550,650,100,40);
	DPipe a13(450,650,100,40);
	DPipe a14(350,550,100,40);
	DPipe a15(350,350,100,40);
	DPipe a16(350,250,100,40);
	DPipe a17(450,150,100,40);
	DPipe a18(550,150,100,40);
	DPipe a19(650,150,100,40);
	DPipe a20(750,150,100,40);
	DPipe a21(850,250,100,40);
	DPipe a22(850,350,100,40);
	DPipe a23(850,450,100,40);
	DPipe a24(850,550,100,40);
	DPipe a25(850,650,100,40);
	DPipe a26(750,750,100,40);
	DPipe a27(650,750,100,40);
	DPipe a28(550,750,100,40);
	DPipe a29(450,750,100,40);
	DPipe a30(350,750,100,40);
	DPipe a31(250,650,100,40);
	DPipe a32(250,550,100,40);
	DPipe a33(250,350,100,40);
	DPipe a34(250,250,100,40);
	DPipe a35(250,150,100,40);
	DPipe a36(350,50,100,40);
	DPipe a37(450,50,100,40);
	DPipe a38(550,50,100,40);
	DPipe a39(650,50,100,40);
	DPipe a40(750,50,100,40);
	DPipe a41(850,50,100,40);
	DPipe a42(950,150,100,40);
	DPipe a43(950,250,100,40);

	DoublePipe b0(150,750,70,40);
	DoublePipe b1(150,450,70,40);
	DoublePipe b2(550,450,70,40);
	DoublePipe b3(550,350,70,40);
	DoublePipe b4(650,350,70,40);
	DoublePipe b5(650,550,70,40);
	DoublePipe b6(450,550,70,40);
	DoublePipe b7(450,250,70,40);
	DoublePipe b8(750,250,70,40);
	DoublePipe b9(750,650,70,40);
	DoublePipe b10(350,650,70,40);
	DoublePipe b11(350,150,70,40);
	DoublePipe b12(850,150,70,40);
	DoublePipe b13(850,750,70,40);
	DoublePipe b14(250,750,70,40);
	DoublePipe b15(250,50,70,40);
	DoublePipe b16(950,50,70,40);
	DoublePipe b17(950,350,70,40);

	CrossPipe c0(250,450,100,40);
	CrossPipe c1(350,450,100,40);
	CrossPipe c2(450,450,100,40);

	DPIPES[0]=a0;
	DPIPES[1]=a1;
	DPIPES[2]=a2;
	DPIPES[3]=a3;
	DPIPES[4]=a4;
	DPIPES[5]=a5;
	DPIPES[6]=a6;
	DPIPES[7]=a7;
	DPIPES[8]=a8;
	DPIPES[9]=a9;
	DPIPES[10]=a10;
	DPIPES[11]=a11;
	DPIPES[12]=a12;
	DPIPES[13]=a13;
	DPIPES[14]=a14;
	DPIPES[15]=a15;
	DPIPES[16]=a16;
	DPIPES[17]=a17;
	DPIPES[18]=a18;
	DPIPES[19]=a19;
	DPIPES[20]=a20;
	DPIPES[21]=a21;
	DPIPES[22]=a22;
	DPIPES[23]=a23;
	DPIPES[24]=a24;
	DPIPES[25]=a25;
	DPIPES[26]=a26;
	DPIPES[27]=a27;
	DPIPES[28]=a28;
	DPIPES[29]=a29;
	DPIPES[30]=a30;
	DPIPES[31]=a31;
	DPIPES[32]=a32;
	DPIPES[33]=a33;
	DPIPES[34]=a34;
	DPIPES[35]=a35;
	DPIPES[36]=a36;
	DPIPES[37]=a37;
	DPIPES[38]=a38;
	DPIPES[39]=a39;
	DPIPES[40]=a40;
	DPIPES[41]=a41;
	DPIPES[42]=a42;
	DPIPES[43]=a43;

	DOUBPIPES[0]=b0;
	DOUBPIPES[1]=b1;
	DOUBPIPES[2]=b2;
	DOUBPIPES[3]=b3;
	DOUBPIPES[4]=b4;
	DOUBPIPES[5]=b5;
	DOUBPIPES[6]=b6;
	DOUBPIPES[7]=b7;
	DOUBPIPES[8]=b8;
	DOUBPIPES[9]=b9;
	DOUBPIPES[10]=b10;
	DOUBPIPES[11]=b11;
	DOUBPIPES[12]=b12;
	DOUBPIPES[13]=b13;
	DOUBPIPES[14]=b14;
	DOUBPIPES[15]=b15;
	DOUBPIPES[16]=b16;
	DOUBPIPES[17]=b17;

	CROSSPIPES[0]=c0;
	CROSSPIPES[1]=c1;
	CROSSPIPES[2]=c2;
}
예제 #12
0
파일: Darwin.cpp 프로젝트: dcesini/Darwin
int main() {
   constants_wrapper cfg;
   cfg.show();
   InitRNG RNG;
   RNG.seed(cfg.SEED);
   int a(0);
   if (!a) std::cout << "TRUEEEEE!!!" << std::endl;
   std::cout << std::endl << std::endl;
   std::cout << "X_MIN = " << cfg.X_MIN << std::endl;
   std::cout << "X_MAX = " << cfg.X_MAX << std::endl;
   std::cout << "Y_MIN = " << cfg.Y_MIN << std::endl;
   std::cout << "Y_MAX = " << cfg.Y_MAX << std::endl;

   std::cout << "READ_FOOD_FROM_FILE = " << cfg.READ_FOOD_FROM_FILE << std::endl;
   std::cout << "FOOD_POINT_DISTRIBUTION = " << cfg.FOOD_POINT_DISTRIBUTION << std::endl;


   chromo beauty_d(beauty_default);
   chromo dim_d(dim_default);
   chromo athlet_d(athlet_default);
   chromo karma_d(karma_default);
   chromo attracted_d(attracted_default);
   chromo charm_d(charm_default);

   DNA dna1(charm_d, beauty_d, dim_d, athlet_d, karma_d, attracted_d);
   DNA dna2(attracted_d, beauty_d, dim_d, athlet_d, karma_d, attracted_d);
   //dna2.set_chromo(c1,5);
   if (dna1 == dna2)  {
      std::cout << "TRUE1" << std::endl;
   } else { std::cout << "qualche problema" << std::endl;
     };
   
   being conf_being(dna1, 0, cfg.starting_energy, true, 1.0, 2.0, 0, 0);
   conf_being.configure(cfg);
   being b1(dna1, 0, cfg.starting_energy, true, 1.0, 2.0, 0, 0);
   //b1.show();
   being b2(dna2, 0, 100, true, 2.0, 2.0, 0, 0);

   food_point fp2(4.1, 4.2, cfg.default_nutrival);
   food_point fp3(1.1, 2.2, cfg.default_nutrival);

   point_2d p1(1,1);
   point_2d p2(2,2);

   // create and open a character archive for output
   std::ofstream ofs("./points.txt");
   // save data to archive
    {
        boost::archive::text_oarchive oa(ofs);
        // write class instance to archive
        oa << p1;
        oa << p2;
        oa << beauty_d;
        oa << dna1;
        oa << b1;
    	// archive and stream closed when destructors are called
    }


    // ... some time later restore the class instance to its orginal state
    point_2d p1new;
    point_2d p2new;
    chromo new_beauty;
    DNA dna1new;
    being b1new;

    {
        // create and open an archive for input
        std::ifstream ifs("./points.txt");
        boost::archive::text_iarchive ia(ifs);
        // read class state from archive
        ia >> p1new;
        ia >> p2new;
        ia >> new_beauty;
        ia >> dna1new;
        ia >> b1new;
        // archive and stream closed when destructors are called
    }

   std::cout << "P1new = ";
   p1new.show_point();
   std::cout << std::endl;

   std::cout << "P2new = ";
   p2new.show_point();
   std::cout << std::endl;

   std::cout << "new beauty = " << new_beauty << std::endl;
   std::cout << "newdna1 = " << dna1new << std::endl;

   if (dna1 == dna1new) std::cout << "TRUE!" << std::endl;

   std::cout << "B1NEW = " << std::endl << b1new << std::endl;

   world myworld(cfg.N_BEINGS,cfg.N_FOOD_POINT_AT_START);
   myworld.name("MyWorld");
   std::cout << "World name = " << myworld.name() << std::endl;
   
   //myworld.add(b1);
   //myworld.add(b2);
   //myworld.add(fp2);
   //myworld.add(fp3);
   //myworld.stats();
   //myworld.advance_one_generation();
   //myworld.stats();

//   myworld.load("DATA/200.txt");
//   myworld.stats();
//   myworld.evolve(1);
//   myworld.stats();

   std::vector<int> iv;
   iv.reserve(10);
   for (int i=0; i<10; ++i) iv.push_back(i);

   std::vector<int>::iterator iv_end = iv.end();
   for (std::vector<int>::iterator it = iv.begin(); it!=iv_end; ++it) {
      std::cout << *it << std::endl;
      iv.push_back(11);
   }

   if (cfg.BEINGS_START_DISTRIBUTION == "UNIFORM") {
      std::uniform_real_distribution<float> beings_distribution_x(cfg.X_MIN , cfg.X_MAX);
      std::uniform_real_distribution<float> beings_distribution_y(cfg.Y_MIN , cfg.Y_MAX);
      for (int i = 0; i < cfg.N_BEINGS; ++i) {
         b1.set_x(beings_distribution_x(RNG.generator));
         b1.set_y(beings_distribution_y(RNG.generator));
         myworld.add(b1) ;
      };
   };

   std::cout << "READ_FOOD_FROM_FILE = " << cfg.READ_FOOD_FROM_FILE << std::endl;
   if (!cfg.READ_FOOD_FROM_FILE) 
   {
      std::cout << "Creating food point from scratch" << std::endl;
      if (cfg.FOOD_POINT_DISTRIBUTION == "UNIFORM") {
         std::uniform_real_distribution<float> food_distribution_x(cfg.X_MIN , cfg.X_MAX);
         std::uniform_real_distribution<float> food_distribution_y(cfg.Y_MIN , cfg.Y_MAX);
         for (int i = 0; i < cfg.N_FOOD_POINT_AT_START; ++i) {
            food_point fpx( food_distribution_x(RNG.generator) , food_distribution_y(RNG.generator) , cfg.default_nutrival );
            myworld.add(fpx) ;
         }
      }
   }
   else 
   {
      std::cout << "Reading food points from file = " << cfg.food_file << std::endl;
      // create and open an archive for input
      std::ifstream ifs2(cfg.food_file);
      boost::archive::text_iarchive ia(ifs2);
      food_point newfp;
      // read class state from archive
      for (int i=0; i<cfg.N_FOOD_POINT_AT_START; ++i) {
         ia >> newfp;
         myworld.add(newfp);
      }
   };
  

   myworld.stats();

   //return 0;
   std::chrono::time_point<std::chrono::high_resolution_clock> start, end;
   start = std::chrono::high_resolution_clock::now();
   myworld.evolve(cfg.ITER_NUMBER);
   end = std::chrono::high_resolution_clock::now();
   cfg.save("myworld.cfg");
   std::cout << "World evolved in = " << std::chrono::duration_cast<std::chrono::milliseconds>(end - start).count() << "ms." << std::endl;
/*
   // create and open a character archive for output
   std::ofstream ofs2("./world.txt");
   // save data to archive
    {
        boost::archive::text_oarchive oa(ofs2);
        // write class instance to archive
        oa << myworld;
        // archive and stream closed when destructors are called
    }



    world newworld(1000,1000);


    {
        // create and open an archive for input
        std::ifstream ifs2("./world.txt");
        boost::archive::text_iarchive ia(ifs2);
        // read class state from archive
        ia >> newworld;
        // archive and stream closed when destructors are called
    }


   newworld.stats();
*/
   return 0;
};
void f(const B &b1) {
  B b2(b1);
}
예제 #14
0
int		main(void)
{
	std::cout << "PART 00" << std::endl;
	// -------------------   PART 00   ------------------------------ //
	Bureaucrat b1("b1", 5);
	Bureaucrat b2("b2", 147);

	try
	{
		Bureaucrat *b3 = new Bureaucrat("b3", 1000);
		delete b3;
	}
	catch (std::exception &e)
	{
		std::cout << "Error: " << e.what() << std::endl;
	}

	for (int i = 0; i < 8; i++)
	{
		try
		{
			b1 += 1;
			b2 -= 1;
		}
		catch (std::exception &e)
		{
			std::cout << "Error: " << e.what() << std::endl;
		}
		std::cout << b1;
		std::cout << b2;
	}



	std::cout << std::endl << "PART 01" << std::endl;
	// -------------------   PART 01   ------------------------------ //
    Form f1("f1", 5, 5);
    Form f2("f2", 100, 100);

	try
	{
		Form *f3 = new Form("f3", 1000, 1000);
		delete f3;
	}
	catch (std::exception &e)
	{
		std::cout << "Error: " << e.what() << std::endl;
	}

    std::cout << f1;
    std::cout << f2;    

    try
    {
        b1.signForm(f1);
    }
    catch (std::exception &e)
    {
        std::cout << "Error: " << e.what() << std::endl;
    }
    std::cout << f1;
    
    try
    {
        b2.signForm(f1);
    }
    catch (std::exception &e)
    {
        std::cout << "Error: " << e.what() << std::endl;
    }
    std::cout << f1;
    
    try
    {
        b1.signForm(f2);
    }
    catch (std::exception &e)
    {
        std::cout << "Error: " << e.what() << std::endl;
    }
    std::cout << f2;

    try
    {
        b2.signForm(f2);
    }
    catch (std::exception &e)
    {
        std::cout << "Error: " << e.what() << std::endl;
    }
    std::cout << f2;

    try
    {
        b2.signForm(f2);
    }
    catch (std::exception &e)
    {
        std::cout << "Error: " << e.what() << std::endl;
    }
    std::cout << f2;

	return (0);
}
예제 #15
0
int main()
{
  B b1;
  B b2(b1);		    // { dg-error "deleted function .B::B.const" }
  B b3(static_cast<B&&>(b1));
}
예제 #16
0
int test_main(int, char* [])
{
    typedef bg::model::d2::point_xy<boost::long_long_type> point;
    typedef bg::model::segment<point> segment;

    typedef bg::strategy::side::side_of_intersection side;

    point no_fb(-99, -99);

    segment a(point(20, 10), point(10, 20));

    segment b1(point(11, 16), point(20, 14));  // IP with a: (14.857, 15.143)
    segment b2(point(10, 16), point(20, 14));  // IP with a: (15, 15)

    segment c1(point(15, 16), point(13, 8));
    segment c2(point(15, 16), point(14, 8));
    segment c3(point(15, 16), point(15, 8));


    BOOST_CHECK_EQUAL( 1, side::apply(a, b1, c1, no_fb));
    BOOST_CHECK_EQUAL(-1, side::apply(a, b1, c2, no_fb));
    BOOST_CHECK_EQUAL(-1, side::apply(a, b1, c3, no_fb));

    BOOST_CHECK_EQUAL( 1, side::apply(a, b2, c1, no_fb));
    BOOST_CHECK_EQUAL( 1, side::apply(a, b2, c2, no_fb));
    BOOST_CHECK_EQUAL( 0, side::apply(a, b2, c3, no_fb));

    // Collinear cases
    // 1: segments intersecting are collinear (with a fallback point):
    {
        point fb(5, 5);
        segment col1(point(0, 5), point(5, 5));
        segment col2(point(5, 5), point(10, 5)); // One IP with col1 at (5,5)
        segment col3(point(5, 0), point(5, 5));
        BOOST_CHECK_EQUAL( 0, side::apply(col1, col2, col3, fb));
    }
    // 2: segment of side calculation collinear with one of the segments
    {
        point fb(5, 5);
        segment col1(point(0, 5), point(10, 5));
        segment col2(point(5, 5), point(5, 12)); // IP with col1 at (5,5)
        segment col3(point(5, 1), point(5, 5)); // collinear with col2
        BOOST_CHECK_EQUAL( 0, side::apply(col1, col2, col3, fb));
    }
    {
        point fb(5, 5);
        segment col1(point(10, 5), point(0, 5));
        segment col2(point(5, 5), point(5, 12)); // IP with col1 at (5,5)
        segment col3(point(5, 1), point(5, 5)); // collinear with col2
        BOOST_CHECK_EQUAL( 0, side::apply(col1, col2, col3, fb));
    }
    {
        point fb(5, 5);
        segment col1(point(0, 5), point(10, 5));
        segment col2(point(5, 12), point(5, 5)); // IP with col1 at (5,5)
        segment col3(point(5, 1), point(5, 5)); // collinear with col2
        BOOST_CHECK_EQUAL( 0, side::apply(col1, col2, col3, fb));
    }

    {
        point fb(517248, -517236);
        segment col1(point(-172408, -517236), point(862076, -517236));
        segment col2(point(517248, -862064), point(517248, -172408));
        segment col3(point(517248, -172408), point(517248, -517236));
        BOOST_CHECK_EQUAL( 0, side::apply(col1, col2, col3, fb));
    }
    {
        point fb(-221647, -830336);
        segment col1(point(-153817, -837972), point(-222457, -830244));
        segment col2(point(-221139, -833615), point(-290654, -384388));
        segment col3(point(-255266, -814663), point(-264389, -811197));
        BOOST_CHECK_EQUAL(1, side::apply(col1, col2, col3, fb)); // Left of segment...
    }


    {
        point fb(27671131, 30809240);
        segment col1(point(27671116, 30809247), point(27675474, 30807351));
        segment col2(point(27666779, 30811130), point(27671139, 30809237));
        segment col3(point(27671122, 30809244), point(27675480, 30807348));
        BOOST_CHECK_EQUAL(1, side::apply(col1, col2, col3, fb)); // Left of segment...
    }

    // TODO: we might add a check calculating the IP, determining the side
    // with the normal side strategy, and verify the results are equal

    return 0;
}
예제 #17
0
int main()
{
    car c("fred");
    roadlet *r1, *r2;
    roadlet *r3, *r4;
    char *buff;
    int i;

    srandom(5);

    // build a two lane one direction road

    r1 = new roadlet ("R start");
    r3 = new roadlet ("L start");
    connect(r1, W, r3, E, return_null); // there but can't move to

    c.set_location(r1);		// a car
    r1->arrive(&c);

    for(i=0; i<10; i++)
    {
	buff = (char *)malloc(4);
	sprintf(buff, "R%d", i);
	r2 = new roadlet(buff);

	buff = (char *)malloc(4);
	sprintf(buff, "L%d", i);
	r4 = new roadlet(buff);

        connect(r1, N, r2, S, &is_empty);
        connect(r3, N, r4, S, &is_empty);
        connect(r1, NW, r4, SE, &lane_switch_ok);
        connect(r3, NE, r2, SW, &lane_switch_ok);
        connect(r2, W, r4, E, return_null); // can't more sideways

	r1 = r2;
	r3 = r4;
    }

    car b2("blocker 2");
    b2.set_location(r1);		// a car
    r1->arrive(&b2);
    cout << b2 << '\n';

    intersection_4x4 i1("intersection ");

    i1.connectSin(r3, r1);

    broken_light l(3,1,4,1);

    for(i = 0; i < 100000; i++)
    {
	cout << l << "\n";
	l.tick();
    }

    for(i=0; i< 100000; i++)
    {
        i1.light()->tick();
    }


    r1 = new roadlet ("East Road R ");
    r3 = new roadlet ("East Road L ");
    connect(r1, N, r3, S, return_null); // there but can't move to

    car b("blocker");
    b.set_location(r1);		// a car
    r1->arrive(&b);
    cout << b << '\n';

    i1.connectEout(r3, r1);

    for(i=0; i< 100000; i++)
    {
        cout << '\n' << i << ' ' << c << '\n';
        c.tick();
    }
    cout << i << ' ' << c << '\n';
}
예제 #18
0
void construct_b() {
  int a;
  B b1(&a);
  B b2("%d %d", 1, 2);
}
예제 #19
0
int main(int argc, char *argv[])
{
  Pooma::initialize(argc, argv);
  Pooma::Tester tester(argc, argv);

  // To declare a field, you first need to set up a layout. This requires
  // knowing the physical vertex-domain and the number of external guard
  // cell layers. Vertex domains contain enough points to hold all of the
  // rectilinear centerings that POOMA is likely to support for quite
  // awhile. Also, it means that the same layout can be used for all
  // fields, regardless of centering.
  
  Interval<2> physicalVertexDomain(14, 14);
  Loc<2> blocks(3, 3);
  GridLayout<2> layout1(physicalVertexDomain, blocks, GuardLayers<2>(1),
                        LayoutTag_t());
  GridLayout<2> layout0(physicalVertexDomain, blocks, GuardLayers<2>(0),
                        LayoutTag_t());

  Centering<2> cell = canonicalCentering<2>(CellType, Continuous, AllDim);
  Centering<2> vert = canonicalCentering<2>(VertexType, Continuous, AllDim);
  Centering<2> yedge = canonicalCentering<2>(EdgeType, Continuous, YDim);

  Vector<2> origin(0.0);
  Vector<2> spacings(1.0, 2.0);

  // First basic test verifies that we're assigning to the correct areas
  // on a brick.

  typedef
    Field<UniformRectilinearMesh<2>, double,
    MultiPatch<GridTag, BrickTag_t> > Field_t;
  Field_t b0(cell, layout1, origin, spacings);
  Field_t b1(vert, layout1, origin, spacings);
  Field_t b2(yedge, layout1, origin, spacings);
  Field_t b3(yedge, layout1, origin, spacings);
  Field_t bb0(cell, layout0, origin, spacings);
  Field_t bb1(vert, layout0, origin, spacings);
  Field_t bb2(yedge, layout0, origin, spacings);

  b0.all() = 0.0;
  b1.all() = 0.0;
  b2.all() = 0.0;

  b0 = 1.0;
  b1 = 1.0;
  b2 = 1.0;

  bb0.all() = 0.0;
  bb1.all() = 0.0;
  bb2.all() = 0.0;

  bb0 = 1.0;
  bb1 = 1.0;
  bb2 = 1.0;

  // SPMD code follows.
  // Note, SPMD code will work with the evaluator if you are careful
  // to perform assignment on all the relevant contexts.  The patchLocal
  // function creates a brick on the local context, so you can just perform
  // the assignment on that context.

  int i;

  for (i = 0; i < b0.numPatchesLocal(); ++i)
  {
    Patch<Field_t>::Type_t patch = b0.patchLocal(i);
    //    tester.out() << "context " << Pooma::context() << ":  assigning to patch " << i
    //              << " with domain " << patch.domain() << std::endl;
    patch += 1.5;
  }

  // This is safe to do since b1 and b2 are built with the same layout.
  for (i = 0; i < b1.numPatchesLocal(); ++i)
  {
    b1.patchLocal(i) += 1.5;
    b2.patchLocal(i) += 1.5;
  }

  for (i = 0; i < bb0.numPatchesLocal(); ++i)
  {
    Patch<Field_t>::Type_t patch = bb0.patchLocal(i);
    //    tester.out() << "context " << Pooma::context() << ":  assigning to patch on bb0 " << i
    //              << " with domain " << patch.domain() << std::endl;
    patch += 1.5;
  }

  // This is safe to do since bb1 and bb2 are built with the same layout.
  for (i = 0; i < bb1.numPatchesLocal(); ++i)
  {
    bb1.patchLocal(i) += 1.5;
    bb2.patchLocal(i) += 1.5;
  }

  tester.check("cell centered field is 2.5", all(b0 == 2.5));
  tester.check("vert centered field is 2.5", all(b1 == 2.5));
  tester.check("edge centered field is 2.5", all(b2 == 2.5));

  tester.out() << "b0.all():" << std::endl << b0.all() << std::endl;
  tester.out() << "b1.all():" << std::endl << b1.all() << std::endl;
  tester.out() << "b2.all():" << std::endl << b2.all() << std::endl;

  tester.check("didn't write into b0 boundary",
               sum(b0.all()) == 2.5 * b0.physicalDomain().size());
  tester.check("didn't write into b1 boundary",
               sum(b1.all()) == 2.5 * b1.physicalDomain().size());
  tester.check("didn't write into b2 boundary",
               sum(b2.all()) == 2.5 * b2.physicalDomain().size());

  tester.check("cell centered field is 2.5", all(bb0 == 2.5));
  tester.check("vert centered field is 2.5", all(bb1 == 2.5));
  tester.check("edge centered field is 2.5", all(bb2 == 2.5));

  tester.out() << "bb0:" << std::endl << bb0 << std::endl;
  tester.out() << "bb1:" << std::endl << bb1 << std::endl;
  tester.out() << "bb2:" << std::endl << bb2 << std::endl;

  typedef
    Field<UniformRectilinearMesh<2>, double,
    MultiPatch<GridTag, CompressibleBrickTag_t> > CField_t;
  CField_t c0(cell, layout1, origin, spacings);
  CField_t c1(vert, layout1, origin, spacings);
  CField_t c2(yedge, layout1, origin, spacings);
  CField_t cb0(cell, layout0, origin, spacings);
  CField_t cb1(vert, layout0, origin, spacings);
  CField_t cb2(yedge, layout0, origin, spacings);

  c0.all() = 0.0;
  c1.all() = 0.0;
  c2.all() = 0.0;

  c0 = 1.0;
  c1 = 1.0;
  c2 = 1.0;

  cb0.all() = 0.0;
  cb1.all() = 0.0;
  cb2.all() = 0.0;

  cb0 = 1.0;
  cb1 = 1.0;
  cb2 = 1.0;

  // SPMD code follows.
  // Note, SPMD code will work with the evaluator if you are careful
  // to perform assignment on all the relevant contexts.  The patchLocal
  // function creates a brick on the local context, so you can just perform
  // the assignment on that context.

  for (i = 0; i < c0.numPatchesLocal(); ++i)
  {
    Patch<CField_t>::Type_t patch = c0.patchLocal(i);
    tester.out() << "context " << Pooma::context() << ":  assigning to patch " << i
                 << " with domain " << patch.domain() << std::endl;
    patch += 1.5;
  }

  // This is safe to do since c1 and c2 are built with the same layout.
  for (i = 0; i < c1.numPatchesLocal(); ++i)
  {
    c1.patchLocal(i) += 1.5;
    c2.patchLocal(i) += 1.5;
  }

  for (i = 0; i < cb0.numPatchesLocal(); ++i)
  {
    Patch<CField_t>::Type_t patch = cb0.patchLocal(i);
    tester.out() << "context " << Pooma::context() << ":  assigning to patch on cb0 " << i
                 << " with domain " << patch.domain() << std::endl;
    patch += 1.5;
  }

  // This is safe to do since cb1 and cb2 are cuilt with the same layout.
  for (i = 0; i < cb1.numPatchesLocal(); ++i)
  {
    cb1.patchLocal(i) += 1.5;
    cb2.patchLocal(i) += 1.5;
  }

  tester.check("cell centered field is 2.5", all(c0 == 2.5));
  tester.check("vert centered field is 2.5", all(c1 == 2.5));
  tester.check("edge centered field is 2.5", all(c2 == 2.5));

  tester.out() << "c0.all():" << std::endl << c0.all() << std::endl;
  tester.out() << "c1.all():" << std::endl << c1.all() << std::endl;
  tester.out() << "c2.all():" << std::endl << c2.all() << std::endl;

  tester.check("didn't write into c0 boundary",
               sum(c0.all()) == 2.5 * c0.physicalDomain().size());
  tester.check("didn't write into c1 boundary",
               sum(c1.all()) == 2.5 * c1.physicalDomain().size());
  tester.check("didn't write into c2 boundary",
               sum(c2.all()) == 2.5 * c2.physicalDomain().size());

  tester.check("cell centered field is 2.5", all(cb0 == 2.5));
  tester.check("vert centered field is 2.5", all(cb1 == 2.5));
  tester.check("edge centered field is 2.5", all(cb2 == 2.5));

  tester.out() << "cb0:" << std::endl << cb0 << std::endl;
  tester.out() << "cb1:" << std::endl << cb1 << std::endl;
  tester.out() << "cb2:" << std::endl << cb2 << std::endl;

  //------------------------------------------------------------------
  // Scalar code example:
  //

  c0 = iota(c0.domain()).comp(0);
  c1 = iota(c1.domain()).comp(1);

  // Make sure all the data-parallel are done:

  Pooma::blockAndEvaluate();

  for (i = 0; i < c0.numPatchesLocal(); ++i)
  {
    Patch<CField_t>::Type_t local0 = c0.patchLocal(i);
    Patch<CField_t>::Type_t local1 = c1.patchLocal(i);
    Patch<CField_t>::Type_t local2 = c2.patchLocal(i);

    Interval<2> domain = local2.domain();  // physical domain of local y-edges

    // --------------------------------------------------------------
    // I believe the following is probably the most efficient approach
    // for sparse computations.  For data-parallel computations, the
    // evaluator will uncompress the patches and take brick views, which
    // provide the most efficient access.  If you are only performing
    // the computation on a small portion of cells, then the gains would
    // be outweighed by the act of copying the compressed value to all the
    // cells.
    //
    // The read function is used on the right hand side, because
    // operator() is forced to uncompress the patch just in case you want
    // to write to it.

    for(Interval<2>::iterator pos = domain.begin(); pos != domain.end(); ++pos)
    {
      Loc<2> edge = *pos;
      Loc<2> rightCell = edge;  // cell to right is same cell
      Loc<2> leftCell = edge - Loc<2>(1,0);
      Loc<2> topVert = edge + Loc<2>(0, 1);
      Loc<2> bottomVert = edge;

      local2(edge) =
        local0.read(rightCell) + local0.read(leftCell) +
        local1.read(topVert) + local1.read(bottomVert);
    }

    // This statement is optional, it tries to compress the patch after
    // we're done computing on it.  Since I used .read() for the local0 and 1
    // they remained in their original state. compress() can be expensive, so
    // it may not be worth trying unless space is really important.

    compress(local2);
  }

  tester.out() << "c0" << std::endl << c0 << std::endl;
  tester.out() << "c1" << std::endl << c1 << std::endl;
  tester.out() << "c2" << std::endl << c2 << std::endl;

  //------------------------------------------------------------------
  // Interfacing with a c-function:
  //
  // This example handles the corner cases, where the patches from a
  // cell centered field with no guard layers actually contain some
  // extra data.

  Pooma::blockAndEvaluate();

  for (i = 0; i < cb0.numPatchesLocal(); ++i)
  {
    Patch<CField_t>::Type_t local0 = cb0.patchLocal(i);
    Interval<2> physicalDomain = local0.physicalDomain();
    double *data;
    int size = physicalDomain.size();

    if (physicalDomain == local0.totalDomain())
    {
      uncompress(local0);
      data = &local0(physicalDomain.firsts());
      nonsense(data, size);
    }
    else
    {
      // In this case, the engine has extra storage even though the
      // field has the right domain. We copy it to a brick engine,
      // call the function and copy it back.  No uncompress is required,
      // since the assignment will copy the compressed value into the
      // brick.

      // arrayView is a work-around.  Array = Field doesn't work at
      // the moment.

      Array<2, double, Brick> brick(physicalDomain);
      Array<2, double, CompressibleBrick> arrayView(local0.engine());
      brick = arrayView(physicalDomain);
      Pooma::blockAndEvaluate();
      data = &brick(Loc<2>(0));
      nonsense(data, size);
      arrayView(physicalDomain) = brick;

      // Note that we don't need a blockAndEvaluate here, since an iterate has
      // been spawned to perform the copy.
    }

    // If you want to try compress(local0) here, you should do blockAndEvaluate
    // first in case the local0 = brick hasn't been executed yet.
  }
      
  tester.out() << "cb0.all()" << std::endl << cb0 << std::endl;

  b2 = positions(b2).comp(0);

  RefCountedBlockPtr<double> block = pack(b2);

  // The following functions give you access to the raw data from pack.
  // Note that the lifetime of the data is managed by the RefCountedBlockPtr,
  // so when "block" goes out of scope, the data goes away.  (i.e. Don't write
  // a function where you return block.beginPointer().)

  double *start = block.beginPointer();  // start of the data
  double *end = block.endPointer();      // one past the end
  int size = block.size();               // size of the data

  tester.out() << Pooma::context() << ":" << block.size() << std::endl;

  unpack(b3, block);

  tester.out() << "b2" << std::endl << b2 << std::endl;
  tester.out() << "b3" << std::endl << b3 << std::endl;

  tester.check("pack, unpack", all(b2 == b3));

  int ret = tester.results("LocalPatch");
  Pooma::finalize();
  return ret;
}
예제 #20
0
파일: Inlet.cpp 프로젝트: Azeko2xo/woodem
Vector3r ArcInlet::randomPosition(const Real& rad, const Real& padDist) {
	AlignedBox3r b2(cylBox);
	Vector3r pad(padDist,padDist/cylBox.min()[0],padDist); b2.min()+=pad; b2.max()-=pad;
	if(!spatialBias) return node->loc2glob(CompUtils::cylCoordBox_sample_cartesian(b2));
	else return node->loc2glob(CompUtils::cylCoordBox_sample_cartesian(b2,spatialBias->unitPos(rad)));
}
예제 #21
0
void testgen_lines2points_2d( string res_folder )
{
  //HCoords c(1024, 512);
  //cout << c.width << " " << c.height << " " << c.depth << endl;
  c.depth = c.width/2;
  for ( double num_clusters_f = 1; num_clusters_f < 10; num_clusters_f *= 1.2 )
  {
    Mat3b res(c.height, c.width, Vec3b(255, 255, 255) );
    // generate clusters  
    int num_clusters = int(num_clusters_f);
    vector< pair< Point3d, Point3d > > clusters; //кластер = 2 прямые 
    for (int i_cluster = 0; i_cluster < num_clusters; i_cluster++)
    {
      Point3d a1(rand() % c.width, rand() % c.height, c.depth);
      Point3d a2(rand() % c.width, rand() % c.height, c.depth);
      while (a1 == a2)
      {
        a2 = Point3d(rand() % c.width, rand() % c.height, c.depth);
      }
      Point3d b1(rand() % c.width, rand() % c.height, c.depth);
      Point3d b2(rand() % c.width, rand() % c.height, c.depth);
      while (b1 == b2)
      {
        b2 = Point3d(rand() % c.width, rand() % c.height, c.depth);
      }

      a1.x -= c.width / 2;
      a1.y -= c.height / 2;
      a2.x -= c.width / 2;
      a2.y -= c.height / 2;
      b1.x -= c.width / 2;
      b1.y -= c.height / 2;
      b2.x -= c.width / 2;
      b2.y -= c.height / 2;
      //cout << a1.x << " " << a1.y << " " << a1.z << endl;
      //cout << a2.x << " " << a2.y << " " << a2.z << endl;

      Point3d l1 = a1.cross(a2);
      Point3d l2 = b1.cross(b2);
      l1 = normalize(l1);
      l2 = normalize(l2);
      //cout << l1.x << " " << l1.y << " " << l1.z << endl;

      pair<Point3d, Point3d> center = make_pair(l1, l2);
      clusters.push_back(center);
        
      draw_Line(res, l1, 0);
      draw_Line(res, l2, 0);
    }

    ////////// generate points around clusters
    vector<Point3d> p;// все прямые в кластере
    for (int i_cluster = 0; i_cluster < num_clusters; i_cluster++)
    {
      Scalar color = Scalar(rand() % 256, rand() % 256, rand() % 256) ;
      for (int i1 = 0; i1 < countLines; ++i1)
      {
        double k = 1.0 * (rand() % 1000) / 1000.0 ;
        Point3d c = clusters[i_cluster].first * k + clusters[i_cluster].second * (1.0 - k);
        p.push_back(gen_point_on_sphere(c, sigma));// немного сдвинутая прямая
        //p.push_back(c);
        //cout << c.x << " " << c.y << " " << c.z << endl;
        //cout << p.back().x << " " << p.back().y << " " << p.back().z << endl;
        //cout << endl;
        draw_Line(res, p.back(), color);
      }
    }
    random_shuffle(p.begin(), p.end());

    string test_name = res_folder + format( "line%.03d", num_clusters );
  //  cerr << res_folder << endl;
    ofstream out((test_name + ".txt").c_str());
    out << c.width << " " << c.height << endl;
    out << num_clusters << endl;

    out.precision(6);
    for (int i=0; i<clusters.size(); i++)
    {
      //draw_Line(res, clusters[i].first);
      //draw_Line(res, clusters[i].second);
      out << fixed <<  clusters[i].first.x << "\t" <<  clusters[i].first.y << "\t" << clusters[i].first.z  << "\t" <<  clusters[i].second.x << "\t" << clusters[i].second.y << "\t" << clusters[i].second.z << "\t" << sigma << endl;
    }

    out << p.size() << endl;
    for (int i = 0; i < p.size(); ++i)
    {

      out << fixed << p[i].x << "\t" << p[i].y << "\t" << p[i].z << endl;
    }
    
    imwrite( test_name+".png", res );
   }  
}
예제 #22
0
void test()
{
    {
        ::my_bool_testable_t b1(true);
        if (b1) {
            ;
        }
        else {
            BOOST_ASSERT(false);
        }

        ::my_bool_testable_t b2(false);
        if (!b2) {
            ;
        }
        else {
            BOOST_ASSERT(false);
        }

        if (b1 && b2) {
            BOOST_ASSERT(false);
        }
        else {
            ;
        }

        if (b1 && !b2) {
            ;
        }
        else {
            BOOST_ASSERT(false);
        }
    }

    {
        ::my_dool_testable_t d1(true);
#if 1
        if (d1) { // *no longer* ambiguous!
            ;
        }
        else {
            BOOST_ASSERT(false);
        }
#endif
        if (!!d1) {
            ;
        }
        else {
            BOOST_ASSERT(false);
        }

        ::my_dool_testable_t d2(false);
        if (!d2) {
            ;
        }
        else {
            BOOST_ASSERT(false);
        }
    }

    {
        ::my_bool_testable_t b1(true), b2(false);

        // errors
        // b1 == b2;
        // b1 != b2;
        // b1 < b2;
    }

    {
        ::my_dool_testable_t d1(true), d2(false);

        // errors
        // d1 == d2;
        // d1 != d2;
        // b1 < b2;
    }

    {
        ::my_equality_t e1, e2;
        e1 == e2;
        e1 != e2;
        BOOST_CHECK( e1 ? true : false );
        BOOST_CHECK( e2 ? true : false );
        // e1 < e2; // error
    }

    {
        if (boost::egg::details::safe_true)
            BOOST_CHECK(true);
        else
            BOOST_CHECK(false);

        if (boost::egg::details::safe_false)
            BOOST_CHECK(false);
        else
            BOOST_CHECK(true);
    }
}
예제 #23
0
파일: c2.c 프로젝트: 0-wiz-0/CMake
int c2()
{
  return b2()+1;
}
예제 #24
0
파일: trill.cpp 프로젝트: aiena/MuseScore
void TrillSegment::draw(QPainter* painter) const
      {
      qreal mag  = magS();
      int idx    = score()->symIdx();
      QRectF b2(symbols[idx][trillelementSym].bbox(mag));
      qreal w2   = symbols[idx][trillelementSym].width(mag);

      qreal x2   = pos2().x();

      painter->setPen(curColor());
      if (subtype() == SEGMENT_SINGLE || subtype() == SEGMENT_BEGIN) {
            int sym = 0;
            qreal x0 = 0.0, x1 = 0.0, y = 0.0;
            int n = 0;
            QRectF b1;

            switch(trill()->subtype()) {
                  case Trill::TRILL_LINE:
                        sym  = trillSym;
                        b1   = symbols[idx][sym].bbox(mag);
                        x0   = -b1.x();
                        x1   = x0 + b1.width();
                        n    = int(floor((x2-x1) / w2));
                        y    = 0.0;
                        break;

                  case Trill::UPPRALL_LINE:
                        sym  = upprallSym;
                        b1   = symbols[idx][sym].bbox(mag);
                        x0   = -b1.x();
                        x1   = b1.width();
                        n    = int(floor((x2-x1) / w2));
                        y    = -b1.height();
                        break;
                  case Trill::DOWNPRALL_LINE:
                        sym  = downprallSym;
                        b1   = symbols[idx][sym].bbox(mag);
                        x0   = -b1.x();
                        x1   = b1.width();
                        n    = int(floor((x2-x1) / w2));
                        y    = -b1.height();
                        break;
                  case Trill::PRALLPRALL_LINE:
                        sym  = prallprallSym;
                        b1   = symbols[idx][sym].bbox(mag);
                        x0   = -b1.x();
                        x1   = b1.width();
                        n    = int(floor((x2-x1) / w2));
                        y    = -b1.height();
                        break;
                  case Trill::PURE_LINE:
                        sym = noSym;
                        x0 = 0;
                        x1 = 0;
                        n    = int(floor((x2-x1) / w2));
                        y = 0.0;
                  }
            if (n <= 0)
                  n = 1;
            if (sym != noSym)
                  symbols[idx][sym].draw(painter, mag, QPointF(x0, y));
            symbols[idx][trillelementSym].draw(painter, mag,  QPointF(x1, b2.y() * .9), n);
            }
      else {
            qreal x1 = 0.0;
            int n = int(floor((x2-x1) / w2));
            symbols[idx][trillelementSym].draw(painter, mag,  QPointF(x1, b2.y() * .9), n);
            }
      }
Matrix<double> BspCurvBasisFuncSet::CreateMatrixIntegral(int lev1, int lev2) const
{
	KnotSet kset1 = KnotSet(*kts,ord,num).CreateKnotSetDeriv(lev1);
	KnotSet kset2 = KnotSet(*kts,ord,num).CreateKnotSetDeriv(lev2);
	
	Matrix<double> mat(kset1.GetNum()-(ord-lev1),kset2.GetNum()-(ord-lev2));
	
	BspCurvBasisFuncSet basis1(kset1.GetKnots(),ord-lev1,kset1.GetNum());
	BspCurvBasisFuncSet basis2(kset2.GetKnots(),ord-lev2,kset2.GetNum());

	// find the first basis function for which the last distinct
	// knot is greater than x1



	Matrix<double> mat1(kset1.GetNum()-ord+lev1,kset2.GetNum()-ord+lev2,0.0);



	for (int i=0; i<kset1.GetNum()-ord+lev1; i++)
		for (int j=0; j<kset2.GetNum()-ord+lev2; j++) {
		
			
			// create the two std::sets representing the two knot std::sets
			Vector<double> temp1((*(basis1.b))[i].GetKnots());
			Vector<double> temp2((*(basis2.b))[j].GetKnots());
			std::set<double> s1(temp1.begin(),temp1.end());
			std::set<double> s2(temp2.begin(),temp2.end());

			if (*(--s2.end()) > *(s1.begin())) {
				// form the intersection
				std::set<double> s3;
				std::set_intersection(s1.begin(),s1.end(),s2.begin(),s2.end(),std::inserter(s3,s3.begin()));
			
				// if there is an intersection
				if (s3.size() > 1) {
					Vector<double> v(s3.size());
					std::set<double>::iterator s = s3.begin();

					// copy the elements into a vector
					for (unsigned int k=0; k<s3.size(); k++) v[k] = *s++;
				
					// create the compbezcurvs
					Vector<BezCurv<double> > vec1(s3.size()-1);
					Vector<BezCurv<double> > vec2(s3.size()-1);

					BspCurv<double> b1((*(basis1.b))[i].GetBspCurv()), b2((*(basis2.b))[j].GetBspCurv());
				
					// find the segments of intersection
					for (unsigned int k=0; k<s3.size()-1; k++) {
						int segb1 = b1.GetKnotSet().Find_segment(v[k]);
						int segb2 = b2.GetKnotSet().Find_segment(v[k]);
						
						vec1[k] = b1.GetSegment(segb1);
						vec2[k] = b2.GetSegment(segb2);
					}
				
					CompBezCurv<double> cb1(vec1,s3.size()-1,v);
					CompBezCurv<double> cb2(vec2,s3.size()-1,v);
					CompBezCurv<double> prod = cb1.Product(cb2);
				
					mat1[i][j] = prod.ConvertBspCurv().Integrate((*kts)[ord-1],(*kts)[num-ord]);
				}
			}
		}
	
	
	
	return mat1;
}
예제 #26
0
int test()
{
#ifdef CH_USE_HDF5

  int error;
  HDF5Handle testFile;

  CH_assert(!testFile.isOpen());

  error = testFile.open("data.h5", HDF5Handle::CREATE);
  if (error != 0)
    {
      if ( verbose )
        pout() << indent2 << "File creation failed "<<error<<endl;
      return error;
    }

  CH_assert(testFile.isOpen());

  Box domain(IntVect::Zero, 20*IntVect::Unit);

  DisjointBoxLayout plan1, plan2;
  {
    IntVectSet tags;

    IntVect center = 10*IntVect::Unit;

    setCircleTags(tags, 6, 1, center); //circle/sphere

    buildDisjointBoxLayout(plan1, tags, domain);

    tags.makeEmpty();

    setCircleTags(tags, 5, 2, center);

    buildDisjointBoxLayout(plan2, tags, domain);
  }
  if ( verbose )
  {
    pout() << "plan1: " << procID() << "...." << plan1 << endl;
    pout() << "plan2: " << procID() << "...." << plan2 << endl;
  }

  //test LayoutData<Real> specialization
  LayoutData<Real>  specialReal(plan1);


  LayoutData<Moment>   vlPlan(plan1);


  LevelData<BaseFab<int> > level1(plan1, 3, IntVect::Unit);

  LevelData<BaseFab<int> > level2;

  level2.define(level1);

  level2.define(plan2, 1);

  for (DataIterator i(level2.dataIterator()); i.ok(); ++i)
  {
    level2[i()].setVal(2);
  }

  level1.apply(values::setVal1);

  level2.apply(values::setVal2);

  HDF5HeaderData set1;
  Real dx=0.004;
  Box b1(IntVect(D_DECL6(1,2,1,1,2,1)), IntVect(D_DECL6(4,4,4,4,4,4)));
  Box b2(IntVect(D_DECL6(5,2,1,5,2,1)), IntVect(D_DECL6(12,4,4,12,4,4)));
  int currentStep = 2332;

  set1.m_string["name"] = "set1";
  set1.m_real["dx"] = dx;
  set1.m_int["currentStep"] = currentStep;
  set1.m_intvect["some intvect or other"] = b1.smallEnd();
  set1.m_box["b1"] = b1;
  set1.m_box["b2"] = b2;

  testFile.setGroupToLevel(1);

  error = write(testFile, plan1);
  if (error != 0)
    {
      if ( verbose )
        pout() << indent2 << "box write failed "<<error<<endl;
      return error;
    }

  error = write(testFile, level1, "level1 state vector");
  if (error != 0)
    {
      if ( verbose )
        pout() << indent2 << "BoxLayoutData 1 write failed "<<error<<endl;
      return error;
    }

  testFile.setGroupToLevel(2);

  error = write(testFile, plan2);
  if (error != 0)
    {
      if ( verbose )
        pout() << indent2 << "box2 write failed "<<error<<endl;
      return error;
    }

  error = write(testFile, level2, "level2 state vector");
  if (error != 0)
    {
      if ( verbose )
        pout() << indent2 << "BoxLayoutData 2 write failed "<<error<<endl;
      return error;
    }

  LevelData<FArrayBox> state(plan2, 3);

  state.apply(values::setVal3);
  testFile.setGroupToLevel(0);
  set1.writeToFile(testFile);

  error = write(testFile, plan2);
  if (error != 0)
    {
      if ( verbose )
        pout() << indent2 << "box2 write failed "<<error<<endl;
      return error;
    }

  testFile.setGroup("/");

  error = writeLevel(testFile, 0, state, 2, 1, 0.001, b2, 2);
  if (error != 0)
    {
      if ( verbose )
        pout() << indent2 << "BoxLayoutData 2 write failed "<<error<<endl;
      return error;
    }

  set1.writeToFile(testFile);
  set1.writeToFile(testFile);

  testFile.close();

 CH_assert(!testFile.isOpen());

  // test the utility functions ReadUGHDF5 and WriteUGHDF5

  WriteUGHDF5("UGIO.hdf5", plan2, state, domain);

  ReadUGHDF5("UGIO.hdf5", plan2, state, domain);
  //========================================================================
  //
  //  now, read this data back in
  //
  //========================================================================

  BoxLayoutData<BaseFab<int> > readlevel1, readlevel2;

  error = testFile.open("data.h5", HDF5Handle::OPEN_RDONLY);
  if (error != 0)
    {
      if ( verbose )
        pout() << indent2 << "File open failed "<<error<<endl;
      return error;
    }

  testFile.setGroupToLevel(2);
  Vector<Box> boxes;
  error = read(testFile, boxes);

  if (error != 0)
    {
      if ( verbose )
        pout() << indent2 << "box read failed "<<error<<endl;
      return error;
    }
  boxes.sort();
  Vector<int> assign;
  error = LoadBalance(assign, boxes);
  if (error != 0)
    {
      if ( verbose )
        pout() << indent2 << "BoxLayout LoadBalance failed "<<error<<endl;
      return error;
    }
  BoxLayout readplan2(boxes, assign);
  readplan2.close();
  error = read(testFile, readlevel2, "level2 state vector", readplan2);
  if (error != 0)
    {
      if ( verbose )
        pout() << indent2 << "BoxLayoutData<BaseFab<int>> read failed "<<error<<endl;
      return error;
    }

  testFile.setGroupToLevel(1);
  error = read(testFile, boxes);
  if (error != 0)
    {
      if ( verbose )
        pout() << indent2 << "box read failed "<<error<<endl;
      return error;
    }

  error = LoadBalance(assign, boxes);
  if (error != 0)
    {
      if ( verbose )
        pout() << indent2 << "BoxLayout LoadBalance failed "<<error<<endl;
      return error;
    }
  BoxLayout readplan1(boxes, assign);
  readplan1.close();
  if ( verbose )
  {
    pout() << "readplan1: " << procID() << "...." << readplan1 << endl;
    pout() << "readplan2: " << procID() << "...." << readplan2 << endl;
  }
  error = read(testFile, readlevel1, "level1 state vector", readplan1);
  if (error != 0)
    {
      if ( verbose )
        pout() << indent2 << "BoxLayoutData<BaseFab<int>> read failed "<<error<<endl;
      return error;
    }

  if ( verbose )
    pout() << plan1<<readplan1<<endl;

  // real test of IO, make sure the data is the same coming and going

  DataIterator l1  = level1.dataIterator();
  DataIterator rl1 = readlevel1.dataIterator();
  DataIterator l2  = level2.dataIterator();
  DataIterator rl2 = readlevel2.dataIterator();

  if (level1.boxLayout().size() != readlevel1.boxLayout().size())
    {
      if ( verbose )
        pout() << indent2 << "level1.size() != readl1.size() read failed "<<error<<endl;
      return 1;
    }
  if (level2.boxLayout().size() != readlevel2.boxLayout().size())
    {
      if ( verbose )
        pout() << indent2 << "level2.size() != readl2.size() read failed "<<error<<endl;
      return 1;
    }

  // we can assume that BoxLayout IO is tested in HDF5boxIO
  BaseFab<int>* before, *after;
  for (; l1.ok(); ++l1, ++rl1)
    {

      before = &(level1[l1()]); after = &(readlevel1[rl1()]);
      for (int c=0; c<before->nComp(); ++c)
        {
          for (BoxIterator it(level1.box(l1())); it.ok(); ++it)
            {
              if ((*before)(it(), c) != (*after)(it(), c))
                {
                  if ( verbose )
                    pout() << indent2 << "l1 != readl1 read failed "<<error<<endl;
                  return 2;
                }
            }
        }
    }

  for (; l2.ok(); ++l2, ++rl2)
    {

      before = &(level2[l2()]); after = &(readlevel2[rl2()]);
      for (int c=0; c<before->nComp(); ++c)
        {
          for (BoxIterator it(level2.box(l2())); it.ok(); ++it)
            {
              if ((*before)(it(), c) != (*after)(it(), c))
                {
                  if ( verbose )
                    pout() << indent2 << "level2 != readlevel2 read failed "<<error<<endl;
                  return 3;
                }
            }
        }
    }

  LevelData<FArrayBox> readState;
  Real dt, time;
  int refRatio;

  testFile.setGroup("/");

  error = readLevel(testFile, 0, readState, dx, dt, time, b2, refRatio);
  if (error != 0)
    {
      if ( verbose )
        pout() << indent2 << "readLevel failed "<<error<<endl;
      return error;
    }

#ifndef CH_MPI
  // OK, now try to read one FArrayBox at a time
  // problem with DataIterator and running the out-of-core in parallel, so
  // have to think about that for now  BVS.
  FArrayBox readFAB;
  Interval  interval(1,2);
  testFile.setGroup("/");
  int index=0;
  for (DataIterator dit(state.dataIterator()); dit.ok(); ++index,++dit)
        {
          FArrayBox& fab = state[dit()];
          readFArrayBox(testFile, readFAB, 0, index, interval);
          for (BoxIterator it(state.box(dit())) ; it.ok() ; ++it)
                {
                  if (readFAB(it(), 0) != fab(it(), 1))
                        {
                          if ( verbose )
                                pout() << indent2 << "state != after for out-of-core "<<error<<endl;
                          return 3;
                        }
                }
        }

#endif

  testFile.close();

 CH_assert(!testFile.isOpen());

#endif // CH_USE_HDF5

  return 0;
}
void AP_UnixDialog_Lists::loadXPDataIntoLocal(void)
{
	//
	// This function reads the various memeber variables and loads them into
	// into the dialog variables.
	//

  //
  // Block all signals while setting these things
  //
	XAP_GtkSignalBlocker b1(  G_OBJECT(m_oAlignList_adj), m_iAlignListSpinID);
	XAP_GtkSignalBlocker b2(  G_OBJECT(m_oIndentAlign_adj), m_iIndentAlignSpinID);

	XAP_GtkSignalBlocker b3(  G_OBJECT(m_wDecimalEntry), m_iDecimalEntryID);
	XAP_GtkSignalBlocker b4(  G_OBJECT(m_wDelimEntry), m_iDelimEntryID );
	//
	// HACK to effectively block an update during this method
	//
	m_bDontUpdate = true;

	UT_DEBUGMSG(("loadXP newListType = %d \n",getNewListType()));
	gtk_spin_button_set_value(GTK_SPIN_BUTTON(m_wAlignListSpin),getfAlign());
	float indent = getfAlign() + getfIndent();
	gtk_spin_button_set_value(GTK_SPIN_BUTTON( m_wIndentAlignSpin),indent);
	if( (getfIndent() + getfAlign()) < 0.0)
	{
		setfIndent( - getfAlign());
		gtk_spin_button_set_value(GTK_SPIN_BUTTON( m_wIndentAlignSpin), 0.0);

	}
	//
	// Code to work out which is active Font
	//
	if(getFont() == "NULL")
	{
		gtk_combo_box_set_active(m_wFontOptions, 0 );
	}
	else
	{
        size_t i = 0;
		for(std::vector<std::string>::const_iterator iter = m_glFonts.begin();
            iter != m_glFonts.end(); ++iter, ++i)
		{
			if(*iter == getFont())
				break;
		}
        if(i < m_glFonts.size())
		{
			gtk_combo_box_set_active(m_wFontOptions, i + 1 );
		}
		else
		{
			gtk_combo_box_set_active(m_wFontOptions, 0 );
		}
	}
	gtk_spin_button_set_value(GTK_SPIN_BUTTON(m_wStartSpin),static_cast<float>(getiStartValue()));

    gtk_entry_set_text( GTK_ENTRY(m_wDecimalEntry), getDecimal().c_str());
	gtk_entry_set_text( GTK_ENTRY(m_wDelimEntry), getDelim().c_str());

	//
	// Now set the list type and style
	FL_ListType save = getNewListType();
	if(getNewListType() == NOT_A_LIST)
	{
		styleChanged(0);
		setNewListType(save);
		gtk_combo_box_set_active(m_wListTypeBox, 0);
		gtk_combo_box_set_active(m_wListStyleBox, 0);
	}
	else if(IS_BULLETED_LIST_TYPE(getNewListType()) )
	{
		styleChanged(1);
		setNewListType(save);
		gtk_combo_box_set_active(m_wListTypeBox, 1);
		gtk_combo_box_set_active(m_wListStyleBox, (gint) (getNewListType() - BULLETED_LIST));
	}
	else
	{
		styleChanged(2);
	    setNewListType(save);
		gtk_combo_box_set_active(m_wListTypeBox, 2);
		if(getNewListType() < OTHER_NUMBERED_LISTS)
		{
			gtk_combo_box_set_active(m_wListStyleBox, getNewListType());
		}
		else
		{
		    gint iMenu = static_cast<gint>(getNewListType()) - OTHER_NUMBERED_LISTS + BULLETED_LIST -1 ;
			gtk_combo_box_set_active(m_wListStyleBox,iMenu);
		}
	}

	//
	// HACK to allow an update during this method
	//
	m_bDontUpdate = false;
}
예제 #28
0
void PrintVirutalFucAddr()
{
	B1 b1(1), b2(2); D1 d1(3), d2(4);
	B1 * pd1 = &d1, * pd2 = &d2;
	cout << "b1对象地址:" << &b1 << endl;
	cout << "b2对象地址:" << &b2 << endl;
	cout << "d1对象地址:" << &d1 << endl;
	cout << "d2对象地址:" << &d2 << endl;
	cout << "pd1对象地址:" << pd1 << endl;
	cout << "pd2对象地址:" << pd2 << endl;
	cout << "b1虚函数表地址:" << (int*)*(int*)(&b1) << endl;
	cout << "b2虚函数表地址:" << (int*)*(int*)(&b2) << endl;
	cout << "d1虚函数表地址:" << (int*)*(int*)(&d1) << endl;
	cout << "d2虚函数表地址:" << (int*)*(int*)(&d2) << endl;
	cout << "pd1虚函数表地址:" << (int*)*(int*)(pd1) << endl;
	cout << "pd2虚函数表地址:" << (int*)*(int*)(pd2) << endl;
	cout << "b1虚函数表  — 第一个函数地址:" << (int*)*((int*)*(int*)(&b1) + 0) << endl;
	cout << "b2虚函数表  — 第一个函数地址:" << (int*)*((int*)*(int*)(&b2) + 0) << endl;
	cout << "d1虚函数表  — 第一个函数地址:" << (int*)*((int*)*(int*)(&d1) + 0) << endl;
	cout << "d2虚函数表  — 第一个函数地址:" << (int*)*((int*)*(int*)(&d2) + 0) << endl;
	cout << "pd1虚函数表 — 第一个函数地址:" << (int*)*((int*)*(int*)(pd1) + 0) << endl;
	cout << "pd2虚函数表 — 第一个函数地址:" << (int*)*((int*)*(int*)(pd2) + 0) << endl;
	cout << "b1虚函数表  — 第二个函数地址:" << (int*)*((int*)*(int*)(&b1) + 1) << endl;
	cout << "b2虚函数表  — 第二个函数地址:" << (int*)*((int*)*(int*)(&b2) + 1) << endl;
	cout << "d1虚函数表  — 第二个函数地址:" << (int*)*((int*)*(int*)(&d1) + 1) << endl;
	cout << "d2虚函数表  — 第二个函数地址:" << (int*)*((int*)*(int*)(&d2) + 1) << endl;
	cout << "pd1虚函数表 — 第二个函数地址:" << (int*)*((int*)*(int*)(pd1) + 1) << endl;
	cout << "pd2虚函数表 — 第二个函数地址:" << (int*)*((int*)*(int*)(pd2) + 1) << endl;

	
	typedef void (*VFUN)(void);

	cout << "b1 与 d1 执行第一个函数地址" << endl;
	VFUN pv1 = (VFUN)*((int*)*(int*)(&b1));
	VFUN pv2 = (VFUN)*((int*)*(int*)(&d1));
	pv1();
	pv2();
	cout << "b1 与 d1 执行第二个函数地址" << endl;
	pv1 = (VFUN)*((int*)*(int*)(&b1) + 1);
	pv2 = (VFUN)*((int*)*(int*)(&d1) + 1);
	pv1();
	pv2();
	cout << "b1 与 d1 执行第四个函数地址" << endl;
	pv1 = (VFUN)*((int*)*(int*)(&b1) + 3);
	pv2 = (VFUN)*((int*)*(int*)(&d1) + 3);
	//pv1(); error
	//pv2(); error
	typedef void (*VFUN2)(B1*);
	VFUN2 pv3 = (VFUN2)*((int*)*(int*)(&b1) + 3);
	VFUN2 pv4 = (VFUN2)*((int*)*(int*)(&d1) + 3);
	pv3(&b1);
	pv4(&d1);
	
	
	cout << "sizeof(int*): " << sizeof(int*) << endl;
	cout << "sizeof(double): " << sizeof(double) << endl;
	cout << "sizeof(float): " << sizeof(float) << endl;
	cout << "sizeof(unsigned long): " << sizeof(unsigned long) << endl;
	cout << "sizeof(long): " << sizeof(long) << endl;
	cout << "sizeof(unsigned int): " << sizeof(unsigned int) << endl;
	cout << "sizeof(int): " << sizeof(int) << endl;
	cout << "sizeof(unsigned short): " << sizeof(unsigned short) << endl;
	cout << "sizeof(short): " << sizeof(short) << endl;
}
예제 #29
0
파일: main.cpp 프로젝트: phelrine/NBTools
//=============================================================================
int main(int argc, char** argv)
{
  ///////////////////////////////////////////////
  //////////////// set precision ////////////////
  ///////////////////////////////////////////////
  std::cout.precision(9);
  std::cout.setf(std::ios::scientific, std::ios::floatfield);
  std::cout.setf(std::ios::showpos);
  std::cerr.precision(3);
  std::cerr.setf(std::ios::scientific, std::ios::floatfield);
  std::cerr.setf(std::ios::showpos);
  
  ///////////////////////////////////////////////
  //////////////////// A,b //////////////////////
  ///////////////////////////////////////////////
  CPPL::dgsmatrix A;
  CPPL::dcovector b;
  //const bool file =true;
  const bool file =false;
  ///////////////////////////
  ////////// read ///////////
  ///////////////////////////
  if(file){
    A.read("A8.dge");  b.read("b8.dco");
    //A.read("A10.dge");  b.read("b10.dco");
    //A.read("A44.dge"); b.read("b44.dco");
  }
  ///////////////////////////
  ///////// random //////////
  ///////////////////////////
  else{//file==false
    std::cerr << "# making random matrix" << std::endl;
    const int size(1000);
    A.resize(size,size);
    b.resize(size);
    srand(time(NULL));
    for(int i=0; i<size; i++){
      for(int j=0; j<size; j++){
        if( rand()%5==0 ){
          A(i,j) =(double(rand())/double(RAND_MAX))*2.0 -1.0;
        }
      }
      A(i,i) +=1e-2*double(size);//generalization
      b(i) =(double(rand())/double(RAND_MAX))*1. -0.5;
    }
    A.write("A.dge");
    b.write("b.dco");
  }

  ///////////////////////////////////////////////
  ////////////////// direct /////////////////////
  ///////////////////////////////////////////////
  std::cerr << "# making solution with dgesv" << std::endl;
  CPPL::dgematrix A2(A.to_dgematrix());
  CPPL::dcovector b2(b);
  A2.dgesv(b2);
  b2.write("ans.dco");
  
  ///////////////////////////////////////////////
  ///////////////// iterative ///////////////////
  ///////////////////////////////////////////////
  //////// initial x ////////
  CPPL::dcovector x(b.l);
  //x.read("x_ini8.dco");
  x.zero();
  //////// eps ////////
  double eps(fabs(damax(b))*1e-6);
  std::cerr << "eps=" << eps << std::endl;
  //////// solve ////////
  if( gmres(A, b, x, eps) ){
    std::cerr << "failed." << std::endl;
    x.write("x.dco");
    exit(1);
  }
  x.write("x.dco");
  std::cerr << "fabs(damax(err))=" << fabs(damax(b2-x)) << std::endl;
  
  return 0;
}
예제 #30
0
파일: fitTF1Self.C 프로젝트: UAEDF/vbfHbb
void fitTF1(TCanvas *canvas, TH1F h, double XMIN_, double XMAX_, double dX_, double params[], Color_t LC_=kBlack) { //double& FWHM_, double& x0_, double& x1_, double& x2_, double& y0_, double& y1_, double& INT_, double& YIELD_) {
//TCanvas* fitTF1(TH1F h, double HSCALE_, double XMIN_, double XMAX_) {
//TF1* fitTF1(TH1F h, double HSCALE_, double XMIN_, double XMAX_) {
	gROOT->ForceStyle();
	RooMsgService::instance().setSilentMode(kTRUE);
	for(int i=0;i<2;i++) RooMsgService::instance().setStreamStatus(i,kFALSE);

	//TCanvas *canvas = new TCanvas(TString::Format("canvas_%s",h.GetName()),TString::Format("canvas_%s",h.GetName()),1800,1200);

	RooDataHist *RooHistFit = 0;
	RooAddPdf *model = 0;

	RooWorkspace w = RooWorkspace("w","workspace");

	RooRealVar x("mbbReg","mbbReg",XMIN_,XMAX_);
	RooRealVar kJES("CMS_scale_j","CMS_scale_j",1,0.9,1.1);
	RooRealVar kJER("CMS_res_j","CMS_res_j",1,0.8,1.2);
	kJES.setConstant(kTRUE);
	kJER.setConstant(kTRUE);

	TString hname = h.GetName();

	RooHistFit = new RooDataHist("fit_"+hname,"fit_"+hname,x,&h);


	RooRealVar YieldVBF = RooRealVar("yield_"+hname,"yield_"+hname,h.Integral());
	RooRealVar m("mean_"+hname,"mean_"+hname,125,100,150);
	RooRealVar s("sigma_"+hname,"sigma_"+hname,12,3,30);
	RooFormulaVar mShift("mShift_"+hname,"@0*@1",RooArgList(m,kJES));
	RooFormulaVar sShift("sShift_"+hname,"@0*@1",RooArgList(m,kJER));
	RooRealVar a("alpha_"+hname,"alpha_"+hname,1,-10,10);
	RooRealVar n("exp_"+hname,"exp_"+hname,1,0,100);
	RooRealVar b0("b0_"+hname,"b0_"+hname,0.5,0.,1.);
	RooRealVar b1("b1_"+hname,"b1_"+hname,0.5,0.,1.);
	RooRealVar b2("b2_"+hname,"b2_"+hname,0.5,0.,1.);
	RooRealVar b3("b3_"+hname,"b3_"+hname,0.5,0.,1.);
	
	RooBernstein bkg("signal_bkg_"+hname,"signal_bkg_"+hname,x,RooArgSet(b0,b1,b2));
	RooRealVar fsig("fsig_"+hname,"fsig_"+hname,0.7,0.0,1.0);
	RooCBShape sig("signal_gauss_"+hname,"signal_gauss_"+hname,x,mShift,sShift,a,n);

	model = new RooAddPdf("signal_model_"+hname,"signal_model_"+hname,RooArgList(sig,bkg),fsig);

	//RooFitResult *res = model->fitTo(*RooHistFit,RooFit::Save(),RooFit::SumW2Error(kFALSE),"q");
	model->fitTo(*RooHistFit,RooFit::Save(),RooFit::SumW2Error(kFALSE),"q");

	//res->Print();
	//model->Print();
	
	canvas->cd();
	canvas->SetTopMargin(0.1);
	RooPlot *frame = x.frame();
// no scale
	RooHistFit->plotOn(frame);
	model->plotOn(frame,RooFit::LineColor(LC_),RooFit::LineWidth(2));//,RooFit::LineStyle(kDotted));
	model->plotOn(frame,RooFit::Components(bkg),RooFit::LineColor(LC_),RooFit::LineWidth(2),RooFit::LineStyle(kDashed));
// with scale
//	RooHistFit->plotOn(frame,RooFit::Normalization(HSCALE_,RooAbsReal::NumEvent));
//	model->plotOn(frame,RooFit::Normalization(HSCALE_,RooAbsReal::NumEvent),RooFit::LineWidth(1));
//	model->plotOn(frame,RooFit::Components(bkg),RooFit::LineColor(kBlue),RooFit::LineWidth(1),RooFit::LineStyle(kDashed),RooFit::Normalization(HSCALE_,RooAbsReal::NumEvent));
	 
	frame->GetXaxis()->SetLimits(50,200);
	frame->GetXaxis()->SetNdivisions(505);
	frame->GetXaxis()->SetTitle("M_{b#bar{b}} (GeV)");
	frame->GetYaxis()->SetTitle("Events");
	frame->Draw();
	h.SetFillColor(kGray);
	h.Draw("hist,same");
	frame->Draw("same");
	gPad->RedrawAxis();

	TF1 *tmp = model->asTF(x,fsig,x);
	//tmp->Print();

	double y0_ = tmp->GetMaximum();
	double x0_ = tmp->GetMaximumX();
	double x1_ = tmp->GetX(y0_/2.,XMIN_,x0_);
	double x2_ = tmp->GetX(y0_/2.,x0_,XMAX_);
	double FWHM_ = x2_-x1_;
	double INT_ = tmp->Integral(XMIN_,XMAX_);
	double YIELD_= YieldVBF.getVal();
	double y1_ = dX_*0.5*y0_*(YieldVBF.getVal()/tmp->Integral(XMIN_,XMAX_));

	params[0] = x0_;
	params[1] = x1_;
	params[2] = x2_;
	params[3] = y0_;
	params[4] = y1_;
	params[5] = FWHM_;
	params[6] = INT_;
	params[7] = YIELD_;

	//cout<<"Int = "<<tmp->Integral(XMIN_,XMAX_)<<", Yield = "<<YieldVBF.getVal()<<", y0 = "<<y0_<<", y1 = "<<y1_ <<", x0 = "<< x0_ << ", x1 = "<<x1_<<", x2 = "<<x2_<<", FWHM = "<<FWHM_<<endl;

	TLine ln = TLine(x1_,y1_,x2_,y1_);
	ln.SetLineColor(kMagenta+3);
	ln.SetLineStyle(7);
	ln.SetLineWidth(2);
	ln.Draw();
	
	canvas->Update();
	canvas->SaveAs("testC.png");
	
//	tmp->Delete();
//	frame->Delete();
//	res->Delete();
//	TF1 *f1 = model->asTF(x,fsig,x);
//	return f1;
	
	////tmp->Delete();
	////ln->Delete();
	////model->Delete();
	////RooHistFit->Delete();
	////w->Delete();
	////YieldVBF->Delete();
	////frame->Delete();
	////res->Delete();
	//delete tmp;
	//delete ln;
	//delete model;
	//delete RooHistFit;
	//delete w;
	//delete YieldVBF;
	//delete frame;
	//delete res;

//	return canvas;
}