void CollisionPolygon2D::_notification(int p_what) {


	switch(p_what) {
		case NOTIFICATION_ENTER_TREE: {
			unparenting=false;
			can_update_body=get_tree()->is_editor_hint();
			if (!get_tree()->is_editor_hint()) {
				//display above all else
				set_z_as_relative(false);
				set_z(VS::CANVAS_ITEM_Z_MAX-1);
			}

		} break;
		case NOTIFICATION_EXIT_TREE: {
			can_update_body=false;
		} break;
		case NOTIFICATION_LOCAL_TRANSFORM_CHANGED: {

			if (!is_inside_tree())
				break;
			if (can_update_body) {
				_update_parent();
			} else if (shape_from>=0 && shape_to>=0) {
				CollisionObject2D *co = get_parent()->cast_to<CollisionObject2D>();
				for(int i=shape_from;i<=shape_to;i++) {
					co->set_shape_transform(i,get_transform());
				}
			}


		} break;

		case NOTIFICATION_DRAW: {

			if (!get_tree()->is_editor_hint() && !get_tree()->is_debugging_collisions_hint()) {
				break;
			}


			for(int i=0;i<polygon.size();i++) {

				Vector2 p = polygon[i];
				Vector2 n = polygon[(i+1)%polygon.size()];
				draw_line(p,n,Color(0.9,0.2,0.0,0.8),3);
			}
#define DEBUG_DECOMPOSE
#if defined(TOOLS_ENABLED) && defined (DEBUG_DECOMPOSE)

			Vector< Vector<Vector2> > decomp = _decompose_in_convex();

			Color c(0.4,0.9,0.1);
			for(int i=0;i<decomp.size();i++) {

				c.set_hsv( Math::fmod(c.get_h() + 0.738,1),c.get_s(),c.get_v(),0.5);
				draw_colored_polygon(decomp[i],c);
			}
#else
			draw_colored_polygon(polygon,get_tree()->get_debug_collisions_color());
#endif


		} break;
		case NOTIFICATION_UNPARENTED: {
			unparenting = true;
			_update_parent();
		} break;

	}
}
Exemplo n.º 2
0
void ZZ_pE::init(const ZZ_pX& p)
{
   ZZ_pEContext c(p);
   c.restore();
}
Exemplo n.º 3
0
Node *Best3OptMove(Node * t1, Node * t2, GainType * G0, GainType * Gain)
{
    Node *t3, *t4, *t5, *t6, *T3 = 0, *T4 = 0, *T5 = 0, *T6 = 0;
    Candidate *Nt2, *Nt4;
    GainType G1, G2, G3, G4, BestG4 = MINUS_INFINITY;
    int Case6, BestCase6 = 0, X4, X6;
    int Breadth2 = 0, Breadth4;

    if (SUC(t1) != t2)
        Reversed ^= 1;

    /* 
     * Determine (T3,T4,T5,T6) = (t3,t4,t5,t6)
     * such that 
     *
     *     G4 = *G0 - C(t2,T3) + C(T3,T4) 
     *              - C(T4,T5) + C(T5,T6)
     *
     * is maximum (= BestG4), and (T5,T6) has not previously been included.
     * If during this process a legal move with *Gain > 0 is found, then make
     * the move and exit Best3OptMove immediately. 
     */

    /* Choose (t2,t3) as a candidate edge emanating from t2 */
    for (Nt2 = t2->CandidateSet; (t3 = Nt2->To); Nt2++) {
        if (t3 == t2->Pred || t3 == t2->Suc ||
            ((G1 = *G0 - Nt2->Cost) <= 0 && GainCriterionUsed &&
             ProblemType != HCP && ProblemType != HPP))
            continue;
        if (++Breadth2 > MaxBreadth)
            break;
        /* Choose t4 as one of t3's two neighbors on the tour */
        for (X4 = ProblemType == ATSP ? 2 : 1; X4 <= 2; X4++) {
            t4 = X4 == 1 ? PRED(t3) : SUC(t3);
            if (FixedOrCommon(t3, t4))
                continue;
            G2 = G1 + C(t3, t4);
            if (X4 == 1 && !Forbidden(t4, t1) &&
                (!c || G2 - c(t4, t1) > 0) && (*Gain = G2 - C(t4, t1)) > 0)
            {
                Swap1(t1, t2, t3);
                return 0;
            }
            if (Backtracking && !Excludable(t3, t4))
                continue;
            Breadth4 = 0;
            /* Choose (t4,t5) as a candidate edge emanating from t4 */
            for (Nt4 = t4->CandidateSet; (t5 = Nt4->To); Nt4++) {
                if (t5 == t4->Pred || t5 == t4->Suc ||
                    ((G3 = G2 - Nt4->Cost) <= 0 && GainCriterionUsed &&
                     ProblemType != HCP && ProblemType != HPP) ||
                    (X4 == 2 && !BETWEEN(t2, t5, t3)))
                    continue;
                if (++Breadth4 > MaxBreadth)
                    break;
                /* Choose t6 as one of t5's two neighbors on the tour */
                for (X6 = 1; X6 <= X4; X6++) {
                    if (X4 == 1) {
                        Case6 = 1 + !BETWEEN(t2, t5, t4);
                        t6 = Case6 == 1 ? SUC(t5) : PRED(t5);
                    } else {
                        Case6 = 4 + X6;
                        t6 = X6 == 1 ? SUC(t5) : PRED(t5);
                        if (t6 == t1)
                            continue;
                    }
                    if (FixedOrCommon(t5, t6))
                        continue;
                    G4 = G3 + C(t5, t6);
                    if (!Forbidden(t6, t1) &&
                        (!c || G4 - c(t6, t1) > 0) &&
                        (*Gain = G4 - C(t6, t1)) > 0) {
                        Make3OptMove(t1, t2, t3, t4, t5, t6, Case6);
                        return 0;
                    }
                    if (GainCriterionUsed && G4 - Precision < t6->Cost)
                        continue;
                    if (!Backtracking || Swaps > 0) {
                        if ((G4 > BestG4 ||
                             (G4 == BestG4 && !Near(t5, t6) &&
                              Near(T5, T6))) &&
                            Swaps < MaxSwaps &&
                            Excludable(t5, t6) && !InInputTour(t5, t6)) {
                            /* Ignore the move if the gain does not vary */
                            if (RestrictedSearch &&
                                ProblemType != HCP &&
                                ProblemType != HPP &&
                                G2 - t4->Pi == G4 - t6->Pi &&
                                G3 + t5->Pi == G1 + t3->Pi)
                                continue;
                            T3 = t3;
                            T4 = t4;
                            T5 = t5;
                            T6 = t6;
                            BestCase6 = Case6;
                            BestG4 = G4;
                        }
                    } else if (MaxSwaps > 0) {
                        GainType G = G4;
                        Node *t = t6;
                        Make3OptMove(t1, t2, t3, t4, t5, t6, Case6);
                        Exclude(t1, t2);
                        Exclude(t3, t4);
                        Exclude(t5, t6);
                        while ((t = BestSubsequentMove(t1, t, &G, Gain)));
                        if (*Gain > 0)
                            return 0;
                        RestoreTour();
                        if (t2 != SUC(t1))
                            Reversed ^= 1;
                    }
                }
            }
        }
    }
    *Gain = 0;
    if (T6) {
        /* Make the best 3-opt move */
        Make3OptMove(t1, t2, T3, T4, T5, T6, BestCase6);
        Exclude(t1, t2);
        Exclude(T3, T4);
        Exclude(T5, T6);
        *G0 = BestG4;
    }
    return T6;
}
Exemplo n.º 4
0
void ForwardMouseEvent(const QMouseEvent* e, QWidget* target) {
  QMouseEvent c(e->type(), target->mapFromGlobal(e->globalPos()),
                e->globalPos(), e->button(), e->buttons(), e->modifiers());

  QApplication::sendEvent(target, &c);
}
Exemplo n.º 5
0
void FlatTextarea::processDocumentContentsChange(int position, int charsAdded) {
	int32 emojiPosition = 0, emojiLen = 0;
	const EmojiData *emoji = 0;

	QTextDocument *doc(document());

	while (true) {
		int32 start = position, end = position + charsAdded;
		QTextBlock from = doc->findBlock(start), till = doc->findBlock(end);
		if (till.isValid()) till = till.next();

		for (QTextBlock b = from; b != till; b = b.next()) {
			for (QTextBlock::Iterator iter = b.begin(); !iter.atEnd(); ++iter) {
				QTextFragment fragment(iter.fragment());
				if (!fragment.isValid()) continue;

				int32 fp = fragment.position(), fe = fp + fragment.length();
				if (fp >= end || fe <= start) {
					continue;
				}

				QString t(fragment.text());
				const QChar *ch = t.constData(), *e = ch + t.size();
				for (; ch != e; ++ch) {
					emoji = emojiFromText(ch, e, emojiLen);
					if (emoji) {
						emojiPosition = fp + (ch - t.constData());
						break;
					}
					if (ch + 1 < e && ch->isHighSurrogate() && (ch + 1)->isLowSurrogate()) ++ch;
				}
				if (emoji) break;
			}
			if (emoji) break;
		}
		if (emoji) {
			QTextCursor c(doc->docHandle(), emojiPosition);
			c.setPosition(emojiPosition + emojiLen, QTextCursor::KeepAnchor);
			int32 removedUpto = c.position();

			insertEmoji(emoji, c);

			for (Insertions::iterator i = _insertions.begin(), e = _insertions.end(); i != e; ++i) {
				if (i->first >= removedUpto) {
					i->first -= removedUpto - emojiPosition - 1;
				} else if (i->first >= emojiPosition) {
					i->second -= removedUpto - emojiPosition;
					i->first = emojiPosition + 1;
				} else if (i->first + i->second > emojiPosition + 1) {
					i->second -= qMin(removedUpto, i->first + i->second) - emojiPosition;
				}
			}

			charsAdded -= removedUpto - position;
			position = emojiPosition + 1;

			emoji = 0;
			emojiPosition = 0;
		} else {
			break;
		}
	}
}
Exemplo n.º 6
0
	void load(Common::ReadStream &input) {
		Common::IFFParser parser(&input);
		Common::Functor1Mem< Common::IFFChunk&, bool, A8SVXLoader > c(this, &A8SVXLoader::callback);
		parser.parse(c);
	}
Exemplo n.º 7
0
// Vector3 methods
Vector3 Vector3::cross(Vector3 b) //return this cross b
{
    Vector3 c(y*b.z - z*b.y, z*b.x - x*b.z, x*b.y - y*b.x);
    return c;
}
Exemplo n.º 8
0
void BenchmarkAll(double t)
{
#if 1
	logtotal = 0;
	logcount = 0;

	cout << "<TABLE border=1><COLGROUP><COL align=left><COL align=right><COL align=right><COL align=right>" << endl;
	cout << "<THEAD><TR><TH>Algorithm<TH>Megabytes(2^20 bytes) Processed<TH>Time Taken<TH>MB/Second\n<TBODY>" << endl;

	BenchMarkKeyless<CRC32>("CRC-32", t);
	BenchMarkKeyless<Adler32>("Adler-32", t);
	BenchMarkKeyless<MD2>("MD2", t);
	BenchMarkKeyless<MD5>("MD5", t);
	BenchMarkKeyless<SHA>("SHA-1", t);
	BenchMarkKeyless<SHA256>("SHA-256", t);
#ifdef WORD64_AVAILABLE
	BenchMarkKeyless<SHA512>("SHA-512", t);
#endif
	BenchMarkKeyless<HAVAL3>("HAVAL (pass=3)", t);
	BenchMarkKeyless<HAVAL4>("HAVAL (pass=4)", t);
	BenchMarkKeyless<HAVAL5>("HAVAL (pass=5)", t);
#ifdef WORD64_AVAILABLE
	BenchMarkKeyless<Tiger>("Tiger", t);
#endif
	BenchMarkKeyless<RIPEMD160>("RIPE-MD160", t);
	BenchMarkKeyless<PanamaHash<LittleEndian> >("Panama Hash (little endian)", t);
	BenchMarkKeyless<PanamaHash<BigEndian> >("Panama Hash (big endian)", t);
#ifdef WORD64_AVAILABLE
	BenchMarkKeyless<Whirlpool>("Whirlpool", t);
#endif
	BenchMarkKeyed<MDC<MD5>::Encryption>("MDC/MD5", t);
	BenchMarkKeyed<LR<MD5>::Encryption>("Luby-Rackoff/MD5", t);
	BenchMarkKeyed<DES::Encryption>("DES", t);
	BenchMarkKeyed<DES_XEX3::Encryption>("DES-XEX3", t);
	BenchMarkKeyed<DES_EDE3::Encryption>("DES-EDE3", t);
	BenchMarkKeyed<IDEA::Encryption>("IDEA", t);
	BenchMarkKeyed<RC2::Encryption>("RC2", t);
	BenchMarkKeyed<RC5::Encryption>("RC5 (r=16)", t);
	BenchMarkKeyed<Blowfish::Encryption>("Blowfish", t);
	BenchMarkKeyed<ThreeWayDecryption>("3-WAY", t);
	BenchMarkKeyed<TEA::Encryption>("TEA", t);
	BenchMarkKeyedVariable<SAFER_SK::Encryption>("SAFER (r=8)", t, 8);
	BenchMarkKeyed<GOST::Encryption>("GOST", t);
#ifdef WORD64_AVAILABLE
	BenchMarkKeyed<SHARK::Encryption>("SHARK (r=6)", t);
#endif
	BenchMarkKeyed<CAST128::Encryption>("CAST-128", t);
	BenchMarkKeyed<CAST256::Encryption>("CAST-256", t);
	BenchMarkKeyed<Square::Encryption>("Square", t);
	BenchMarkKeyed<SKIPJACK::Encryption>("SKIPJACK", t);
	BenchMarkKeyed<RC6::Encryption>("RC6", t);
	BenchMarkKeyed<MARS::Encryption>("MARS", t);
	BenchMarkKeyedVariable<Rijndael::Encryption>("Rijndael (128-bit key)", t, 16);
	BenchMarkKeyedVariable<Rijndael::Encryption>("Rijndael (192-bit key)", t, 24);
	BenchMarkKeyedVariable<Rijndael::Encryption>("Rijndael (256-bit key)", t, 32);
	BenchMarkKeyedVariable<CTR_Mode<Rijndael>::Encryption>("Rijndael (128) CTR", t, 16);
	BenchMarkKeyedVariable<OFB_Mode<Rijndael>::Encryption>("Rijndael (128) OFB", t, 16);
	BenchMarkKeyedVariable<CFB_Mode<Rijndael>::Encryption>("Rijndael (128) CFB", t, 16);
	BenchMarkKeyedVariable<CBC_Mode<Rijndael>::Encryption>("Rijndael (128) CBC", t, 16);
	BenchMarkKeyed<Twofish::Encryption>("Twofish", t);
	BenchMarkKeyed<Serpent::Encryption>("Serpent", t);
	BenchMarkKeyed<ARC4>("ARC4", t);
	BenchMarkKeyed<SEAL<BigEndian>::Encryption>("SEAL-3.0-BE", t);
	BenchMarkKeyed<SEAL<LittleEndian>::Encryption>("SEAL-3.0-LE", t);
	BenchMarkKeyed<WAKE_CFB<BigEndian>::Encryption>("WAKE-CFB-BE", t);
	BenchMarkKeyed<WAKE_CFB<LittleEndian>::Encryption>("WAKE-CFB-LE", t);
	BenchMarkKeyed<WAKE_OFB<BigEndian>::Encryption>("WAKE-OFB-BE", t);
	BenchMarkKeyed<WAKE_OFB<LittleEndian>::Encryption>("WAKE-OFB-LE", t);
	BenchMarkKeyed<PanamaCipher<LittleEndian>::Encryption>("Panama Cipher (little endian)", t);
	BenchMarkKeyed<PanamaCipher<BigEndian>::Encryption>("Panama Cipher (big endian)", t);
	BenchMarkKeyedVariable<SHACAL2::Encryption>("SHACAL-2 (128-bit key)", t, 16);
	BenchMarkKeyedVariable<SHACAL2::Encryption>("SHACAL-2 (512-bit key)", t, 64);
#ifdef WORD64_AVAILABLE
	BenchMarkKeyedVariable<Camellia::Encryption>("Camellia (128-bit key)", t, 16);
	BenchMarkKeyedVariable<Camellia::Encryption>("Camellia (192-bit key)", t, 24);
	BenchMarkKeyedVariable<Camellia::Encryption>("Camellia (256-bit key)", t, 32);
#endif
	BenchMarkKeyed<MD5MAC>("MD5-MAC", t);
	BenchMarkKeyed<XMACC<MD5> >("XMACC/MD5", t);
	BenchMarkKeyed<HMAC<MD5> >("HMAC/MD5", t);
	BenchMarkKeyed<TTMAC>("Two-Track-MAC", t);
	BenchMarkKeyed<CBC_MAC<Rijndael> >("CBC-MAC/Rijndael", t);
	BenchMarkKeyed<DMAC<Rijndael> >("DMAC/Rijndael", t);

	{
		Integer p("CB6C,B8CE,6351,164F,5D0C,0C9E,9E31,E231,CF4E,D551,CBD0,E671,5D6A,7B06,D8DF,C4A7h");
		Integer q("FD2A,8594,A132,20CC,4E6D,DE77,3AAA,CF15,CD9E,E447,8592,FF46,CC77,87BE,9876,A2AFh");
		Integer s("63239752671357255800299643604761065219897634268887145610573595874544114193025997412441121667211431");
		BlumBlumShub c(p, q, s);
		BenchMark("BlumBlumShub 512", c, t);
	}
	{
		Integer p("FD2A,8594,A132,20CC,4E6D,DE77,3AAA,CF15,CD9E,E447,8592,FF46,CC77,87BE,9876,9E2C,"
				  "8572,64C3,4CF4,188A,44D4,2130,1135,7982,6FF6,EDD3,26F0,5FAA,BAF4,A81E,7ADC,B80Bh");
		Integer q("C8B9,5797,B349,6BA3,FD72,F2C0,A796,8A65,EE0F,B4BA,272F,4FEE,4DB1,06D5,ECEB,7142,"
				  "E8A8,E5A8,6BF9,A32F,BA37,BACC,8A75,8A6B,2DCE,D6EC,B515,980A,4BB1,08FB,6F2C,2383h");
		Integer s("3578,8F00,2965,71A4,4382,699F,45FD,3922,8238,241B,CEBA,0543,3443,E8D9,12FB,AC46,"
				  "7EC4,8505,EC9E,7EE8,5A23,9B2A,B615,D0C4,9448,F23A,ADEE,E850,1A7A,CA30,0B5B,A408,"
				  "D936,21BA,844E,BDD6,7848,3D1E,9137,CC87,DAA5,773B,D45A,C8BB,5392,1393,108B,6992,"
				  "74E3,C5E2,C235,A321,0111,3BA4,BAB4,1A2F,17EE,C371,DE67,01C9,0F3D,907A,B252,9BDDh");
		BlumBlumShub c(p, q, s);
		BenchMark("BlumBlumShub 1024", c, t);
	}
	{
		Integer p("EB56,978A,7BA7,B5D9,1383,4611,94F5,4766,FCEF,CF41,958A,FC41,43D0,839F,C56B,B568,"
				  "4ED3,9E5A,BABB,5ACE,8B11,CEBC,88A2,7C12,FFEE,E6E8,CF0A,E231,5BC2,DEDE,80B7,32F6,"
				  "340E,D8A6,B7DE,C779,7EE5,0E16,9C88,FC9F,2A0E,EE6C,7D47,C5F2,6B06,EB8C,F1C8,2E67,"
				  "5B82,8C28,4FB8,542F,2874,C355,CEEE,7A54,1B06,A8AB,8B66,6A5C,9DB2,72B8,74F3,7BC7h");
		Integer q("EB6B,3645,4591,8343,7331,7CAC,B02E,4BB9,DEF5,8EDC,1772,DB9B,9571,5FAB,1CDD,4FB1,"
				  "7B9A,07CD,E715,D448,F552,CBBD,D387,C037,DE70,6661,F360,D0E8,D42E,292A,9321,DDCB,"
				  "0BF9,C514,BFAC,3F2C,C06E,DF64,A9B8,50D6,AC4F,B9E4,014B,5624,2B40,A0D4,5D0B,6DD4,"
				  "0989,D00E,0268,99AB,21DB,0BB4,DB38,84DA,594F,575F,95AC,1B70,45E4,96C8,C6AD,CE67h");
		Integer s("C75A,8A0D,E231,295F,C08A,1716,8611,D5EC,E9EF,B565,90EC,58C0,57D0,DA7D,C6E6,DB00,"
				  "2282,1CA7,EA31,D64E,768C,0B19,8563,36DF,2226,F4EC,74A4,2844,2E8D,37E8,53DC,0172,"
				  "5F56,8CF9,B444,CA02,78B3,17AF,7C78,D320,16AE,AC3D,B97F,7259,1B8F,9C84,6A16,B878,"
				  "0595,70BB,9C52,18B5,9100,9C1F,E85A,4035,06F3,5F38,7462,F01D,0462,BFBC,A4CD,4A45,"
				  "3A77,E7F8,DED1,D6EF,CEF7,0937,CD3F,3AF1,4F88,932D,6D4B,002C,3735,304C,C5D3,B88A,"
				  "B57B,24B6,5346,9B46,5153,B7ED,B216,C181,B1C6,C52E,CD2B,E0AA,B1BB,0A93,C92E,4F79,"
				  "4931,E303,7C8F,A408,8ACF,56CD,6EC0,76A2,5015,6BA4,4C50,C44D,53B9,E168,5F84,B381,"
				  "2514,10B2,00E5,B4D1,4156,A2FE,0BF6,6F33,0A1B,91C6,31B8,1C90,02F1,FB1F,C494,8B65h");
		BlumBlumShub c(p, q, s);
		BenchMark("BlumBlumShub 2048", c, t);
	}
	cout << "</TABLE>" << endl;

	BenchmarkAll2(t);

	cout << "Throughput Geometric Average: " << setiosflags(ios::fixed) << exp(logtotal/logcount) << endl;

	time_t endTime = time(NULL);
	cout << "\nTest ended at " << asctime(localtime(&endTime));
#endif
}
Exemplo n.º 9
0
 comment_content_object( Constructor&& c, allocator< Allocator > a ) :
    title( a ), body( a ), json_metadata( a )
 {
    c( *this );
 }
Exemplo n.º 10
0
Arquivo: gflops.c Projeto: yoyz/mpi
double addmul_sse()
{
  long long ii;
  double    res;
  double    mul=1.00001;

  Vec2d  a(0.1, 0.2);
  Vec2d  b(0.3, 0.4);
  Vec2d  c(0.5, 0.6);
  Vec2d  d(0.7, 0.8);

  Vec2d  e(2.1, 2.2);
  Vec2d  f(2.3, 2.4);
  Vec2d  g(2.5, 2.6);
  Vec2d  h(2.7, 2.8);

  Vec2d  i(3.1, 3.2);
  Vec2d  j(3.3, 3.4);
  Vec2d  k(3.5, 3.6);
  Vec2d  l(3.7, 3.8);

  Vec2d  m(4.1, 4.2);
  Vec2d  n(4.3, 4.4);
  Vec2d  o(4.5, 4.6);
  Vec2d  p(4.7, 4.8);

  
  for(ii=0; ii< max1*max2 ; ii++)
    {
      a=a*b;
      b=b+c;
      c=c*d;
      d=d+e;
   
      e=e*f;
      f=f+g;
      g=g*h;
      h=h+i;

      i=i*j;
      j=j+k;
      k=k*l;
      l=l+m;

      m=m*n;
      n=n+o;
      o=o*p;
      p=p+a;
    }

  res=
    a[0]+a[1]+
    b[0]+b[1]+
    c[0]+c[1]+
    d[0]+d[1]+

    e[0]+e[1]+
    f[0]+f[1]+
    g[0]+g[1]+
    h[0]+h[1]+

    i[0]+i[1]+
    j[0]+j[1]+
    k[0]+k[1]+
    l[0]+l[1]+

    m[0]+m[1]+
    n[0]+n[1]+
    o[0]+o[1]+
    p[0]+p[1]

  ;

  return res;

}
Exemplo n.º 11
0
Arquivo: gflops.c Projeto: yoyz/mpi
double addmul_avx()
{
  long long ii;
  double  res;
  double  mul=1.00001;

  Vec4d  a(0.1, 0.2, 0.3, 0.4);
  Vec4d  b(0.5, 0.6, 0.7, 0.8);
  Vec4d  c(0.9, 1.0, 1.1, 1.2);
  Vec4d  d(1.3, 1.4, 1.5, 1.6);

  Vec4d  e(2.1, 2.2, 2.3, 2.4);
  Vec4d  f(2.5, 2.6, 2.7, 2.8);
  Vec4d  g(2.9, 3.0, 3.1, 3.2);
  Vec4d  h(3.3, 3.4, 3.5, 3.6);

  Vec4d  i(4.1, 4.2, 4.3, 4.4);
  Vec4d  j(4.5, 4.6, 4.7, 4.8);
  Vec4d  k(4.9, 5.0, 5.1, 5.2);
  Vec4d  l(5.3, 5.4, 5.5, 5.6);

  Vec4d  m(6.1, 6.2, 6.3, 6.4);
  Vec4d  n(6.5, 6.6, 6.7, 6.8);
  Vec4d  o(6.9, 7.0, 7.1, 7.2);
  Vec4d  p(7.3, 7.4, 7.5, 7.6);

  
  for(ii=0; ii< max1*max2 ; ii++)
    {
      a=a*c;
      b=b+d;
      c=c*e;
      d=d+f;
   
      e=e*g;
      f=f+h;
      g=g*i;
      h=h+j;

      i=i*k;
      j=j+l;
      k=k*m;
      l=l+n;

      m=m*o;
      n=n+p;
      o=o*a;
      p=p+b;
    }

  res=
    a[0]+a[1]+a[2]+a[3] + 
    b[0]+b[1]+b[2]+b[3] + 
    c[0]+c[1]+c[2]+c[3] +
    d[0]+d[1]+d[2]+d[3] +

    e[0]+e[1]+e[2]+e[3] + 
    f[0]+f[1]+f[2]+f[3] + 
    g[0]+g[1]+g[2]+g[3] +
    h[0]+h[1]+h[2]+h[3] +

    i[0]+i[1]+i[2]+i[3] + 
    j[0]+j[1]+j[2]+j[3] + 
    k[0]+k[1]+k[2]+k[3] +
    l[0]+l[1]+l[2]+l[3] +

    m[0]+m[1]+m[2]+m[3] + 
    n[0]+n[1]+n[2]+n[3] + 
    o[0]+o[1]+o[2]+o[3] +
    p[0]+p[1]+p[2]+p[3] 

  ;

  return res;

}
Exemplo n.º 12
0
	virtual void doPaint(wxDC* dc)
	{
		if (!m_imgHandle.getImg() || !m_imgHandle->IsOk())
		{
			dc->SetTextForeground(wxColor(0,0,0));
			dc->Clear();
			return;
		}

		dc->SetFont(GetFont());
		dc->SetTextBackground(GetBackgroundColour());

		if (m_bHovering)
			dc->SetTextForeground(m_colHover);
		else if (m_bSelected)
			dc->SetTextForeground(m_colSelected);
		else
			dc->SetTextForeground(m_colNormal);


		int h = GetSize().GetHeight();
		int w = GetSize().GetWidth();
		int iw = m_imgHandle->GetSize().GetWidth();

		wxBitmap   tmpBmp(w, h);
		wxMemoryDC tmpDC(tmpBmp);

		tmpDC.SetBrush(wxBrush(wxColor(255,0,255)));
		tmpDC.SetPen( wxPen(wxColor(255,0,255),1) );
		tmpDC.DrawRectangle(0,0,w,h);

		wxImage scaled = m_imgHandle->Scale(iw, h);

		wxBitmap left;
		wxBitmap right;
		wxBitmap centerImg = GetGCThemeManager()->getSprite(scaled, "playlist_button", "fill");

		if (m_uiPos == LEFT)
		{
			left = GetGCThemeManager()->getSprite(scaled, "playlist_button", "left");
		}
		else
		{
			left = GetGCThemeManager()->getSprite(scaled, "playlist_button", "fill");
		}

		if (m_uiPos == RIGHT)
		{
			right = GetGCThemeManager()->getSprite(scaled, "playlist_button", "right");
		}
		else
		{
			right = GetGCThemeManager()->getSprite(scaled, "playlist_button", "seperator");
		}


		wxBitmap center(w-(left.GetWidth()+right.GetWidth()),h);

		wxColor c(255,0,255);
		gcImage::tileImg(center, centerImg, &c);

		tmpDC.DrawBitmap(left, 0,0,true);
		tmpDC.DrawBitmap(center, left.GetWidth(),0,true);
		tmpDC.DrawBitmap(right, w-right.GetWidth(),0,true);

		tmpDC.SelectObject(wxNullBitmap);
		dc->DrawBitmap(tmpBmp, 0,0, true);

		if (m_bTransEnabled)
		{
			wxRegion region = wxRegion(tmpBmp, wxColor(255,0,255), 1);
			SetShape(region, this);
		}

		wxString lab = GetLabel();

		long x = (w - dc->GetTextExtent(lab).GetWidth())/2;
		long y = (h - dc->GetTextExtent(lab).GetHeight())/2;

		dc->DrawText(lab, x, y);
	}
Exemplo n.º 13
0
int main(int, char**)
{
    {
        typedef std::unordered_multiset<NotConstructible,
                                   test_hash<std::hash<NotConstructible> >,
                                   test_compare<std::equal_to<NotConstructible> >,
                                   test_allocator<NotConstructible>
                                   > C;
        C c(test_allocator<NotConstructible>(10));
        LIBCPP_ASSERT(c.bucket_count() == 0);
        assert(c.hash_function() == test_hash<std::hash<NotConstructible> >());
        assert(c.key_eq() == test_compare<std::equal_to<NotConstructible> >());
        assert(c.get_allocator() == test_allocator<NotConstructible>(10));
        assert(c.size() == 0);
        assert(c.empty());
        assert(std::distance(c.begin(), c.end()) == 0);
        assert(c.load_factor() == 0);
        assert(c.max_load_factor() == 1);
    }
#if TEST_STD_VER >= 11
    {
        typedef std::unordered_multiset<NotConstructible,
                                   test_hash<std::hash<NotConstructible> >,
                                   test_compare<std::equal_to<NotConstructible> >,
                                   min_allocator<NotConstructible>
                                   > C;
        C c(min_allocator<NotConstructible>{});
        LIBCPP_ASSERT(c.bucket_count() == 0);
        assert(c.hash_function() == test_hash<std::hash<NotConstructible> >());
        assert(c.key_eq() == test_compare<std::equal_to<NotConstructible> >());
        assert(c.get_allocator() == min_allocator<NotConstructible>());
        assert(c.size() == 0);
        assert(c.empty());
        assert(std::distance(c.begin(), c.end()) == 0);
        assert(c.load_factor() == 0);
        assert(c.max_load_factor() == 1);
    }
#if TEST_STD_VER > 11
    {
        typedef NotConstructible T;
        typedef test_hash<std::hash<T>> HF;
        typedef test_compare<std::equal_to<T>> Comp;
        typedef test_allocator<T> A;
        typedef std::unordered_multiset<T, HF, Comp, A> C;

        A a(43);
        C c(3, a);
        LIBCPP_ASSERT(c.bucket_count() == 3);
        assert(c.hash_function() == HF());
        assert(c.key_eq() == Comp ());
        assert(c.get_allocator() == a);
        assert(!(c.get_allocator() == A()));
        assert(c.size() == 0);
        assert(c.empty());
        assert(std::distance(c.begin(), c.end()) == 0);
        assert(c.load_factor() == 0);
        assert(c.max_load_factor() == 1);
    }
    {
        typedef NotConstructible T;
        typedef test_hash<std::hash<T>> HF;
        typedef test_compare<std::equal_to<T>> Comp;
        typedef test_allocator<T> A;
        typedef std::unordered_multiset<T, HF, Comp, A> C;

        HF hf(42);
        A a(43);
        C c(4, hf, a);
        LIBCPP_ASSERT(c.bucket_count() == 4);
        assert(c.hash_function() == hf);
        assert(!(c.hash_function() == HF()));
        assert(c.key_eq() == Comp ());
        assert(c.get_allocator() == a);
        assert(!(c.get_allocator() == A()));
        assert(c.size() == 0);
        assert(c.empty());
        assert(std::distance(c.begin(), c.end()) == 0);
        assert(c.load_factor() == 0);
        assert(c.max_load_factor() == 1);
    }
#endif
#endif

  return 0;
}
Exemplo n.º 14
0
int main( )
{
    cube< color > c(
        faces< color > { color::blue },
        faces< color > { color::green },
        faces< color > { color::orange },
        faces< color > { color::red },
        faces< color > { color::white },
        faces< color > { color::yellow } );
    std::vector< move > moves =
    {
        { move::up, move::clockwise },
        { move::right, move::flip },
        { move::front, move::clockwise },
        { move::back, move::clockwise },
        { move::right, move::clockwise },
        { move::back, move::flip },
        { move::right, move::clockwise },
        { move::up, move::flip },
        { move::left, move::clockwise },
        { move::back, move::flip },
        { move::right, move::clockwise },
        { move::up, move::counter_clockwise },
        { move::down, move::counter_clockwise },
        { move::right, move::flip },
        { move::front, move::clockwise },
        { move::right, move::counter_clockwise },
        { move::left, move::clockwise },
        { move::back, move::flip },
        { move::up, move::flip },
        { move::front, move::flip }
    };
    c.make_moves( moves.begin( ), moves.end( ) );
    using wild_cube = cube< std::set< color > >;
    auto make_wild_cube = []( ) -> wild_cube
    {
        return
        {
            faces< std::set< color > > { { } },
            faces< std::set< color > > { { } },
            faces< std::set< color > > { { } },
            faces< std::set< color > > { { } },
            faces< std::set< color > > { { } },
            faces< std::set< color > > { { } }
        };
    };
    std::list< wild_cube > middle_steps =
    {
        make_wild_cube( ),
        make_wild_cube( ),
        make_wild_cube( ),
        make_wild_cube( ),
        make_wild_cube( ),
        make_wild_cube( ),
        make_wild_cube( ),
        make_wild_cube( ),
        make_wild_cube( ),
        make_wild_cube( ),
        make_wild_cube( ),
        make_wild_cube( ),
        make_wild_cube( ),
        make_wild_cube( ),
        make_wild_cube( )
    };
    auto it = middle_steps.begin( ), end = middle_steps.end( );
    std::for_each(
        it,
        end,
        [&]( wild_cube & wc )
        {
            wc.front[1][1] =
            { c.front[1][1] };
            wc.back[1][1] =
            { c.back[1][1] };
            wc.left[1][1] =
            { c.left[1][1] };
            wc.right[1][1] =
            { c.right[1][1] };
            wc.up[1][1] =
            { c.up[1][1] };
            wc.down[1][1] =
            { c.down[1][1] };
        } );
    ++it;
    std::for_each(
        it,
        end,
        [&]( wild_cube & wc )
        {
            wc.down[0][0] =
            wc.down[0][2] =
            wc.down[2][0] =
            wc.down[2][2] =
            { c.down[1][1] };
            wc.front[2][0] =
            wc.front[2][2] =
            { c.front[1][1] };
            wc.left[2][0] =
            wc.left[2][2] =
            { c.left[1][1] };
            wc.right[2][0] =
            wc.right[2][2] =
            { c.right[1][1] };
            wc.back[0][0] =
            wc.back[0][2] =
            { c.back[1][1] };
        } );
    ++it;
    std::for_each(
        it,
        end,
        [&]( wild_cube & wc )
        {
            wc.up[0][0] =
            wc.up[0][2] =
            wc.up[2][0] =
            wc.up[2][2] =
            { c.up[1][1] };
            wc.front[0][0] =
            wc.front[0][2] =
            { c.front[1][1] };
            wc.left[0][0] =
            wc.left[0][2] =
            { c.left[1][1] };
            wc.right[0][0] =
            wc.right[0][2] =
            { c.right[1][1] };
            wc.back[2][0] =
            wc.back[2][2] =
            { c.back[1][1] };
        } );
    ++it;
    std::for_each(
        it,
        end,
        [&]( wild_cube & wc )
        {
            wc.left[1][2] =
            { c.left[1][1] };
            wc.front[1][0] =
            { c.front[1][1] };
        } );
    ++it;
    std::for_each(
        it,
        end,
        [&]( wild_cube & wc )
        {
            wc.left[2][1] =
            { c.left[1][1] };
            wc.down[1][0] =
            { c.down[1][1] };
        } );
    ++it;
    std::for_each(
        it,
        end,
        [&]( wild_cube & wc )
        {
            wc.left[1][0] =
            { c.left[1][1] };
            wc.back[1][0] =
            { c.back[1][1] };
        } );
    ++it;
    std::for_each(
        it,
        end,
        [&]( wild_cube & wc )
        {
            wc.right[1][0] =
            { c.right[1][1] };
            wc.front[1][2] =
            { c.front[1][1] };
        } );
    ++it;
    std::for_each(
        it,
        end,
        [&]( wild_cube & wc )
        {
            wc.right[0][1] =
            { c.right[1][1] };
            wc.up[1][2] =
            { c.up[1][1] };
        } );
    ++it;
    std::for_each(
        it,
        end,
        [&]( wild_cube & wc )
        {
            wc.right[2][1] =
            { c.right[1][1] };
            wc.down[1][2] =
            { c.down[1][1] };
        } );
    ++it;
    std::for_each(
        it,
        end,
        [&]( wild_cube & wc )
        {
            wc.right[1][2] =
            { c.left[1][1] };
            wc.back[1][2] =
            { c.back[1][1] };
        } );
    ++it;
    std::for_each(
        it,
        end,
        [&]( wild_cube & wc )
        {
            wc.front[0][1] =
            wc.front[2][1] =
            {
                c.front[1][1],
                c.back[1][1]
            };
        } );
    ++it;
    std::for_each(
        it,
        end,
        [&]( wild_cube & wc )
        {
            wc.back[0][1] =
            wc.back[2][1] =
            {
                c.front[1][1],
                c.back[1][1]
            };
        } );
    ++it;
    std::for_each(
        it,
        end,
        [&]( wild_cube & wc )
        {
            wc.up[0][1] =
            wc.up[2][1] =
            { c.up[1][1] };
        } );
    ++it;
    std::for_each(
        it,
        end,
        [&]( wild_cube & wc )
        {
            wc.down[0][1] =
            wc.down[2][1] =
            { c.down[1][1] };
        } );
    ++it;
    std::for_each(
        it,
        end,
        [&]( wild_cube & wc )
        {
            wc.front[0][1] =
            wc.front[2][1] =
            { c.front[1][1] };
        } );
    ++it;
    std::for_each(
        it,
        end,
        [&]( wild_cube & wc )
        {
            wc.back[0][1] =
            wc.back[2][1] =
            { c.back[1][1] };
        } );
    assert( it == end );
    auto all_action =
        []( const wild_cube &, auto it ) { std::copy( all_moves( ).begin( ), all_moves( ).end( ), it ); };
    auto f1 =
        []( wild_cube c, move m )
        {
            c.make_move( m );
            return c;
        };
    std::list< wild_cube > finished_middle_steps = middle_steps;
    for ( wild_cube & c : middle_steps ) { c.make_moves( moves.begin( ), moves.end( ) ); }
    while ( ! middle_steps.empty( ) )
    {
        std::list< move > forward, backward;
        AI::biderectional_breadth_first_search< move, move >(
            middle_steps.front( ),
            finished_middle_steps.front( ),
            all_action,
            f1,
            std::back_insert_iterator< decltype( forward ) >( forward ),
            all_action,
            f1,
            std::back_insert_iterator< decltype( backward ) >( backward ) );
        c.make_moves( forward.begin( ), forward.end( ) );
        c.undo_moves( backward.rbegin( ), backward.rend( ) );
        std::cout << c << std::endl;
        middle_steps.pop_front( );
        finished_middle_steps.pop_front( );
        for ( wild_cube & wc : middle_steps )
        {
            wc.make_moves( forward.begin( ), forward.end( ) );
            wc.undo_moves( backward.rbegin( ), backward.rend( ) );
        }
    }
    return 0;
}
Exemplo n.º 15
0
  Rational operator /(Rational a, Rational b) {
  	Rational c(a.num*b.den, a.den*b.num);

  	return c;
  }
Exemplo n.º 16
0
void Waveform::DrawWaveView(const WaveView &wv)
{
    int index;
    glLineWidth( 1 );

    xlColor color(212,208,200);
    DrawGLUtils::AddVertex(0, 0, color);
    DrawGLUtils::AddVertex(mWindowWidth, 0, color);
    DrawGLUtils::AddVertex(mWindowWidth, mWindowHeight, color);
    DrawGLUtils::AddVertex(0, mWindowHeight, color);
    DrawGLUtils::End(GL_TRIANGLE_FAN);

    int max_wave_ht = mWindowHeight - VERTICAL_PADDING;

    // Draw Outside rectangle
    color.Set(128, 128, 128);
    DrawGLUtils::AddVertex(0.25, 0, color);
    DrawGLUtils::AddVertex(mWindowWidth, 0, color);
    DrawGLUtils::AddVertex(mWindowWidth, mWindowHeight-0.5, color);
    DrawGLUtils::AddVertex(0.25, mWindowHeight-0.5, color);
    DrawGLUtils::End(GL_LINE_LOOP);

    // Get selection positions from timeline
    int selected_x1 = mTimeline->GetSelectedPositionStart();
    int selected_x2 = mTimeline->GetSelectedPositionEnd();

    // draw shaded region if needed
    if( selected_x1 != -1 && selected_x2 != -1)
    {
        glEnable(GL_BLEND);
        color.Set(0, 0, 200, 45);
        DrawGLUtils::AddVertex(selected_x1, 1, color);
        DrawGLUtils::AddVertex(selected_x2, 1, color);
        DrawGLUtils::AddVertex(selected_x2, mWindowHeight-1, color);
        DrawGLUtils::AddVertex(selected_x1, mWindowHeight-1, color);
        DrawGLUtils::End(GL_TRIANGLE_FAN);
        glDisable(GL_BLEND);
    }

    if(_media != NULL)
    {
        xlColor c(130,178,207,255);

        std::vector<double> vertexes;
        vertexes.resize((mWindowWidth + 2) * 2);

        for (int x=0;x<mWindowWidth && (x)<wv.MinMaxs.size();x++)
        {
            index = x+mStartPixelOffset;
            if (index >= 0 && index < wv.MinMaxs.size())
            {
                double y1 = ((wv.MinMaxs[index].min * (float)(max_wave_ht/2))+ (mWindowHeight/2));
                double y2 = ((wv.MinMaxs[index].max * (float)(max_wave_ht/2))+ (mWindowHeight/2));
                DrawGLUtils::AddVertex(x, y1, c);
                DrawGLUtils::AddVertex(x, y2, c);
                vertexes[x * 2] = y1;
                vertexes[x * 2 + 1] = y2;
            }
        }
        DrawGLUtils::End(GL_TRIANGLE_STRIP);

        
        for(int x=0;x<mWindowWidth-1 && (x)<wv.MinMaxs.size();x++)
        {
            DrawGLUtils::AddVertex(x, vertexes[x * 2], xlWHITE);
        }
        for(int x=mWindowWidth;x >= 0 ; x--)
        {
            if (x<wv.MinMaxs.size()) {
                DrawGLUtils::AddVertex(x, vertexes[x * 2 + 1], xlWHITE);
            }
        }
        DrawGLUtils::End(GL_LINE_STRIP);
    }

    // draw selection line if not a range
    if( selected_x1 != -1 && selected_x2 == -1 )
    {
        color.Set(0, 0, 0, 128);
        DrawGLUtils::AddVertex(selected_x1, 1, color);
        DrawGLUtils::AddVertex(selected_x1, mWindowHeight-1, color);
    }

    // draw mouse position line
    int mouse_marker = mTimeline->GetMousePosition();
    if( mouse_marker != -1 )
    {
        color.Set(0, 0, 255, 255);
        DrawGLUtils::AddVertex(mouse_marker, 1, color);
        DrawGLUtils::AddVertex(mouse_marker, mWindowHeight-1, color);
    }

    // draw play marker line
    int play_marker = mTimeline->GetPlayMarker();
    if( play_marker != -1 )
    {
        color.Set(0, 0, 0, 255);
        DrawGLUtils::AddVertex(play_marker, 1, color);
        DrawGLUtils::AddVertex(play_marker, mWindowHeight-1, color);
    }
    if (DrawGLUtils::VertexCount() > 0) {
        DrawGLUtils::End(GL_LINES);
    }
}
Exemplo n.º 17
0
double Navigation::getPath(RobotCommand rc, QList<Vector2D> *points)
{
    Q_UNUSED(points);
    if(rc.useNav == false)
        return wm->ourRobot[id].pos.loc.dist(rc.fin_pos.loc);

    AStarSearch<MapSearchNode> astarsearch;
    MapSearchNode::wm = wm;
    MapSearchNode::isBallObs = rc.isBallObs;
    MapSearchNode::isKickObs = rc.isKickObs;
    MapSearchNode::selfRobot = id;

    MapSearchNode nodeStart;
    MapSearchNode nodeEnd;

    nodeStart.vec = wm->ourRobot[id].pos.loc;

    auto obs = MapSearchNode::getObsCircle();
    bool is_fin_obs = false;
    for(int i=0; i<obs.size(); i++)
    {
        if(obs[i].contains(rc.fin_pos.loc))
        {
            Circle2D c(obs[i].center(), obs[i].radius() + BALL_RADIUS*3);
            if(rc.fin_pos.loc == obs[i].center()) rc.fin_pos.loc += Vector2D(-1,0);
            Line2D l(obs[i].center(), rc.fin_pos.loc);
            Vector2D ans1, ans2;
            int ans = c.intersection(l, &ans1, &ans2);
            switch (ans)
            {
            case 0:
                qDebug() << "NAV 0 !!!";
                //qDebug() << c.center().x << c.center().y << c.radius();
                //qDebug() << l.a() << l.b() << l.c();
                //qDebug() << wm->ball.pos.loc.x << wm->ball.pos.loc.y;
                //qDebug() << rc.fin_pos.loc.x << rc.fin_pos.loc.y;
                break;
            case 1:
                //qDebug() << "1";
                nodeEnd.vec = ans1;
                is_fin_obs = true;
                break;
            case 2:
                //qDebug() << "2";
                if(ans1.dist2(rc.fin_pos.loc) < ans2.dist2(rc.fin_pos.loc))
                    nodeEnd.vec = ans1;
                else
                    nodeEnd.vec = ans2;
                is_fin_obs = true;
                break;
            default:
                qDebug() << "DEF";
                break;
            }

            //qDebug() << "FIN_POS chaned" << rc.fin_pos.loc.x << rc.fin_pos.loc.y << nodeEnd.vec.x << nodeEnd.vec.y;
            break;
        }
    }
    if(!is_fin_obs) nodeEnd.vec = rc.fin_pos.loc;

    //qDebug()<< "----- NAV START -----";
    //qDebug()<< "start" << nodeStart.vec.x << nodeStart.vec.y;
    //qDebug()<< "end  " << nodeEnd.vec.x << nodeEnd.vec.y;

    astarsearch.SetStartAndGoalStates(nodeStart, nodeEnd);

    unsigned int SearchState;
    unsigned int SearchSteps = 0;

    do
    {
        //qDebug() << "SearchStep" << SearchSteps;
        SearchState = astarsearch.SearchStep();
        SearchSteps++;
    }
    while(SearchState == AStarSearch<MapSearchNode>::SEARCH_STATE_SEARCHING);

    double pathL = 0;
    if(SearchState == AStarSearch<MapSearchNode>::SEARCH_STATE_SUCCEEDED)
    {
        //qDebug() << "AStarSearch SUCCEEDED";
        MapSearchNode *node = astarsearch.GetSolutionStart();
        //qDebug() << "SolutionStart" << node->vec.x << node->vec.y;
        int steps = 0;
        if(points) points->append(node->vec); //nodeStart
        Vector2D lastNode = node->vec;
        for(;;)
        {
            node = astarsearch.GetSolutionNext();
            if(!node) break;
            //qDebug() << "SolutionNext" << node->vec.x << node->vec.y;
            if(points) points->append(node->vec);
            steps++;
            pathL += (lastNode - node->vec).length();
            lastNode = node->vec;
        }
        astarsearch.FreeSolutionNodes();
    }
    else if(SearchState == AStarSearch<MapSearchNode>::SEARCH_STATE_FAILED)
    {
        qDebug() << "AStarSearch FAILED" << id;
    }
    astarsearch.EnsureMemoryFreed();

    //qDebug()<< "----- NAV END -----";
    return pathL; //path length
}
Exemplo n.º 18
0
/* 
 * [type,num_constraint,constraint_val,dconstraint_val,constraint_name,lower_bound,upper_bound] = testSingleTimeKinCnstmex(kinCnst_ptr,q,t)
 * @param kinCnst_ptr           A pointer to a SingleTimeKinematicConstraint object
 * @param q                     A nqx1 double vector
 * @param t                     A double scalar, the time to evaluate constraint value, bounds and name. This is optional.
 * @retval type                 The type of the constraint
 * @retval num_constraint       The number of constraint active at time t
 * @retval constraint_val       The value of the constraint at time t
 * @retval dconstraint_val      The gradient of the constraint w.r.t q at time t
 * @retval constraint_name      The name of the constraint at time t
 * @retval lower_bound          The lower bound of the constraint at time t
 * @retval upper_bound          The upper bound of the constraint at time t
 * */
void mexFunction(int nlhs, mxArray* plhs[], int nrhs, const mxArray* prhs[])
{
  if((nrhs!=3 && nrhs != 2)||nlhs != 7)
  {
    mexErrMsgIdAndTxt("Drake:testSingleTimeKinCnstmex:BadInputs","Usage [type, num_cnst,cnst_val,dcnst_val,cnst_name,lb,ub] = testSingleTimeKinKinCnstmex(kinCnst,q,t)");
  }
  SingleTimeKinematicConstraint* cnst = (SingleTimeKinematicConstraint*) getDrakeMexPointer(prhs[0]);
  double* t_ptr;
  if(nrhs == 2)
  {
    t_ptr = nullptr;
  }
  else
  {
    size_t num_t = mxGetNumberOfElements(prhs[2]);
    if(num_t == 0)
    {
      t_ptr = nullptr;
    }
    if(num_t == 1)
    {
      t_ptr = mxGetPrSafe(prhs[2]);
    }
    if(num_t>1)
    {
      mexErrMsgIdAndTxt("Drake:testSingleTimeKinCnstmex:BadInputs","t must be either empty or a single number");
    }
  }
  int type = cnst->getType();
  int num_cnst = cnst->getNumConstraint(t_ptr);
  //mexPrintf("num_cnst = %d\n",num_cnst);
  int nq = cnst->getRobotPointer()->num_positions;
  Map<VectorXd> q(mxGetPrSafe(prhs[1]), nq);
  KinematicsCache<double> cache = cnst->getRobotPointer()->doKinematics(q, 0);
  VectorXd c(num_cnst);
  MatrixXd dc(num_cnst,nq);
  cnst->eval(t_ptr, cache, c, dc);
  //mexPrintf("get c,dc\n");
  VectorXd lb(num_cnst);
  VectorXd ub(num_cnst);
  cnst->bounds(t_ptr,lb,ub);
  //mexPrintf("get lb, ub\n");
  std::vector<std::string> cnst_names;
  cnst->name(t_ptr,cnst_names);
  //mexPrintf("get name\n");
  int retvec_size;
  if(num_cnst == 0)
  {
    retvec_size = 0;
  }
  else
  {
    retvec_size = 1;
  }
  plhs[0] = mxCreateDoubleScalar((double) type);
  plhs[1] = mxCreateDoubleScalar((double) num_cnst);
  plhs[2] = mxCreateDoubleMatrix(num_cnst,retvec_size,mxREAL);
  memcpy(mxGetPrSafe(plhs[2]),c.data(),sizeof(double)*num_cnst);
  plhs[3] = mxCreateDoubleMatrix(num_cnst,nq,mxREAL);
  memcpy(mxGetPrSafe(plhs[3]),dc.data(),sizeof(double)*num_cnst*nq);
  int name_ndim = 1;
  mwSize name_dims[] = {(mwSize) num_cnst};
  plhs[4] = mxCreateCellArray(name_ndim,name_dims);
  mxArray *name_ptr;
  for(int i = 0;i<num_cnst;i++)
  {
    name_ptr = mxCreateString(cnst_names[i].c_str());
    mxSetCell(plhs[4],i,name_ptr);
  }
  plhs[5] = mxCreateDoubleMatrix(num_cnst,retvec_size,mxREAL);
  plhs[6] = mxCreateDoubleMatrix(num_cnst,retvec_size,mxREAL);
  memcpy(mxGetPrSafe(plhs[5]),lb.data(),sizeof(double)*num_cnst);
  memcpy(mxGetPrSafe(plhs[6]),ub.data(),sizeof(double)*num_cnst);
}
Exemplo n.º 19
0
    void _initAndListen(int listenPort ) {

        Client::initThread("initandlisten");

        bool is32bit = sizeof(int*) == 4;

        {
            ProcessId pid = ProcessId::getCurrent();
            LogstreamBuilder l = log();
            l << "MongoDB starting : pid=" << pid
              << " port=" << serverGlobalParams.port
              << " dbpath=" << storageGlobalParams.dbpath;
            if( replSettings.master ) l << " master=" << replSettings.master;
            if( replSettings.slave )  l << " slave=" << (int) replSettings.slave;
            l << ( is32bit ? " 32" : " 64" ) << "-bit host=" << getHostNameCached() << endl;
        }
        DEV log() << "_DEBUG build (which is slower)" << endl;
        logStartupWarnings();
#if defined(_WIN32)
        printTargetMinOS();
#endif
        logProcessDetails();
        {
            stringstream ss;
            ss << endl;
            ss << "*********************************************************************" << endl;
            ss << " ERROR: dbpath (" << storageGlobalParams.dbpath << ") does not exist." << endl;
            ss << " Create this directory or give existing directory in --dbpath." << endl;
            ss << " See http://dochub.mongodb.org/core/startingandstoppingmongo" << endl;
            ss << "*********************************************************************" << endl;
            uassert(10296,  ss.str().c_str(), boost::filesystem::exists(storageGlobalParams.dbpath));
        }
        {
            stringstream ss;
            ss << "repairpath (" << storageGlobalParams.repairpath << ") does not exist";
            uassert(12590,  ss.str().c_str(),
                    boost::filesystem::exists(storageGlobalParams.repairpath));
        }

        // TODO check non-journal subdirs if using directory-per-db
        checkReadAhead(storageGlobalParams.dbpath);

        acquirePathLock(mongodGlobalParams.repair);
        boost::filesystem::remove_all(storageGlobalParams.dbpath + "/_tmp/");

        FileAllocator::get()->start();

        // TODO:  This should go into a MONGO_INITIALIZER once we have figured out the correct
        // dependencies.
        if (snmpInit) {
            snmpInit();
        }

        MONGO_ASSERT_ON_EXCEPTION_WITH_MSG( clearTmpFiles(), "clear tmp files" );

        dur::startup();

        if (storageGlobalParams.durOptions & StorageGlobalParams::DurRecoverOnly)
            return;

        unsigned long long missingRepl = checkIfReplMissingFromCommandLine();
        if (missingRepl) {
            log() << startupWarningsLog;
            log() << "** WARNING: mongod started without --replSet yet " << missingRepl
                  << " documents are present in local.system.replset" << startupWarningsLog;
            log() << "**          Restart with --replSet unless you are doing maintenance and no"
                  << " other clients are connected." << startupWarningsLog;
            log() << "**          The TTL collection monitor will not start because of this." << startupWarningsLog;
            log() << "**          For more info see http://dochub.mongodb.org/core/ttlcollections" << startupWarningsLog;
            log() << startupWarningsLog;
        }

        if (mongodGlobalParams.scriptingEnabled) {
            ScriptEngine::setup();
            globalScriptEngine->setCheckInterruptCallback( jsInterruptCallback );
            globalScriptEngine->setGetCurrentOpIdCallback( jsGetCurrentOpIdCallback );
        }

        // On replica set members we only clear temp collections on DBs other than "local" during
        // promotion to primary. On pure slaves, they are only cleared when the oplog tells them to.
        // The local DB is special because it is not replicated.  See SERVER-10927 for more details.
        const bool shouldClearNonLocalTmpCollections = !(missingRepl
                                                         || replSettings.usingReplSets()
                                                         || replSettings.slave == SimpleSlave);
        repairDatabasesAndCheckVersion(shouldClearNonLocalTmpCollections);

        if (mongodGlobalParams.upgrade)
            return;

        uassertStatusOK(getGlobalAuthorizationManager()->initialize());

        /* this is for security on certain platforms (nonce generation) */
        srand((unsigned) (curTimeMicros() ^ startupSrandTimer.micros()));

        // The snapshot thread provides historical collection level and lock statistics for use
        // by the web interface. Only needed when HTTP is enabled.
        if (serverGlobalParams.isHttpInterfaceEnabled)
            snapshotThread.go();

        d.clientCursorMonitor.go();
        PeriodicTask::startRunningPeriodicTasks();
        if (missingRepl) {
            // a warning was logged earlier
        }
        else {
            startTTLBackgroundJob();
        }

#ifndef _WIN32
        mongo::signalForkSuccess();
#endif

        if(getGlobalAuthorizationManager()->isAuthEnabled()) {
            // open admin db in case we need to use it later. TODO this is not the right way to
            // resolve this.
            Client::WriteContext c("admin", storageGlobalParams.dbpath);
        }

        authindex::configureSystemIndexes("admin");

        getDeleter()->startWorkers();

        // Starts a background thread that rebuilds all incomplete indices. 
        indexRebuilder.go(); 

        listen(listenPort);

        // listen() will return when exit code closes its socket.
        exitCleanly(EXIT_NET_ERROR);
    }
 void const_constraints(const TT& a) {
   TT c(a);            // require const copy constructor
   const TT* ptr = &a; // require const address of operator
   ignore_unused_variable_warning(c);
   ignore_unused_variable_warning(ptr);
 }
Exemplo n.º 21
0
Arquivo: main.cpp Projeto: CCJY/coliru
int main()
{
    someCoolClass c(10);
    std::cout << std::uppercase << std::hex << c << std::endl;
}
Exemplo n.º 22
0
int main() {

	typedef std::vector<argos::CPrimitive2*> TChildren;
	typedef std::vector<argos::CPrimitive2*>::iterator TIteratorChildren;

   //argos::CRectangle r(argos::CVector2(0.5, -1.0), argos::CRadians::PI_OVER_TWO, 2.0, 1.0);
	argos::CRectangle r(argos::CVector2(0.5, -0.5), argos::CRadians::PI, 2.0, 1.0);

	argos::CRectangle r2(argos::CVector2(-1, -0.5), argos::CRadians::ZERO, 2.0, 1.0);
  argos::CCircle c(argos::CVector2(0.5, -2.5), 0.5);
   argos::CCircle circle(argos::CVector2(0.5, 1.3), 1.0);
   argos::CRectangle rect(argos::CVector2(0.5, 1.5), argos::CRadians::PI_OVER_THREE, 2.0, 1.0);
   argos::CCompound compound(argos::CVector2(0.5, -1.0));
   compound.AddChild(&r);
   compound.AddChild(&r2);
   compound.AddChild(&c);

   TChildren m_tChildren = compound.GetChildren();

   //compound.Rotate(argos::CRadians::PI/9);
   //compound.AddChild(&c);


   for (counter = 0; counter < 20; ++counter){
	   //r.Intersects(idRC, c);
	   //c.Intersects(idCR, r);

//	   circle.Intersects(idCircleCompound, r);
//	   r.Intersects(idCompoundCircle, circle);

	   rect.Intersects(idCircleCompound, r);
	   r.Intersects(idCompoundCircle, rect);


	   //rect.Intersects(idCircleCompound, r);
	   //r.Intersects(idCompoundCircle, rect);
	   //rect.Intersects(idCircleCompound, compound);
	   //compound.Intersects(idCompoundCircle, rect);

	   //circle.Intersects(idCircleCompound, compound);
	   //compound.Intersects(idCompoundCircle, circle);

	   //r.Gnuplot();


	   StartGnuplot();

	   rect.Gnuplot();
	   r.Gnuplot();
	   //circle.Gnuplot();
	   //compound.Gnuplot();

	   StopGnuplot();
	   std::cin.get();
	   //compound.Rotate(argos::CRadians::PI/9);
	   r.Rotate(argos::CRadians::PI/9);

   }





}
Exemplo n.º 23
0
void LLGAnalysis::FinishRun() {

    
    TCanvas c("","");
    for( map<string,TH1D>::iterator itr_h = _histograms1D.begin(); itr_h != _histograms1D.end(); ++itr_h ) {
        (*itr_h).second.Draw( (_histograms1DDrawOptions.at((*itr_h).first)).c_str() );
        for( vector<string>::iterator itr_f = _plotFormats.begin(); itr_f != _plotFormats.end(); ++itr_f ) {
            string thisPlotName = (*itr_h).first + (*itr_f);
            c.Print( thisPlotName.c_str() );
        }
    }
    
    for( map<string,TH2D>::iterator itr_h = _histograms2D.begin(); itr_h != _histograms2D.end(); ++itr_h ) {
        (*itr_h).second.Draw( (_histograms2DDrawOptions.at((*itr_h).first)).c_str()  );
        for( vector<string>::iterator itr_f = _plotFormats.begin(); itr_f != _plotFormats.end(); ++itr_f ) {
            string thisPlotName = (*itr_h).first + (*itr_f);
            c.Print( thisPlotName.c_str() );
        }
    }
    
    MakeEfficiencyPlot( _histograms1D.at("MET_HLT_PFMET170_NoiseCleaned_v1"), _histograms1D.at("MET_allEvents"), &c, "HLT_PFMET170_NoiseCleaned_v1" ); 
    MakeEfficiencyPlot( _histograms1D.at("jet1_pt_HLT_PFJet260_v1"), _histograms1D.at("jet1_pt_allEvents"), &c, "HLT_PFJet260_v1" ); 

    cout << endl << "RECO CUT FLOW " << endl;
    cout << "-----------------------------" << endl;
    for( map<string,int>::iterator itr = _cutFlow.begin(); itr != _cutFlow.end(); ++itr ) {
        cout << (*itr).first << " " << (*itr).second * evtWeight << endl;
    }

    TFile *fHistOutput = new TFile( outputHistos.c_str() , "RECREATE" );
    for( map<string,TH1D>::iterator itr_h = _histograms1D.begin(); itr_h != _histograms1D.end(); ++itr_h ) {
      (*itr_h).second.Write();
    }
    for( map<string,TH2D>::iterator itr_h = _histograms2D.begin(); itr_h != _histograms2D.end(); ++itr_h ) {
      (*itr_h).second.Write();
    }
    fHistOutput->Close();

    gDirectory = _outputFile;
    _outputTree->Write();
    _outputFile->Close();

    /* 
    cout << "PRINTING 2D OPTIMISATION MATRIX : " << endl;
    for( unsigned int i = 0; i < _yields2DOptimisation.size(); ++i ) {
      for( unsigned int j = 0; j < _yields2DOptimisation.at(i).size(); ++j ) {
        cout << std::setw(8) << _yields2DOptimisation.at(i).at(j) << " ";
      }
      cout << endl;
    }
    */

    delete _inputTree;
    delete recoJet_pt;
    delete recoJet_phi;
    delete recoJet_eta;
    delete recoJet_btag_combinedInclusiveSecondaryVertexV2BJetTags;
    delete recoJet_btag_jetBProbabilityBJetTags;
    delete recoJet_btag_jetProbabilityBJetTags;
    delete recoJet_btag_trackCountingHighPurBJetTags;
    delete recoJet_btag_trackCountingHighEffBJetTags;
    delete recoJet_isLeptonLike;
    delete recoJet_vertex_x;
    delete recoJet_vertex_y;
    delete recoJet_vertex_z;
    delete muon_px;
    delete muon_py;
    delete muon_pz;
    delete muon_phi;
    delete muon_eta;
    delete muon_iso;
    delete muon_isTightMuon;
    delete muon_isLooseMuon;
    delete electron_px;
    delete electron_py;
    delete electron_pz;
    delete electron_phi;
    delete electron_eta;
    delete electron_iso;
    delete electron_isVeto;
    delete electron_isLoose;
    delete electron_isMedium;
    delete electron_isTight;
    delete electron_isHEEP;
    delete triggerBits;
    delete triggerNames;
    /*
    delete recoJet_constVertex_x;
    delete recoJet_constVertex_y;
    delete recoJet_constVertex_z;
    delete recoJet_const_pt;
    delete recoJet_const_closestVertex_dxy;
    delete recoJet_const_closestVertex_dz;
    delete recoJet_const_closestVertex_d;
    delete recoJet_const_charge;
    */
    delete vertex_x;
    delete vertex_y;
    delete vertex_z;
    delete vertex_dx;
    delete vertex_dy;
    delete vertex_dz;
    delete vertex_nTracks;
    delete vertex_pt;
    delete vertex_ndof;
    delete secVertex_x;
    delete secVertex_y;
    delete secVertex_z;
    delete secVertex_dx;
    delete secVertex_dy;
    delete secVertex_dz;
    delete secVertex_ndof;
    delete secVertex_pt;

} 
Exemplo n.º 24
0
/** Creates a mesh for this graph. The mesh is not added to a scene node and
 *  is stored in m_mesh.
 *  \param show_invisble  If true, also create a mesh for parts of the
 *         driveline that are invisible.
 *  \param enable_transparency Enable alpha blending to make the mesh
 *         semi transparent.
 *  \param track_color Colour of the actual quads.
 *  \param lap_color If defined, show the lap counting line in that colour.
 */
void QuadGraph::createMesh(bool show_invisible,
                           bool enable_transparency,
                           const video::SColor *track_color,
                           const video::SColor *lap_color)
{
    // The debug track will not be lighted or culled.
    video::SMaterial m;
    m.BackfaceCulling  = false;
    m.Lighting         = false;
    if(enable_transparency)
        m.MaterialType = video::EMT_TRANSPARENT_ALPHA_CHANNEL;
    m_mesh             = irr_driver->createQuadMesh(&m);
    m_mesh_buffer      = m_mesh->getMeshBuffer(0);
    assert(m_mesh_buffer->getVertexType()==video::EVT_STANDARD);

    // Count the number of quads to display (some quads might be invisible
    unsigned int  n = 0;
    for(unsigned int i=0; i<m_all_nodes.size(); i++)
    {
        if(show_invisible || !m_all_nodes[i]->getQuad().isInvisible())
            n++;
    }

    // Four vertices for each of the n-1 remaining quads
    video::S3DVertex *new_v = new video::S3DVertex[4*n];
    // Each quad consists of 2 triangles with 3 elements, so
    // we need 2*3 indices for each quad.
    irr::u16         *ind   = new irr::u16[6*n];
    video::SColor     c(255, 255, 0, 0);

    if(track_color)
        c = *track_color;

    // Now add all quads
    int i=0;
    for(unsigned int count=0; count<m_all_nodes.size(); count++)
    {
        // Ignore invisible quads
        if(!show_invisible && m_all_nodes[count]->getQuad().isInvisible())
            continue;
        // Swap the colours from red to blue and back
        if(!track_color)
        {
            c.setRed ((i%2) ? 255 : 0);
            c.setBlue((i%2) ? 0 : 255);
        }
        // Transfer the 4 points of the current quad to the list of vertices
        m_all_nodes[count]->getQuad().getVertices(new_v+4*i, c);

        // Set up the indices for the triangles
        // (note, afaik with opengl we could use quads directly, but the code
        // would not be portable to directx anymore).
        ind[6*i  ] = 4*i+2;  // First triangle: vertex 0, 1, 2
        ind[6*i+1] = 4*i+1;
        ind[6*i+2] = 4*i;
        ind[6*i+3] = 4*i+3;  // second triangle: vertex 0, 1, 3
        ind[6*i+4] = 4*i+2;
        ind[6*i+5] = 4*i;
        i++;
    }   // for i=1; i<QuadSet::get()

    m_mesh_buffer->append(new_v, n*4, ind, n*6);

    if(lap_color)
    {
        video::S3DVertex lap_v[4];
        irr::u16         lap_ind[6];
        video::SColor     c(128, 255, 0, 0);
        m_all_nodes[0]->getQuad().getVertices(lap_v, *lap_color);

        // Now scale the length (distance between vertix 0 and 3
        // and between 1 and 2) to be 'length':
        Vec3 bb_min, bb_max;
        QuadSet::get()->getBoundingBox(&bb_min, &bb_max);
        // Length of the lap line about 3% of the 'height'
        // of the track.
        const float length=(bb_max.getZ()-bb_min.getZ())*0.03f;

        core::vector3df dl = lap_v[3].Pos-lap_v[0].Pos;
        float ll2 = dl.getLengthSQ();
        if(ll2<0.001)
            lap_v[3].Pos = lap_v[0].Pos+core::vector3df(0, 0, 1);
        else
            lap_v[3].Pos = lap_v[0].Pos+dl*length/sqrt(ll2);

        core::vector3df dr = lap_v[2].Pos-lap_v[1].Pos;
        float lr2 = dr.getLengthSQ();
        if(lr2<0.001)
            lap_v[2].Pos = lap_v[1].Pos+core::vector3df(0, 0, 1);
        else
            lap_v[2].Pos = lap_v[1].Pos+dr*length/sqrt(lr2);
        lap_ind[0] = 2;
        lap_ind[1] = 1;
        lap_ind[2] = 0;
        lap_ind[3] = 3;
        lap_ind[4] = 2;
        lap_ind[5] = 0;
        // Set it a bit higher to avoid issued with z fighting,
        // i.e. part of the lap line might not be visible.
        for(unsigned int i=0; i<4; i++)
            lap_v[i].Pos.Y += 0.1f;
#ifndef USE_TEXTURED_LINE
        m_mesh_buffer->append(lap_v, 4, lap_ind, 6);
#else
        lap_v[0].TCoords = core::vector2df(0,0);
        lap_v[1].TCoords = core::vector2df(3,0);
        lap_v[2].TCoords = core::vector2df(3,1);
        lap_v[3].TCoords = core::vector2df(0,1);
        m_mesh_buffer->append(lap_v, 4, lap_ind, 6);
        video::SMaterial &m = m_mesh_buffer->getMaterial();
        video::ITexture *t = irr_driver->getTexture("chess.png");
        m.setTexture(0, t);
#endif
    }

    // Instead of setting the bounding boxes, we could just disable culling,
    // since the debug track should always be drawn.
    //m_node->setAutomaticCulling(scene::EAC_OFF);
    m_mesh_buffer->recalculateBoundingBox();
    m_mesh->setBoundingBox(m_mesh_buffer->getBoundingBox());

    delete[] ind;
    delete[] new_v;
}   // createMesh
Exemplo n.º 25
0
VectorBase ADFun<Base>::ForTwo(
    const VectorBase   &x,
    const VectorSize_t &j,
    const VectorSize_t &k)
{   size_t i;
    size_t j1;
    size_t k1;
    size_t l;

    size_t n = Domain();
    size_t m = Range();
    size_t p = j.size();

    // check VectorBase is Simple Vector class with Base type elements
    CheckSimpleVector<Base, VectorBase>();

    // check VectorSize_t is Simple Vector class with size_t elements
    CheckSimpleVector<size_t, VectorSize_t>();

    CPPAD_ASSERT_KNOWN(
        x.size() == n,
        "ForTwo: Length of x not equal domain dimension for f."
    );
    CPPAD_ASSERT_KNOWN(
        j.size() == k.size(),
        "ForTwo: Lenght of the j and k vectors are not equal."
    );
    // point at which we are evaluating the second partials
    Forward(0, x);


    // dimension the return value
    VectorBase ddy(m * p);

    // allocate memory to hold all possible diagonal Taylor coefficients
    // (for large sparse cases, this is not efficient)
    VectorBase D(m * n);

    // boolean flag for which diagonal coefficients are computed
    CppAD::vector<bool> c(n);
    for(j1 = 0; j1 < n; j1++)
        c[j1] = false;

    // direction vector in argument space
    VectorBase dx(n);
    for(j1 = 0; j1 < n; j1++)
        dx[j1] = Base(0);

    // result vector in range space
    VectorBase dy(m);

    // compute the diagonal coefficients that are needed
    for(l = 0; l < p; l++)
    {   j1 = j[l];
        k1 = k[l];
        CPPAD_ASSERT_KNOWN(
            j1 < n,
            "ForTwo: an element of j not less than domain dimension for f."
        );
        CPPAD_ASSERT_KNOWN(
            k1 < n,
            "ForTwo: an element of k not less than domain dimension for f."
        );
        size_t count = 2;
        while(count)
        {   count--;
            if( ! c[j1] )
            {   // diagonal term in j1 direction
                c[j1]  = true;
                dx[j1] = Base(1);
                Forward(1, dx);

                dx[j1] = Base(0);
                dy     = Forward(2, dx);
                for(i = 0; i < m; i++)
                    D[i * n + j1 ] = dy[i];
            }
            j1 = k1;
        }
    }
    // compute all the requested cross partials
    for(l = 0; l < p; l++)
    {   j1 = j[l];
        k1 = k[l];
        if( j1 == k1 )
        {   for(i = 0; i < m; i++)
                ddy[i * p + l] = Base(2) * D[i * n + j1];
        }
        else
        {
            // cross term in j1 and k1 directions
            dx[j1] = Base(1);
            dx[k1] = Base(1);
            Forward(1, dx);

            dx[j1] = Base(0);
            dx[k1] = Base(0);
            dy = Forward(2, dx);

            // place result in return value
            for(i = 0; i < m; i++)
                ddy[i * p + l] = dy[i] - D[i*n+j1] - D[i*n+k1];

        }
    }
    return ddy;
}
Exemplo n.º 26
0
  Rational operator -(Rational a, Rational b) {
  	Rational c(a.num*b.den - b.num*a.den, 
  		a.den*b.den);

  	return c;
  }
Exemplo n.º 27
0
	bool utp_socket_manager::incoming_packet(error_code const& ec, udp::endpoint const& ep
			, char const* p, int size)
	{
//		UTP_LOGV("incoming packet size:%d\n", size);

		if (size < int(sizeof(utp_header))) return false;

		utp_header const* ph = (utp_header*)p;

//		UTP_LOGV("incoming packet version:%d\n", int(ph->get_version()));

		if (ph->get_version() != 1) return false;

		const ptime receive_time = time_now_hires();
		
		// parse out connection ID and look for existing
		// connections. If found, forward to the utp_stream.
		boost::uint16_t id = ph->connection_id;

		// first test to see if it's the same socket as last time
		// in most cases it is
		if (m_last_socket
			&& utp_match(m_last_socket, ep, id))
		{
			return utp_incoming_packet(m_last_socket, p, size, ep, receive_time);
		}

		std::pair<socket_map_t::iterator, socket_map_t::iterator> r =
			m_utp_sockets.equal_range(id);

		for (; r.first != r.second; ++r.first)
		{
			if (!utp_match(r.first->second, ep, id)) continue;
			bool ret = utp_incoming_packet(r.first->second, p, size, ep, receive_time);
			if (ret) m_last_socket = r.first->second;
			return ret;
		}

//		UTP_LOGV("incoming packet id:%d source:%s\n", id, print_endpoint(ep).c_str());

		if (!m_sett.enable_incoming_utp)
			return false;

		// if not found, see if it's a SYN packet, if it is,
		// create a new utp_stream
		if (ph->get_type() == ST_SYN)
		{
			// possible SYN flood. Just ignore
			if (m_utp_sockets.size() > m_sett.connections_limit * 2)
				return false;

//			UTP_LOGV("not found, new connection id:%d\n", m_new_connection);

			boost::shared_ptr<socket_type> c(new (std::nothrow) socket_type(m_sock.get_io_service()));
			if (!c) return false;

			TORRENT_ASSERT(m_new_connection == -1);
			// create the new socket with this ID
			m_new_connection = id;

			instantiate_connection(m_sock.get_io_service(), proxy_settings(), *c, 0, this);
			utp_stream* str = c->get<utp_stream>();
			TORRENT_ASSERT(str);
			int link_mtu, utp_mtu;
			mtu_for_dest(ep.address(), link_mtu, utp_mtu);
			utp_init_mtu(str->get_impl(), link_mtu, utp_mtu);
			bool ret = utp_incoming_packet(str->get_impl(), p, size, ep, receive_time);
			if (!ret) return false;
			m_cb(c);
			// the connection most likely changed its connection ID here
			// we need to move it to the correct ID
			return true;
		}

		if (ph->get_type() == ST_RESET) return false;

		// #error send reset

		return false;
	}
Exemplo n.º 28
0
  Rational operator *(Rational a, Rational b) {
  	Rational c(a.num*b.num,	a.den*b.den);

  	return c;
  }
Exemplo n.º 29
0
int main()
{
    {
        typedef std::unordered_set<int,
                                   test_hash<std::hash<int> >,
                                   test_compare<std::equal_to<int> >,
                                   test_allocator<int>
                                   > C;
        typedef int P;
        P a[] =
        {
            P(1),
            P(2),
            P(3),
            P(4),
            P(1),
            P(2)
        };
        C c(input_iterator<P*>(a), input_iterator<P*>(a + sizeof(a)/sizeof(a[0])));
        assert(c.bucket_count() >= 5);
        assert(c.size() == 4);
        assert(c.count(1) == 1);
        assert(c.count(2) == 1);
        assert(c.count(3) == 1);
        assert(c.count(4) == 1);
        assert(c.hash_function() == test_hash<std::hash<int> >());
        assert(c.key_eq() == test_compare<std::equal_to<int> >());
        assert(c.get_allocator() == test_allocator<int>());
        assert(!c.empty());
        assert(std::distance(c.begin(), c.end()) == c.size());
        assert(std::distance(c.cbegin(), c.cend()) == c.size());
        assert(fabs(c.load_factor() - (float)c.size()/c.bucket_count()) < FLT_EPSILON);
        assert(c.max_load_factor() == 1);
    }
#if __cplusplus >= 201103L
    {
        typedef std::unordered_set<int,
                                   test_hash<std::hash<int> >,
                                   test_compare<std::equal_to<int> >,
                                   min_allocator<int>
                                   > C;
        typedef int P;
        P a[] =
        {
            P(1),
            P(2),
            P(3),
            P(4),
            P(1),
            P(2)
        };
        C c(input_iterator<P*>(a), input_iterator<P*>(a + sizeof(a)/sizeof(a[0])));
        assert(c.bucket_count() >= 5);
        assert(c.size() == 4);
        assert(c.count(1) == 1);
        assert(c.count(2) == 1);
        assert(c.count(3) == 1);
        assert(c.count(4) == 1);
        assert(c.hash_function() == test_hash<std::hash<int> >());
        assert(c.key_eq() == test_compare<std::equal_to<int> >());
        assert(c.get_allocator() == min_allocator<int>());
        assert(!c.empty());
        assert(std::distance(c.begin(), c.end()) == c.size());
        assert(std::distance(c.cbegin(), c.cend()) == c.size());
        assert(fabs(c.load_factor() - (float)c.size()/c.bucket_count()) < FLT_EPSILON);
        assert(c.max_load_factor() == 1);
    }
#if _LIBCPP_STD_VER > 11
    {
        typedef int T;
        typedef test_hash<std::hash<T>> HF;
        typedef test_compare<std::equal_to<T>> Comp;
        typedef test_allocator<T> A;
        typedef std::unordered_set<T, HF, Comp, A> C;
        T arr[] =
        {
            T(1),
            T(2),
            T(3),
            T(4),
            T(1),
            T(2)
        };
        A a(42);
        C c(input_iterator<T*>(arr), input_iterator<T*>(arr + sizeof(arr)/sizeof(arr[0])), 12, a);
        assert(c.bucket_count() >= 12);
        assert(c.size() == 4);
        assert(c.count(1) == 1);
        assert(c.count(2) == 1);
        assert(c.count(3) == 1);
        assert(c.count(4) == 1);
        assert(c.hash_function() == HF());
        assert(c.key_eq() == Comp());
        assert(c.get_allocator() == a);
        assert(!(c.get_allocator() == A()));
        assert(!c.empty());
        assert(std::distance(c.begin(), c.end()) == c.size());
        assert(std::distance(c.cbegin(), c.cend()) == c.size());
        assert(fabs(c.load_factor() - (float)c.size()/c.bucket_count()) < FLT_EPSILON);
        assert(c.max_load_factor() == 1);
    }
    {
        typedef int T;
        typedef test_hash<std::hash<T>> HF;
        typedef test_compare<std::equal_to<T>> Comp;
        typedef test_allocator<T> A;
        typedef std::unordered_set<T, HF, Comp, A> C;
        T arr[] =
        {
            T(1),
            T(2),
            T(3),
            T(4),
            T(1),
            T(2)
        };
        HF hf(43);
        A a(42);
        C c(input_iterator<T*>(arr), input_iterator<T*>(arr + sizeof(arr)/sizeof(arr[0])), 16, hf, a);
        assert(c.bucket_count() >= 16);
        assert(c.size() == 4);
        assert(c.count(1) == 1);
        assert(c.count(2) == 1);
        assert(c.count(3) == 1);
        assert(c.count(4) == 1);
        assert(c.hash_function() == hf);
        assert(!(c.hash_function() == HF()));
        assert(c.key_eq() == Comp());
        assert(c.get_allocator() == a);
        assert(!(c.get_allocator() == A()));
        assert(!c.empty());
        assert(std::distance(c.begin(), c.end()) == c.size());
        assert(std::distance(c.cbegin(), c.cend()) == c.size());
        assert(fabs(c.load_factor() - (float)c.size()/c.bucket_count()) < FLT_EPSILON);
        assert(c.max_load_factor() == 1);
    }

#endif
#endif
}
Exemplo n.º 30
0
int main() {
	DA* pa = 0;
	C c(pa);
}