void LineBucket::addGeometry(const std::vector<Coordinate>& vertices) {
    const GLsizei len = [&vertices] {
        GLsizei l = static_cast<GLsizei>(vertices.size());
        // If the line has duplicate vertices at the end, adjust length to remove them.
        while (l > 2 && vertices[l - 1] == vertices[l - 2]) {
            l--;
        }
        return l;
    }();

    if (len < 2) {
        // fprintf(stderr, "a line must have at least two vertices\n");
        return;
    }

    const float miterLimit = layout.join == JoinType::Bevel ? 1.05f : float(layout.miterLimit);

    const Coordinate firstVertex = vertices.front();
    const Coordinate lastVertex = vertices[len - 1];
    const bool closed = firstVertex == lastVertex;

    if (len == 2 && closed) {
        // fprintf(stderr, "a line may not have coincident points\n");
        return;
    }

    const CapType beginCap = layout.cap;
    const CapType endCap = closed ? CapType::Butt : CapType(layout.cap);

    int8_t flip = 1;
    double distance = 0;
    bool startOfLine = true;
    Coordinate currentVertex = Coordinate::null(), prevVertex = Coordinate::null(),
               nextVertex = Coordinate::null();
    vec2<double> prevNormal = vec2<double>::null(), nextNormal = vec2<double>::null();

    // the last three vertices added
    e1 = e2 = e3 = -1;

    if (closed) {
        currentVertex = vertices[len - 2];
        nextNormal = util::perp(util::unit(vec2<double>(firstVertex - currentVertex)));
    }

    const GLint startVertex = vertexBuffer.index();
    std::vector<TriangleElement> triangleStore;

    for (GLsizei i = 0; i < len; ++i) {
        if (closed && i == len - 1) {
            // if the line is closed, we treat the last vertex like the first
            nextVertex = vertices[1];
        } else if (i + 1 < len) {
            // just the next vertex
            nextVertex = vertices[i + 1];
        } else {
            // there is no next vertex
            nextVertex = Coordinate::null();
        }

        // if two consecutive vertices exist, skip the current one
        if (nextVertex && vertices[i] == nextVertex) {
            continue;
        }

        if (nextNormal) {
            prevNormal = nextNormal;
        }
        if (currentVertex) {
            prevVertex = currentVertex;
        }

        currentVertex = vertices[i];

        // Calculate how far along the line the currentVertex is
        if (prevVertex)
            distance += util::dist<double>(currentVertex, prevVertex);

        // Calculate the normal towards the next vertex in this line. In case
        // there is no next vertex, pretend that the line is continuing straight,
        // meaning that we are just using the previous normal.
        nextNormal = nextVertex ? util::perp(util::unit(vec2<double>(nextVertex - currentVertex)))
                                : prevNormal;

        // If we still don't have a previous normal, this is the beginning of a
        // non-closed line, so we're doing a straight "join".
        if (!prevNormal) {
            prevNormal = nextNormal;
        }

        // Determine the normal of the join extrusion. It is the angle bisector
        // of the segments between the previous line and the next line.
        vec2<double> joinNormal = util::unit(prevNormal + nextNormal);

        /*  joinNormal     prevNormal
         *             ↖      ↑
         *                .________. prevVertex
         *                |
         * nextNormal  ←  |  currentVertex
         *                |
         *     nextVertex !
         *
         */

        // Calculate the length of the miter (the ratio of the miter to the width).
        // Find the cosine of the angle between the next and join normals
        // using dot product. The inverse of that is the miter length.
        const float cosHalfAngle = joinNormal.x * nextNormal.x + joinNormal.y * nextNormal.y;
        const float miterLength = cosHalfAngle != 0 ? 1 / cosHalfAngle: 1;

        // The join if a middle vertex, otherwise the cap
        const bool middleVertex = prevVertex && nextVertex;
        JoinType currentJoin = layout.join;
        const CapType currentCap = nextVertex ? beginCap : endCap;

        if (middleVertex) {
            if (currentJoin == JoinType::Round) {
                if (miterLength < layout.roundLimit) {
                    currentJoin = JoinType::Miter;
                } else if (miterLength <= 2) {
                    currentJoin = JoinType::FakeRound;
                }
            }

            if (currentJoin == JoinType::Miter && miterLength > miterLimit) {
                currentJoin = JoinType::Bevel;
            }

            if (currentJoin == JoinType::Bevel) {
                // The maximum extrude length is 128 / 63 = 2 times the width of the line
                // so if miterLength >= 2 we need to draw a different type of bevel where.
                if (miterLength > 2) {
                    currentJoin = JoinType::FlipBevel;
                }

                // If the miterLength is really small and the line bevel wouldn't be visible,
                // just draw a miter join to save a triangle.
                if (miterLength < miterLimit) {
                    currentJoin = JoinType::Miter;
                }
            }
        }

        if (middleVertex && currentJoin == JoinType::Miter) {
            joinNormal = joinNormal * miterLength;
            addCurrentVertex(currentVertex, flip, distance, joinNormal, 0, 0, false, startVertex,
                             triangleStore);

        } else if (middleVertex && currentJoin == JoinType::FlipBevel) {
            // miter is too big, flip the direction to make a beveled join

            if (miterLength > 100) {
                // Almost parallel lines
                joinNormal = nextNormal;
            } else {
                const float direction = prevNormal.x * nextNormal.y - prevNormal.y * nextNormal.x > 0 ? -1 : 1;
                const float bevelLength = miterLength * util::mag(prevNormal + nextNormal) /
                                          util::mag(prevNormal - nextNormal);
                joinNormal = util::perp(joinNormal) * bevelLength * direction;
            }

            addCurrentVertex(currentVertex, flip, distance, joinNormal, 0, 0, false, startVertex,
                             triangleStore);

            addCurrentVertex(currentVertex, -flip, distance, joinNormal, 0, 0, false, startVertex,
                             triangleStore);
        } else if (middleVertex && (currentJoin == JoinType::Bevel || currentJoin == JoinType::FakeRound)) {
            const bool lineTurnsLeft = flip * (prevNormal.x * nextNormal.y - prevNormal.y * nextNormal.x) > 0;
            const float offset = -std::sqrt(miterLength * miterLength - 1);
            float offsetA;
            float offsetB;

            if (lineTurnsLeft) {
                offsetB = 0;
                offsetA = offset;
            } else {
                offsetA = 0;
                offsetB = offset;
            }

            // Close previous segement with bevel
            if (!startOfLine) {
                addCurrentVertex(currentVertex, flip, distance, prevNormal, offsetA, offsetB, false,
                                 startVertex, triangleStore);
            }

            if (currentJoin == JoinType::FakeRound) {
                // The join angle is sharp enough that a round join would be visible.
                // Bevel joins fill the gap between segments with a single pie slice triangle.
                // Create a round join by adding multiple pie slices. The join isn't actually round, but
                // it looks like it is at the sizes we render lines at.

                // Add more triangles for sharper angles.
                // This math is just a good enough approximation. It isn't "correct".
                const int n = std::floor((0.5 - (cosHalfAngle - 0.5)) * 8);

                for (int m = 0; m < n; m++) {
                    auto approxFractionalJoinNormal = util::unit(nextNormal * ((m + 1.0f) / (n + 1.0f)) + prevNormal);
                    addPieSliceVertex(currentVertex, flip, distance, approxFractionalJoinNormal, lineTurnsLeft, startVertex, triangleStore);
                }

                addPieSliceVertex(currentVertex, flip, distance, joinNormal, lineTurnsLeft, startVertex, triangleStore);

                for (int k = n - 1; k >= 0; k--) {
                    auto approxFractionalJoinNormal = util::unit(prevNormal * ((k + 1.0f) / (n + 1.0f)) + nextNormal);
                    addPieSliceVertex(currentVertex, flip, distance, approxFractionalJoinNormal, lineTurnsLeft, startVertex, triangleStore);
                }
            }

            // Start next segment
            if (nextVertex) {
                addCurrentVertex(currentVertex, flip, distance, nextNormal, -offsetA, -offsetB,
                                 false, startVertex, triangleStore);
            }

        } else if (!middleVertex && currentCap == CapType::Butt) {
            if (!startOfLine) {
                // Close previous segment with a butt
                addCurrentVertex(currentVertex, flip, distance, prevNormal, 0, 0, false,
                                 startVertex, triangleStore);
            }

            // Start next segment with a butt
            if (nextVertex) {
                addCurrentVertex(currentVertex, flip, distance, nextNormal, 0, 0, false,
                                 startVertex, triangleStore);
            }

        } else if (!middleVertex && currentCap == CapType::Square) {
            if (!startOfLine) {
                // Close previous segment with a square cap
                addCurrentVertex(currentVertex, flip, distance, prevNormal, 1, 1, false,
                                 startVertex, triangleStore);

                // The segment is done. Unset vertices to disconnect segments.
                e1 = e2 = -1;
                flip = 1;
            }

            // Start next segment
            if (nextVertex) {
                addCurrentVertex(currentVertex, flip, distance, nextNormal, -1, -1, false,
                                 startVertex, triangleStore);
            }

        } else if (middleVertex ? currentJoin == JoinType::Round : currentCap == CapType::Round) {
            if (!startOfLine) {
                // Close previous segment with a butt
                addCurrentVertex(currentVertex, flip, distance, prevNormal, 0, 0, false,
                                 startVertex, triangleStore);

                // Add round cap or linejoin at end of segment
                addCurrentVertex(currentVertex, flip, distance, prevNormal, 1, 1, true, startVertex,
                                 triangleStore);

                // The segment is done. Unset vertices to disconnect segments.
                e1 = e2 = -1;
                flip = 1;
            }

            // Start next segment with a butt
            if (nextVertex) {
                // Add round cap before first segment
                addCurrentVertex(currentVertex, flip, distance, nextNormal, -1, -1, true,
                                 startVertex, triangleStore);

                addCurrentVertex(currentVertex, flip, distance, nextNormal, 0, 0, false,
                                 startVertex, triangleStore);
            }
        }

        startOfLine = false;
    }

    const GLsizei endVertex = vertexBuffer.index();
    const GLsizei vertexCount = endVertex - startVertex;

    // Store the triangle/line groups.
    {
        if (triangleGroups.empty() || (triangleGroups.back()->vertex_length + vertexCount > 65535)) {
            // Move to a new group because the old one can't hold the geometry.
            triangleGroups.emplace_back(std::make_unique<TriangleGroup>());
        }

        assert(triangleGroups.back());
        auto& group = *triangleGroups.back();
        for (const auto& triangle : triangleStore) {
            triangleElementsBuffer.add(group.vertex_length + triangle.a,
                                       group.vertex_length + triangle.b,
                                       group.vertex_length + triangle.c);
        }

        group.vertex_length += vertexCount;
        group.elements_length += triangleStore.size();
    }
}
bool Solver(const CScript& scriptPubKey, txnouttype& typeRet, std::vector<std::vector<unsigned char> >& vSolutionsRet)
{
    // Templates
    static std::multimap<txnouttype, CScript> mTemplates;
    if (mTemplates.empty())
    {
        // Standard tx, sender provides pubkey, receiver adds signature
        mTemplates.insert(std::make_pair(TX_PUBKEY, CScript() << OP_PUBKEY << OP_CHECKSIG));

        // Bitcoin address tx, sender provides hash of pubkey, receiver provides signature and pubkey
        mTemplates.insert(std::make_pair(TX_PUBKEYHASH, CScript() << OP_DUP << OP_HASH160 << OP_PUBKEYHASH << OP_EQUALVERIFY << OP_CHECKSIG));

        // Sender provides N pubkeys, receivers provides M signatures
        mTemplates.insert(std::make_pair(TX_MULTISIG, CScript() << OP_SMALLINTEGER << OP_PUBKEYS << OP_SMALLINTEGER << OP_CHECKMULTISIG));
    }

    vSolutionsRet.clear();

    // If we have a name script, strip the prefix
    const CNameScript nameOp(scriptPubKey);
    const CScript& script1 = nameOp.getAddress();

    // Shortcut for pay-to-script-hash, which are more constrained than the other types:
    // it is always OP_HASH160 20 [20 byte hash] OP_EQUAL
    if (script1.IsPayToScriptHash(false))
    {
        typeRet = TX_SCRIPTHASH;
        std::vector<unsigned char> hashBytes(script1.begin()+2, script1.begin()+22);
        vSolutionsRet.push_back(hashBytes);
        return true;
    }

    int witnessversion;
    std::vector<unsigned char> witnessprogram;
    if (scriptPubKey.IsWitnessProgram(witnessversion, witnessprogram)) {
        if (witnessversion == 0 && witnessprogram.size() == 20) {
            typeRet = TX_WITNESS_V0_KEYHASH;
            vSolutionsRet.push_back(witnessprogram);
            return true;
        }
        if (witnessversion == 0 && witnessprogram.size() == 32) {
            typeRet = TX_WITNESS_V0_SCRIPTHASH;
            vSolutionsRet.push_back(witnessprogram);
            return true;
        }
        if (witnessversion != 0) {
            typeRet = TX_WITNESS_UNKNOWN;
            vSolutionsRet.push_back(std::vector<unsigned char>{(unsigned char)witnessversion});
            vSolutionsRet.push_back(std::move(witnessprogram));
            return true;
        }
        return false;
    }

    // Provably prunable, data-carrying output
    //
    // So long as script passes the IsUnspendable() test and all but the first
    // byte passes the IsPushOnly() test we don't care what exactly is in the
    // script.
    if (scriptPubKey.size() >= 1 && scriptPubKey[0] == OP_RETURN && scriptPubKey.IsPushOnly(scriptPubKey.begin()+1)) {
        typeRet = TX_NULL_DATA;
        return true;
    }

    // Scan templates
    for (const std::pair<txnouttype, CScript>& tplate : mTemplates)
    {
        const CScript& script2 = tplate.second;
        vSolutionsRet.clear();

        opcodetype opcode1, opcode2;
        std::vector<unsigned char> vch1, vch2;

        // Compare
        CScript::const_iterator pc1 = script1.begin();
        CScript::const_iterator pc2 = script2.begin();
        while (true)
        {
            if (pc1 == script1.end() && pc2 == script2.end())
            {
                // Found a match
                typeRet = tplate.first;
                if (typeRet == TX_MULTISIG)
                {
                    // Additional checks for TX_MULTISIG:
                    unsigned char m = vSolutionsRet.front()[0];
                    unsigned char n = vSolutionsRet.back()[0];
                    if (m < 1 || n < 1 || m > n || vSolutionsRet.size()-2 != n)
                        return false;
                }
                return true;
            }
            if (!script1.GetOp(pc1, opcode1, vch1))
                break;
            if (!script2.GetOp(pc2, opcode2, vch2))
                break;

            // Template matching opcodes:
            if (opcode2 == OP_PUBKEYS)
            {
                while (vch1.size() >= 33 && vch1.size() <= 65)
                {
                    vSolutionsRet.push_back(vch1);
                    if (!script1.GetOp(pc1, opcode1, vch1))
                        break;
                }
                if (!script2.GetOp(pc2, opcode2, vch2))
                    break;
                // Normal situation is to fall through
                // to other if/else statements
            }

            if (opcode2 == OP_PUBKEY)
            {
                if (vch1.size() < 33 || vch1.size() > 65)
                    break;
                vSolutionsRet.push_back(vch1);
            }
            else if (opcode2 == OP_PUBKEYHASH)
            {
                if (vch1.size() != sizeof(uint160))
                    break;
                vSolutionsRet.push_back(vch1);
            }
            else if (opcode2 == OP_SMALLINTEGER)
            {   // Single-byte small integer pushed onto vSolutions
                if (opcode1 == OP_0 ||
                    (opcode1 >= OP_1 && opcode1 <= OP_16))
                {
                    char n = (char)CScript::DecodeOP_N(opcode1);
                    vSolutionsRet.push_back(valtype(1, n));
                }
                else
                    break;
            }
            else if (opcode1 != opcode2 || vch1 != vch2)
            {
                // Others must match exactly
                break;
            }
        }
    }

    vSolutionsRet.clear();
    typeRet = TX_NONSTANDARD;
    return false;
}
std::vector<Point> ImageTransform::getConvexHull(std::vector<Point>& points)
{
	//this function implements the Graham's scan algorithm for finding the convex hull
	//Here is a link to some explanation: http://en.wikipedia.org/wiki/Graham_scan

	std::vector<Point> result;
	result.clear();

	//check to see if we have any points
	if (points.empty()) return result;

	//first find the lowest, leftmost point
	ITHelperFuncs::basePoint = points.front();

	std::vector<Point>::iterator it;

	for(it = points.begin(); it != points.end(); it++)
	{
		if (ITHelperFuncs::basePoint.y >= it->y)
		{
			//check for strict inequality
			if (ITHelperFuncs::basePoint.y > it->y)
			{
				ITHelperFuncs::basePoint = *it;
			}
			else
			{
				if (ITHelperFuncs::basePoint.x > it->x)
				{
					ITHelperFuncs::basePoint = *it;
				}
			}
		}
	}


	//now remove the basePoint

	for (it = points.begin(); it != points.end(); it++)
	{
		if (ITHelperFuncs::basePoint != *it)
		{
			result.push_back(*it);
		}
	}


	std::make_heap(result.begin(), result.end(), ITHelperFuncs::sortPointFunc);
	std::sort_heap(result.begin(), result.end(), ITHelperFuncs::sortPointFunc);

	//now look through the points and if two points have the same angle keep only 
	//the farthest point from the basePoint
	
	points.clear();

	Point current;

	if (result.empty())
	{
		//there is no point left

		//push the basepoint into result and return
		result.push_back(ITHelperFuncs::basePoint);
		return result;
	}

	it = result.begin();

	current = *it;

	points.push_back(current);

	do
	{
		//if the angles are not equal then insert the point in the vector
		if (!ITHelperFuncs::areEqual(current, *it))
		{
			current = *it;
			points.push_back(current);
		}
		it++;
	}while (it != result.end());


	//now walk this set 
	//the points will be kept in a stack

	it = points.begin();

	result.clear();

	result.push_back(ITHelperFuncs::basePoint);

	result.push_back(*it);
	it++;
//	result.push_back(*it);

	while(it != points.end())
	{
		if (info(result[result.size() - 2], result[result.size() - 1], *it) > 0)
		{
			//the new point should be included into the hull
			result.push_back(*it);
			it++;
		}
		else
		{
			//pop a point from the stack
			result.pop_back();
		}
	}

	return result;
}
 static type create(const std::vector<double>& t) { return type(&t.front()); }
Beispiel #5
0
 const mbedtls_ecp_group_id* get() const {
     return &list.front();
 }
Beispiel #6
0
bool Evangelism::init()
{
	if (!Layer::init())
	{
		return false;
	}

	// initialize game elements
	direction = STOP;
	score = 0;

	//sprites creation
	auto backgroundSprite = Sprite::create("background.png");
	priestSprite = Sprite::create("leftpriest.png");
	humanSprite = Sprite::create("human.png");
	
	selSched = schedule_selector(Evangelism::update);
	members.push_back(priestSprite);
	members.front()->setPosition(45, 45);

	//background music
	auto audio = CocosDenshion::SimpleAudioEngine::getInstance();
	audio->preloadBackgroundMusic("bgsong.wma");
	audio->playBackgroundMusic("bgsong.wma");

	// random human spawn
	humanX = 45 * (1 + random() % 18);
	humanY = 45 * (1 + random() % 18);
	humanSprite->setPosition(humanX, humanY);

	//add sprites to this layer
	this->addChild(backgroundSprite, 0);
	this->addChild(members.front(), 1);
	this->addChild(humanSprite, 2);

	//score
	label = Label::createWithSystemFont(std::to_string(score), "Arial", 48);
	label->setAnchorPoint(cocos2d::Vec2(-16, -15));
	this->addChild(label, 3);

	//keyboard controls
	auto eventListener = EventListenerKeyboard::create();

	eventListener->onKeyPressed = [](EventKeyboard::KeyCode keyCode, Event* event) {
		Vec2 loc = event->getCurrentTarget()->getPosition();

		switch (keyCode) {
			case EventKeyboard::KeyCode::KEY_UP_ARROW:
			case EventKeyboard::KeyCode::KEY_W:
				if (direction != DOWN)
					direction = UP;break;
			case EventKeyboard::KeyCode::KEY_DOWN_ARROW:
			case EventKeyboard::KeyCode::KEY_S:
				if (direction != UP)
					direction = DOWN;break;
			case EventKeyboard::KeyCode::KEY_LEFT_ARROW:
			case EventKeyboard::KeyCode::KEY_A:
				if (direction != RIGHT)
					direction = LEFT;break;
			case EventKeyboard::KeyCode::KEY_RIGHT_ARROW:
			case EventKeyboard::KeyCode::KEY_D:
				if (direction != LEFT)
					direction = RIGHT;break;
		}
	};

	this->_eventDispatcher->addEventListenerWithSceneGraphPriority(eventListener, priestSprite);
	this->schedule(selSched, .35);
	return true;
}
Beispiel #7
0
void ReflectInterpreter::InterpretType(const std::vector<Reflect::Element*>& instances, Container* parent, i32 includeFlags, i32 excludeFlags, bool expandPanel)
{
  const Class* typeInfo = instances[0]->GetClass();
  
  // create a panel
  PanelPtr panel = m_Container->GetCanvas()->Create<Panel>(this);

  // parse
  ContainerPtr scriptOutput = m_Container->GetCanvas()->Create<Container>(this);

  tstring typeInfoUI;
  typeInfo->GetProperty( TXT( "UIScript" ), typeInfoUI );
  bool result = Script::Parse(typeInfoUI, this, parent->GetCanvas(), scriptOutput);

  // compute panel label
  tstring labelText;
  if (result)
  {
    V_Control::const_iterator itr = scriptOutput->GetControls().begin();
    V_Control::const_iterator end = scriptOutput->GetControls().end();
    for( ; itr != end; ++itr )
    {
      Label* label = Reflect::ObjectCast<Label>( *itr );
      if (label)
      {
          bool converted = Helium::ConvertString( label->GetText(), labelText );
          HELIUM_ASSERT( converted );
            
        if ( !labelText.empty() )
        {
          break;
        }
      }
    }
  }

  if (labelText.empty())
  {
    std::vector<Reflect::Element*>::const_iterator itr = instances.begin();
    std::vector<Reflect::Element*>::const_iterator end = instances.end();
    for ( ; itr != end; ++itr )
    {
      Reflect::Element* instance = *itr;

      if ( labelText.empty() )
      {
        labelText = instance->GetTitle();
      }
      else
      {
        if ( labelText != instance->GetTitle() )
        {
          labelText.clear();
          break;
        }
      }
    }

    if ( labelText.empty() )
    {
      labelText = typeInfo->m_UIName;
    }
  }

  tstring temp;
  bool converted = Helium::ConvertString( labelText, temp );
  HELIUM_ASSERT( converted );

  panel->SetText( temp );

  M_Panel panelsMap;
  panelsMap.insert( std::make_pair( TXT( "" ), panel) );

  // don't bother including Element's fields
  int offset = Reflect::GetClass<Element>()->m_LastFieldID;

  // for each field in the type
  M_FieldIDToInfo::const_iterator itr = typeInfo->m_FieldIDToInfo.find(offset + 1);
  M_FieldIDToInfo::const_iterator end = typeInfo->m_FieldIDToInfo.end();
  for ( ; itr != end; ++itr )
  {
    const Field* field = itr->second;

    bool noFlags = ( field->m_Flags == 0 && includeFlags == 0xFFFFFFFF );
    bool doInclude = ( field->m_Flags & includeFlags ) != 0;
    bool dontExclude = ( excludeFlags == 0 ) || !(field->m_Flags & excludeFlags );
    bool hidden = (field->m_Flags & Reflect::FieldFlags::Hide) != 0; 

    // if we don't have flags (or we are included, and we aren't excluded) then make UI
    if ( ( noFlags || doInclude ) && ( dontExclude ) )
    {
      //
      // Handle sub panels for grouping content
      // 

      bool groupExpanded = false;
      field->GetProperty( TXT( "UIGroupExpanded" ), groupExpanded );

      tstring fieldUIGroup;
      field->GetProperty( TXT( "UIGroup" ), fieldUIGroup );
      if ( !fieldUIGroup.empty() )
      {
        M_Panel::iterator itr = panelsMap.find( fieldUIGroup );
        if ( itr == panelsMap.end() )
        {
          // This panel isn't in our list so make a new one
          PanelPtr newPanel = m_Container->GetCanvas()->Create<Panel>(this);
          panelsMap.insert( std::make_pair(fieldUIGroup, newPanel) );

          PanelPtr parent;
          tstring groupName;
          size_t idx = fieldUIGroup.find_last_of( TXT( "/" ) );
          if ( idx != tstring::npos )
          {
            tstring parentName = fieldUIGroup.substr( 0, idx );
            groupName = fieldUIGroup.substr( idx+1 );
            if ( panelsMap.find( parentName ) == panelsMap.end() )
            {          
              parent = m_Container->GetCanvas()->Create<Panel>(this);

              // create the parent hierarchy since it hasn't already been made
              tstring currentParent = parentName;
              for (;;)
              {
                idx = currentParent.find_last_of( TXT( "/" ) );
                if ( idx == tstring::npos )
                {
                  // no more parents so we add it to the root
                  panelsMap.insert( std::make_pair(currentParent, parent) );
                  parent->SetText( currentParent );
                  panelsMap[ TXT( "" ) ]->AddControl( parent );
                  break;
                }
                else
                {
                  parent->SetText( currentParent.substr( idx+1 ) );
                  
                  if ( panelsMap.find( currentParent ) != panelsMap.end() )
                  {
                    break;
                  }
                  else
                  {
                    PanelPtr grandParent = m_Container->GetCanvas()->Create<Panel>(this);
                    grandParent->AddControl( parent );
                    panelsMap.insert( std::make_pair(currentParent, parent) );
                    
                    parent = grandParent;
                  }
                  currentParent = currentParent.substr( 0, idx );
                }
              }
              panelsMap.insert( std::make_pair(parentName, parent) );
            }
            parent = panelsMap[parentName];
          }
          else
          {
            parent = panelsMap[ TXT( "" )];
            groupName = fieldUIGroup;
          }
          newPanel->SetText( groupName );
          if( groupExpanded )
          {
            newPanel->SetExpanded( true );
          }
          parent->AddControl( newPanel );
        }
        
        panel = panelsMap[fieldUIGroup];
      }
      else
      {
        panel = panelsMap[ TXT( "" )];
      }


      //
      // Pointer support
      //

      if (field->m_SerializerID == Reflect::GetType<Reflect::PointerSerializer>())
      {
        if (hidden)
        {
          continue; 
        }        

        std::vector<Reflect::Element*> fieldInstances;

        std::vector<Reflect::Element*>::const_iterator elementItr = instances.begin();
        std::vector<Reflect::Element*>::const_iterator elementEnd = instances.end();
        for ( ; elementItr != elementEnd; ++elementItr )
        {
          uintptr fieldAddress = (uintptr)(*elementItr) + itr->second->m_Offset;

          Element* element = *((ElementPtr*)(fieldAddress));

          if ( element )
          {
            fieldInstances.push_back( element );
          }
        }

        if ( !fieldInstances.empty() && fieldInstances.size() == instances.size() )
        {
          InterpretType(fieldInstances, panel);
        }

        continue;
      }


      //
      // Attempt to find a handler via the factory
      //

      ReflectFieldInterpreterPtr fieldInterpreter;

      for ( const Reflect::Class* type = Registry::GetInstance()->GetClass( field->m_SerializerID );
            type != Reflect::GetClass<Reflect::Element>() && !fieldInterpreter;
            type = Reflect::Registry::GetInstance()->GetClass( type->m_Base ) )
      {
        fieldInterpreter = ReflectFieldInterpreterFactory::Create( type->m_TypeID, field->m_Flags, m_Container );
      }

      if ( fieldInterpreter.ReferencesObject() )
      {
        Interpreter::ConnectInterpreterEvents( this, fieldInterpreter );
        fieldInterpreter->InterpretField( field, instances, panel );
        m_Interpreters.push_back( fieldInterpreter );
        continue;
      }


      //
      // ElementArray support
      //

#pragma TODO("Move this out to an interpreter")
      if (field->m_SerializerID == Reflect::GetType<ElementArraySerializer>())
      {
        if (hidden)
        {
          continue;
        }

        if ( instances.size() == 1 )
        {
          uintptr fieldAddress = (uintptr)(instances.front()) + itr->second->m_Offset;

          V_Element* elements = (V_Element*)fieldAddress;

          if ( elements->size() > 0 )
          {
            PanelPtr childPanel = panel->GetCanvas()->Create<Panel>( this );

               tstring temp;
              bool converted = Helium::ConvertString( field->m_UIName, temp );
              HELIUM_ASSERT( converted );

              childPanel->SetText( temp );

            V_Element::const_iterator elementItr = elements->begin();
            V_Element::const_iterator elementEnd = elements->end();
            for ( ; elementItr != elementEnd; ++elementItr )
            {
              std::vector<Reflect::Element*> childInstances;
              childInstances.push_back(*elementItr);
              InterpretType(childInstances, childPanel);
            }

            panel->AddControl( childPanel );
          }
        }

        continue;
      }


      //
      // Lastly fall back to the value interpreter
      //

      const Reflect::Class* type = Registry::GetInstance()->GetClass( field->m_SerializerID );
      if ( !type->HasType( Reflect::GetType<Reflect::ContainerSerializer>() ) )
      {
        fieldInterpreter = CreateInterpreter< ReflectValueInterpreter >( m_Container );
        fieldInterpreter->InterpretField( field, instances, panel );
        m_Interpreters.push_back( fieldInterpreter );
        continue;
      }
    }
  }

  // Make sure we have the base panel
  panel = panelsMap[TXT( "" )];

  if (parent == m_Container)
  {
    panel->SetExpanded(expandPanel);
  }

  if ( !panel->GetControls().empty() )
  {
    parent->AddControl(panel);
  }
}
Beispiel #8
0
int insert_in_parent(string original_node,string key,string new_node )
{
	//cout<<"ENTERING insert_in_parent\n ORIGINAL NODE SENT "<<original_node<<" NEW NODE "<<new_node<<" key "<<key<<endl;
	if(original_node == linkedList.front())
	{
		total_nodes++;
		root_num = total_nodes;

		string contents_to_write;
		contents_to_write="node\n1\n";
		contents_to_write+=original_node+";"+key+"\n"+new_node+";-1\n";
		
		ofstream new_root;
		//cout<<"OPENING NEW ROOT 10: "<<("node"+to_string(total_nodes)).c_str()<<endl;//("node"+to_string(total_nodes)).c_str()<<endl;

		new_root.open(("node"+to_string(total_nodes)).c_str());

		if(!new_root.is_open())
		{
			printf("\nError: Open leaf node 98 %s\n",("node"+to_string(total_nodes)).c_str());
			exit(0);
		}
		
		//cout<<"CONTENTS WRRITING TO NEW NODE\n******\n"<<contents_to_write<<"****"<<endl;
		new_root<<contents_to_write;
		new_root.close();
		//cout<<"RETURN From insert_in_parent"<<endl;
		// exit(0);
		return 1;
	}
	else
	{
		string parent = find_parent(original_node);
		
		//cout<<"CHILD : "<<original_node<<" PARENT NODE : "<<parent<<endl;
		fstream parent_file;

		//cout<<"OPENING FILE 11: "<<parent<<endl;
		parent_file.open(parent.c_str());
		if(!parent_file.is_open())
		{
			cout<<"Unable to open"+parent+" here"<<endl;
			exit(0);
		}
		/*Problem can be here*/	
		string contents_to_write = new_node+";"+key+"\n";	//new file contents
		string contents_to_send_away="";//orignal file contents

		
		string line;
		getline(parent_file,line);
		contents_to_send_away+=line+"\n";

		getline(parent_file,line);
		//TODO update the number accordingly
		if(stoi(line)<num)
		{
			std::vector<std::string> x;
			int flag=0;
			contents_to_send_away+=to_string(stoi(line.c_str())+1)+"\n";

			while(getline(parent_file,line))
			{
				x =split(line,';');
				if(x[0]==original_node)
				{
					// if(x[1]=="-1")
						// contents_to_send_away+=x[0]+";"+key+"\n"+new_node+";-1\n";
					// else
					// {
						//cout<<"here"<<endl;
						contents_to_send_away+=x[0]+";"+key+"\n"+new_node+";"+x[1]+"\n";
						// contents_to_send_away+=line+"\n";
						// contents_to_send_away+=contents_to_write;
					// }
				}
				else
					contents_to_send_away+=line+"\n";
			}
			parent_file.close();

			ofstream new_parent_file;
			new_parent_file.open(parent);
			if(!new_parent_file.is_open())
			{
				cout<<"ERROR: UNABLE TO OPEN 94"<<parent<<endl;
				exit(0);
			}
			//cout<<"CONETENTS HERE\n******\n"<<contents_to_send_away<<"******"<<endl;
			new_parent_file<<contents_to_send_away;
			new_parent_file.close();
			// exit(0);
			return 1;
		}
		else
		{
			// exit(0);
			std::vector<std::string> x;
			// string last_line;
			
			int copy_length = ceil((num+1)/2); //allowed k:= n-1, but here k=n so adding one
			
			// strs<<copy_length;
			contents_to_send_away+=to_string(copy_length)+"\n";

			string new_contents="";
			new_contents = "node\n";

			// strs<< (num+1) - copy_length;
			new_contents+=to_string((num) - copy_length)+"\n";

			std::vector<string> temp_strs;// = new std::vector<string>();
			//cout<<" COPY LENGTH "<<copy_length<<endl;
			while(getline(parent_file,line))
			{
				// contents_to_send_away.append(line);
				// cout<<"LINE READ : "<<line<<endl;
				// if(line=="")
					// break;
				x = split(line,';');
				//cout<<"SPLIT RESULT IN PARENT x[0]: "+ x[0] +":: x[1] : "<<x[1]<<endl;
				if(x[0]==original_node)
				{ 
					// if(x[1]=="-1")
						temp_strs.push_back(x[0]+";"+key+"\n");	
						temp_strs.push_back(new_node+";"+x[1]+"\n");
					// else
					// {
						// cout<<"here"<<endl;
						// temp_strs.push_back(contents_to_write);
					// }	
				}
				else
					temp_strs.push_back(line+"\n");
			}
			std::string least_k="";
			//cout<<"LABEL"<<endl;
			// vector<string>::iterator it;
			//cout<<"NUM TILL WE GO "<<num+1<<endl;
			//cout<<"NUM TILL WE COPY "<<copy_length<<endl;
			for(int i=0; i<=num+1; i++ ) 
			{
				if(i<copy_length)
					contents_to_send_away+=temp_strs[i];
				else if(i==copy_length)
				{
					std::vector<std::string> v;
					v = split(temp_strs[i],';');
					contents_to_send_away+=v[0]+";-1\n";
					least_k = v[1];
				}
				else
					new_contents+=temp_strs[i];
            }
			// string new_file_val = temp_strs[copy_length-1];

			total_nodes++;
			// strs<<total_nodes;

			string new_file_name = "node"+to_string(total_nodes);
			
			// parent_file.seekg(0,ios::beg);
			parent_file.close();

			ofstream new_parent;
			new_parent.open(parent.c_str());
			if(!new_parent.is_open())
			{
				cout<<"ERROR :  UNABLE TO OPEN 96 "<<parent<<endl;
				exit(0);
			}
			//cout<<"CONETENTS WRITING TO PARENT 46\n*****"<<endl<<contents_to_send_away<<endl<<"*****"<<endl;
			new_parent<<contents_to_send_away;
			new_parent.close();
			
			ofstream new_node;
			new_node.open(new_file_name.c_str(),ios::trunc);
			if(!new_node.is_open())
			{
				cout<<"ERROR :  UNABLE TO OPEN 95 "<<parent<<endl;
				exit(0);
			}
			//cout<<"CONETENTS WRITING TO NEW FILE 45 \n*****"<<endl<<new_contents<<endl<<"*****"<<endl;
			//cout<<"OPENING FILE 1:"<<new_file_name<<endl;
			new_node<<new_contents;
			new_node.close();

			least_k.erase(std::remove(least_k.begin(), least_k.end(), '\n'), least_k.end());
			// x= split(new_file_val,';');

			if(insert_in_parent(parent,least_k,new_file_name))
				return 1;
			else
				return -1;
		}
		// if()
	}

	return -1;
}
Beispiel #9
0
/**
 * Return public keys or hashes from scriptPubKey, for 'standard' transaction types.
 */
bool Solver(const CScript& scriptPubKeyIn, txnouttype& typeRet, std::vector<std::vector<unsigned char> >& vSolutionsRet)
{
    // Templates
    static std::multimap<txnouttype, CScript> mTemplates;
    if (mTemplates.empty())
    {
        // Standard tx, sender provides pubkey, receiver adds signature
        mTemplates.insert(std::make_pair(TX_PUBKEY, CScript() << OP_PUBKEY << OP_CHECKSIG));

        // Syscoin address tx, sender provides hash of pubkey, receiver provides signature and pubkey
        mTemplates.insert(std::make_pair(TX_PUBKEYHASH, CScript() << OP_DUP << OP_HASH160 << OP_PUBKEYHASH << OP_EQUALVERIFY << OP_CHECKSIG));

        // Sender provides N pubkeys, receivers provides M signatures
        mTemplates.insert(std::make_pair(TX_MULTISIG, CScript() << OP_SMALLINTEGER << OP_PUBKEYS << OP_SMALLINTEGER << OP_CHECKMULTISIG));
    }

	// SYSCOIN check to see if this is a syscoin service transaction, if so get the scriptPubKey by extracting service specific script information
	CScript scriptPubKey;
	CScript scriptPubKeyOut;
	if (RemoveSyscoinScript(scriptPubKeyIn, scriptPubKeyOut))
		scriptPubKey = scriptPubKeyOut;
	else
		scriptPubKey = scriptPubKeyIn;
    vSolutionsRet.clear();

    // Shortcut for pay-to-script-hash, which are more constrained than the other types:
    // it is always OP_HASH160 20 [20 byte hash] OP_EQUAL
    if (scriptPubKey.IsPayToScriptHash())
    {
        typeRet = TX_SCRIPTHASH;
        std::vector<unsigned char> hashBytes(scriptPubKey.begin()+2, scriptPubKey.begin()+22);
        vSolutionsRet.push_back(hashBytes);
        return true;
    }

    // Provably prunable, data-carrying output
    //
    // So long as script passes the IsUnspendable() test and all but the first
    // byte passes the IsPushOnly() test we don't care what exactly is in the
    // script.
    if (scriptPubKey.size() >= 1 && scriptPubKey[0] == OP_RETURN && scriptPubKey.IsPushOnly(scriptPubKey.begin()+1)) {
        typeRet = TX_NULL_DATA;
        return true;
    }

    // Scan templates
    const CScript& script1 = scriptPubKey;
    BOOST_FOREACH(const PAIRTYPE(txnouttype, CScript)& tplate, mTemplates)
    {
        const CScript& script2 = tplate.second;
        vSolutionsRet.clear();

        opcodetype opcode1, opcode2;
        std::vector<unsigned char> vch1, vch2;

        // Compare
        CScript::const_iterator pc1 = script1.begin();
        CScript::const_iterator pc2 = script2.begin();
        while (true)
        {
            if (pc1 == script1.end() && pc2 == script2.end())
            {
                // Found a match
                typeRet = tplate.first;
                if (typeRet == TX_MULTISIG)
                {
                    // Additional checks for TX_MULTISIG:
                    unsigned char m = vSolutionsRet.front()[0];
                    unsigned char n = vSolutionsRet.back()[0];
                    if (m < 1 || n < 1 || m > n || vSolutionsRet.size()-2 != n)
                        return false;
                }
                return true;
            }
            if (!script1.GetOp(pc1, opcode1, vch1))
                break;
            if (!script2.GetOp(pc2, opcode2, vch2))
                break;

            // Template matching opcodes:
            if (opcode2 == OP_PUBKEYS)
            {
                while (vch1.size() >= 33 && vch1.size() <= 65)
                {
                    vSolutionsRet.push_back(vch1);
                    if (!script1.GetOp(pc1, opcode1, vch1))
                        break;
                }
                if (!script2.GetOp(pc2, opcode2, vch2))
                    break;
                // Normal situation is to fall through
                // to other if/else statements
            }

            if (opcode2 == OP_PUBKEY)
            {
                if (vch1.size() < 33 || vch1.size() > 65)
                    break;
                vSolutionsRet.push_back(vch1);
            }
            else if (opcode2 == OP_PUBKEYHASH)
            {
                if (vch1.size() != sizeof(uint160))
                    break;
                vSolutionsRet.push_back(vch1);
            }
            else if (opcode2 == OP_SMALLINTEGER)
            {   // Single-byte small integer pushed onto vSolutions
                if (opcode1 == OP_0 ||
                    (opcode1 >= OP_1 && opcode1 <= OP_16))
                {
                    char n = (char)CScript::DecodeOP_N(opcode1);
                    vSolutionsRet.push_back(valtype(1, n));
                }
                else
                    break;
            }
            else if (opcode1 != opcode2 || vch1 != vch2)
            {
                // Others must match exactly
                break;
            }
        }
    }

    vSolutionsRet.clear();
    typeRet = TX_NONSTANDARD;
    return false;
}
bool CrossWordsField::ProcessWordsBackTrack(std::vector<Word> words)
{
	if (words.size() == 0)
	{
		if (PlacedWords.size() == _wordsToInsert)
		{
			std::cout << "all placed" << std::endl;

			return true;
		}
		else
		{
			return false;
		}
	}

	auto wordToPlace = words.front();

	if (PlacedWords.size() == 0)
	{
		Point p = Point();
		p.X = DimX / 2;
		p.Y = DimY / 2;
		InsertWord(wordToPlace, Horisontal, p);

		std::vector<Word>::iterator minusOne = words.erase(words.begin()); 
		return ProcessWordsBackTrack(words);
	}
	else
	{
		auto next = words.front();
		auto avalibelePos = CrossPositions(next);

		if (avalibelePos.size() == 0)
		{
			if (swapCount >= _wordsToInsert + 1)
			{
				return false;
			}

			swapCount++;

			auto inseted = RemoveLastWord()._word;

			words.push_back(inseted);

			return ProcessWordsBackTrack(words);
		}
		else
		{

			// try insert
			auto result = false;


			while (result == false)
			{
				if (avalibelePos.size() == 0)
				{
					break;
				}
				auto f = avalibelePos.front();

				//if (f == nullptr avalibelePos.end().)
				// TODO: need to be implimented?????
				//{
					//break;
				//}

				auto cPos = CanPlaceToCrossPos(f, next);

				if (cPos.Posible())
				{
					InsertWord(cPos, next);

					words.erase(words.begin()); //Remove(next);

					result = true;
				}
				else
				{
					avalibelePos.erase(avalibelePos.begin());// Remove(f);
					result = false;
				}

			}

			if (!result)
			{
				RemoveLastWord();
				auto it = words.erase(words.begin()); //Remove(next);
				
				words.push_back(next);
			}
		}

		return ProcessWordsBackTrack(words);
	}
}
void CUDASolverBundling::solve(EntryJ* d_correspondences, unsigned int numberOfCorrespondences, const int* d_validImages, unsigned int numberOfImages,
	unsigned int nNonLinearIterations, unsigned int nLinearIterations, const CUDACache* cudaCache,
	const std::vector<float>& weightsSparse, const std::vector<float>& weightsDenseDepth, const std::vector<float>& weightsDenseColor, bool usePairwiseDense,
	float3* d_rotationAnglesUnknowns, float3* d_translationUnknowns,
	bool rebuildJT, bool findMaxResidual, unsigned int revalidateIdx)
{
	nNonLinearIterations = std::min(nNonLinearIterations, (unsigned int)weightsSparse.size());
	MLIB_ASSERT(numberOfImages > 1 && nNonLinearIterations > 0);
	if (numberOfCorrespondences > m_maxCorrPerImage*m_maxNumberOfImages) {
		//warning: correspondences will be invalidated AT RANDOM!
		std::cerr << "WARNING: #corr (" << numberOfCorrespondences << ") exceeded limit (" << m_maxCorrPerImage << "*" << m_maxNumberOfImages << "), please increase max #corr per image in the GAS" << std::endl;
	}

	float* convergence = NULL;
	if (m_bRecordConvergence) {
		m_convergence.resize(nNonLinearIterations + 1, -1.0f);
		convergence = m_convergence.data();
	}

	m_solverState.d_xRot = d_rotationAnglesUnknowns;
	m_solverState.d_xTrans = d_translationUnknowns;

	SolverParameters parameters = m_defaultParams;
	parameters.nNonLinearIterations = nNonLinearIterations;
	parameters.nLinIterations = nLinearIterations;
	parameters.verifyOptDistThresh = m_verifyOptDistThresh;
	parameters.verifyOptPercentThresh = m_verifyOptPercentThresh;
	parameters.highResidualThresh = std::numeric_limits<float>::infinity();

	parameters.weightSparse = weightsSparse.front();
	parameters.weightDenseDepth = weightsDenseDepth.front();
	parameters.weightDenseColor = weightsDenseColor.front();
	parameters.useDense = (parameters.weightDenseDepth > 0 || parameters.weightDenseColor > 0);
	parameters.useDenseDepthAllPairwise = usePairwiseDense;

	SolverInput solverInput;
	solverInput.d_correspondences = d_correspondences;
	solverInput.d_variablesToCorrespondences = d_variablesToCorrespondences;
	solverInput.d_numEntriesPerRow = d_numEntriesPerRow;
	solverInput.numberOfImages = numberOfImages;
	solverInput.numberOfCorrespondences = numberOfCorrespondences;

	solverInput.maxNumberOfImages = m_maxNumberOfImages;
	solverInput.maxCorrPerImage = m_maxCorrPerImage;
	solverInput.maxNumDenseImPairs = m_maxNumDenseImPairs;

	solverInput.weightsSparse = weightsSparse.data();
	solverInput.weightsDenseDepth = weightsDenseDepth.data();
	solverInput.weightsDenseColor = weightsDenseColor.data();
	solverInput.d_validImages = d_validImages;
	if (cudaCache) {
		solverInput.d_cacheFrames = cudaCache->getCacheFramesGPU();
		solverInput.denseDepthWidth = cudaCache->getWidth(); //TODO constant buffer for this?
		solverInput.denseDepthHeight = cudaCache->getHeight();
		mat4f intrinsics = cudaCache->getIntrinsics();
		solverInput.intrinsics = make_float4(intrinsics(0, 0), intrinsics(1, 1), intrinsics(0, 2), intrinsics(1, 2));
		MLIB_ASSERT(solverInput.denseDepthWidth / parameters.denseOverlapCheckSubsampleFactor > 8); //need enough samples
	}
	else {
		solverInput.d_cacheFrames = NULL;
		solverInput.denseDepthWidth = 0;
		solverInput.denseDepthHeight = 0;
		solverInput.intrinsics = make_float4(-std::numeric_limits<float>::infinity());
	}
#ifdef NEW_GUIDED_REMOVE
	convertLiePosesToMatricesCU(m_solverState.d_xRot, m_solverState.d_xTrans, solverInput.numberOfImages, d_transforms, m_solverState.d_xTransformInverses); //debugging only (store transforms before opt)
#endif
#ifdef DEBUG_PRINT_SPARSE_RESIDUALS
	if (findMaxResidual) {
		float residualBefore = EvalResidual(solverInput, m_solverState, parameters, NULL);
		computeMaxResidual(solverInput, parameters, (unsigned int)-1);
		vec2ui beforeMaxImageIndices; float beforeMaxRes; unsigned int curFrame = (revalidateIdx == (unsigned int)-1) ? solverInput.numberOfImages - 1 : revalidateIdx;
		getMaxResidual(curFrame, d_correspondences, beforeMaxImageIndices, beforeMaxRes);
		std::cout << "\tbefore: (" << solverInput.numberOfImages << ") sumres = " << residualBefore << " / " << solverInput.numberOfCorrespondences << " = " << residualBefore / (float)solverInput.numberOfCorrespondences << " | maxres = " << beforeMaxRes << " images (" << beforeMaxImageIndices << ")" << std::endl;
	}
#endif


	if (rebuildJT) {
		buildVariablesToCorrespondencesTable(d_correspondences, numberOfCorrespondences);
	}

	//if (cudaCache) {
	//	cudaCache->printCacheImages("debug/cache/");
	//	int a = 5;
	//}
	solveBundlingStub(solverInput, m_solverState, parameters, m_solverExtra, convergence, m_timer);

	if (findMaxResidual) {
		computeMaxResidual(solverInput, parameters, revalidateIdx);
#ifdef DEBUG_PRINT_SPARSE_RESIDUALS
		float residualAfter = EvalResidual(solverInput, m_solverState, parameters, NULL);
		vec2ui afterMaxImageIndices; float afterMaxRes; unsigned int curFrame = (revalidateIdx == (unsigned int)-1) ? solverInput.numberOfImages - 1 : revalidateIdx;
		getMaxResidual(curFrame, d_correspondences, afterMaxImageIndices, afterMaxRes);
		std::cout << "\tafter: (" << solverInput.numberOfImages << ") sumres = " << residualAfter << " / " << solverInput.numberOfCorrespondences << " = " << residualAfter / (float)solverInput.numberOfCorrespondences << " | maxres = " << afterMaxRes << " images (" << afterMaxImageIndices << ")" << std::endl;
#endif
	}
}
Beispiel #12
0
    void recursiveSearchKNearestNeighbours(uint32_t nodeIndex, const Vec3f& point, size_t K, Predicate predicate,
                                           float& distSquared, std::vector<std::pair<uint32_t, float>>& heap) const {
        auto node = m_Nodes[nodeIndex];
        uint32_t index = m_NodesData[nodeIndex].m_nIndex;

        float candidateDistSquared = sqr_distance(point, m_NodesData[nodeIndex].m_Position);

        // If the node is a leaf, end of the recursion
        if(node.m_nSplitAxis == 3) {
            if((heap.size() < K || candidateDistSquared < distSquared) && predicate(index)) {
                heap.push_back(std::make_pair(nodeIndex, candidateDistSquared));
                std::push_heap(heap.begin(), heap.end(), compare);

                if(heap.size() > K) {
                    std::pop_heap(heap.begin(), heap.end(), compare);
                    heap.pop_back();
                }

                distSquared = heap.front().second;
            }
            return;
        }

        uint8_t axis = node.m_nSplitAxis;

        bool isAtLeft = (point[axis] <= node.m_fSplitPosition);

        // Left side
        if(isAtLeft && node.m_bHasLeftChild) {
            recursiveSearchKNearestNeighbours(nodeIndex + 1, point, K, predicate, distSquared, heap);
        }
        // Right side
        else if(!isAtLeft && node.m_nRightChildIndex < m_Nodes.size()) {
            recursiveSearchKNearestNeighbours(node.m_nRightChildIndex, point, K, predicate, distSquared, heap);
        }

        // Test the current node against the actual best match
        if((heap.size() < K || candidateDistSquared < distSquared) && predicate(index)) {
            heap.push_back(std::make_pair(nodeIndex, candidateDistSquared));
            std::push_heap(heap.begin(), heap.end(), compare);

            if(heap.size() > K) {
                std::pop_heap(heap.begin(), heap.end(), compare);
                heap.pop_back();
            }

            distSquared = heap.front().second;
        }

        float axisDistSquared = sqr(point[axis] - node.m_fSplitPosition);

        // If the separation axis is closer to the point than the actual best match
        // we must search the other side
        if(heap.size() < K || axisDistSquared < distSquared) {
            if(isAtLeft && node.m_nRightChildIndex < m_Nodes.size()) {
                recursiveSearchKNearestNeighbours(node.m_nRightChildIndex, point, K, predicate, distSquared, heap);
            }
            else if(!isAtLeft && node.m_bHasLeftChild) {
                recursiveSearchKNearestNeighbours(nodeIndex + 1, point, K, predicate, distSquared, heap);
            }
        }
    }
Beispiel #13
0
 bool diffie_hellman::compute_shared_key( const std::vector<char>& pubk ) {
    return compute_shared_key( &pubk.front(), pubk.size() );
 }
Beispiel #14
0
StatusWith<boost::optional<ChunkRange>> splitChunkAtMultiplePoints(
    OperationContext* txn,
    const ShardId& shardId,
    const NamespaceString& nss,
    const ShardKeyPattern& shardKeyPattern,
    ChunkVersion collectionVersion,
    const ChunkRange& chunkRange,
    const std::vector<BSONObj>& splitPoints) {
    invariant(!splitPoints.empty());

    const size_t kMaxSplitPoints = 8192;

    if (splitPoints.size() > kMaxSplitPoints) {
        return {ErrorCodes::BadValue,
                str::stream() << "Cannot split chunk in more than " << kMaxSplitPoints
                              << " parts at a time."};
    }

    // Sanity check that we are not attempting to split at the boundaries of the chunk. This check
    // is already performed at chunk split commit time, but we are performing it here for parity
    // with old auto-split code, which might rely on it.
    if (SimpleBSONObjComparator::kInstance.evaluate(chunkRange.getMin() == splitPoints.front())) {
        const std::string msg(str::stream() << "not splitting chunk " << chunkRange.toString()
                                            << ", split point "
                                            << splitPoints.front()
                                            << " is exactly on chunk bounds");
        return {ErrorCodes::CannotSplit, msg};
    }

    if (SimpleBSONObjComparator::kInstance.evaluate(chunkRange.getMax() == splitPoints.back())) {
        const std::string msg(str::stream() << "not splitting chunk " << chunkRange.toString()
                                            << ", split point "
                                            << splitPoints.back()
                                            << " is exactly on chunk bounds");
        return {ErrorCodes::CannotSplit, msg};
    }

    BSONObjBuilder cmd;
    cmd.append("splitChunk", nss.ns());
    cmd.append("configdb",
               Grid::get(txn)->shardRegistry()->getConfigServerConnectionString().toString());
    cmd.append("from", shardId.toString());
    cmd.append("keyPattern", shardKeyPattern.toBSON());
    collectionVersion.appendForCommands(&cmd);
    chunkRange.append(&cmd);
    cmd.append("splitKeys", splitPoints);

    BSONObj cmdObj = cmd.obj();

    Status status{ErrorCodes::InternalError, "Uninitialized value"};
    BSONObj cmdResponse;

    auto shardStatus = Grid::get(txn)->shardRegistry()->getShard(txn, shardId);
    if (!shardStatus.isOK()) {
        status = shardStatus.getStatus();
    } else {
        auto cmdStatus = shardStatus.getValue()->runCommandWithFixedRetryAttempts(
            txn,
            ReadPreferenceSetting{ReadPreference::PrimaryOnly},
            "admin",
            cmdObj,
            Shard::RetryPolicy::kNotIdempotent);
        if (!cmdStatus.isOK()) {
            status = std::move(cmdStatus.getStatus());
        } else {
            status = std::move(cmdStatus.getValue().commandStatus);
            cmdResponse = std::move(cmdStatus.getValue().response);
        }
    }

    if (!status.isOK()) {
        log() << "Split chunk " << redact(cmdObj) << " failed" << causedBy(redact(status));
        return {status.code(), str::stream() << "split failed due to " << status.toString()};
    }

    BSONElement shouldMigrateElement;
    status = bsonExtractTypedField(cmdResponse, kShouldMigrate, Object, &shouldMigrateElement);
    if (status.isOK()) {
        auto chunkRangeStatus = ChunkRange::fromBSON(shouldMigrateElement.embeddedObject());
        if (!chunkRangeStatus.isOK()) {
            return chunkRangeStatus.getStatus();
        }

        return boost::optional<ChunkRange>(std::move(chunkRangeStatus.getValue()));
    } else if (status != ErrorCodes::NoSuchKey) {
        warning()
            << "Chunk migration will be skipped because splitChunk returned invalid response: "
            << redact(cmdResponse) << ". Extracting " << kShouldMigrate << " field failed"
            << causedBy(redact(status));
    }

    return boost::optional<ChunkRange>();
}
// ------------------------------------------------------------------------------------------------
// Convert to UTF8 data
void BaseImporter::ConvertToUTF8(std::vector<char>& data)
{
	ConversionResult result;
	if(data.size() < 8) {
		throw DeadlyImportError("File is too small");
	}

	// UTF 8 with BOM
	if((uint8_t)data[0] == 0xEF && (uint8_t)data[1] == 0xBB && (uint8_t)data[2] == 0xBF) {
		DefaultLogger::get()->debug("Found UTF-8 BOM ...");

		std::copy(data.begin()+3,data.end(),data.begin());
		data.resize(data.size()-3);
		return;
	}

	// UTF 32 BE with BOM
	if(*((uint32_t*)&data.front()) == 0xFFFE0000) {
	
		// swap the endianess ..
		for(uint32_t* p = (uint32_t*)&data.front(), *end = (uint32_t*)&data.back(); p <= end; ++p) {
			AI_SWAP4P(p);
		}
	}
	
	// UTF 32 LE with BOM
	if(*((uint32_t*)&data.front()) == 0x0000FFFE) {
		DefaultLogger::get()->debug("Found UTF-32 BOM ...");

		const uint32_t* sstart = (uint32_t*)&data.front()+1, *send = (uint32_t*)&data.back()+1;
		char* dstart,*dend;
		std::vector<char> output;
		do {
			output.resize(output.size()?output.size()*3/2:data.size()/2);
			dstart = &output.front(),dend = &output.back()+1;

			result = ConvertUTF32toUTF8((const UTF32**)&sstart,(const UTF32*)send,(UTF8**)&dstart,(UTF8*)dend,lenientConversion);
		} while(result == targetExhausted);

		ReportResult(result);

		// copy to output buffer. 
		const size_t outlen = (size_t)(dstart-&output.front());
		data.assign(output.begin(),output.begin()+outlen);
		return;
	}

	// UTF 16 BE with BOM
	if(*((uint16_t*)&data.front()) == 0xFFFE) {
	
		// swap the endianess ..
		for(uint16_t* p = (uint16_t*)&data.front(), *end = (uint16_t*)&data.back(); p <= end; ++p) {
			ByteSwap::Swap2(p);
		}
	}
	
	// UTF 16 LE with BOM
	if(*((uint16_t*)&data.front()) == 0xFEFF) {
		DefaultLogger::get()->debug("Found UTF-16 BOM ...");

		const uint16_t* sstart = (uint16_t*)&data.front()+1, *send = (uint16_t*)(&data.back()+1);
		char* dstart,*dend;
		std::vector<char> output;
		do {
			output.resize(output.size()?output.size()*3/2:data.size()*3/4);
			dstart = &output.front(),dend = &output.back()+1;

			result = ConvertUTF16toUTF8((const UTF16**)&sstart,(const UTF16*)send,(UTF8**)&dstart,(UTF8*)dend,lenientConversion);
		} while(result == targetExhausted);

		ReportResult(result);

		// copy to output buffer.
		const size_t outlen = (size_t)(dstart-&output.front());
		data.assign(output.begin(),output.begin()+outlen);
		return;
	}
}
 inline Real CapFloorTermVolSurface::minStrike() const {
     return strikes_.front();
 }
ClusteringGrid::ClusteringGrid(const std::vector<double> &grid_spacing_x, const std::vector<double> &grid_spacing_y)
:grid_spacing_x_(grid_spacing_x), grid_spacing_y_(grid_spacing_y), range_x_(grid_spacing_x.front(),grid_spacing_x.back()), range_y_(grid_spacing_y.front(),grid_spacing_y.back())
{
}
/*
Show the filtertypes of each scanline in this PNG image.
*/
void displayFilterTypes(const std::vector<unsigned char>& buffer, bool ignore_checksums)
{
  //Get color type and interlace type
  lodepng::State state;
  if(ignore_checksums)
  {
    state.decoder.ignore_crc = 1;
    state.decoder.zlibsettings.ignore_adler32 = 1;
  }
  unsigned w, h;
  unsigned error;
  error = lodepng_inspect(&w, &h, &state, &buffer[0], buffer.size());

  if(error)
  {
    std::cout << "inspect error " << error << ": " << lodepng_error_text(error) << std::endl;
    return;
  }

  if(state.info_png.interlace_method == 1)
  {
    std::cout << "showing filtertypes for interlaced PNG not supported by this example" << std::endl;
    return;
  }

  //Read literal data from all IDAT chunks
  const unsigned char *chunk, *begin, *end, *next;
  end = &buffer.back() + 1;
  begin = chunk = &buffer.front() + 8;

  std::vector<unsigned char> zdata;

  while(chunk + 8 < end && chunk >= begin)
  {
    char type[5];
    lodepng_chunk_type(type, chunk);
    if(std::string(type).size() != 4)
    {
      std::cout << "this is probably not a PNG" << std::endl;
      return;
    }

    if(std::string(type) == "IDAT")
    {
      const unsigned char* cdata = lodepng_chunk_data_const(chunk);
      unsigned clength = lodepng_chunk_length(chunk);
      if(chunk + clength + 12 > end || clength > buffer.size() || chunk + clength + 12 < begin) {
        std::cout << "invalid chunk length" << std::endl;
        return;
      }

      for(unsigned i = 0; i < clength; i++)
      {
        zdata.push_back(cdata[i]);
      }
    }

    next = lodepng_chunk_next_const(chunk);
    if (next <= chunk) break; // integer overflow
    chunk = next;
  }

  //Decompress all IDAT data
  std::vector<unsigned char> data;
  error = lodepng::decompress(data, &zdata[0], zdata.size());

  if(error)
  {
    std::cout << "decompress error " << error << ": " << lodepng_error_text(error) << std::endl;
    return;
  }

  //A line is 1 filter byte + all pixels
  size_t linebytes = 1 + lodepng_get_raw_size(w, 1, &state.info_png.color);

  if(linebytes == 0)
  {
    std::cout << "error: linebytes is 0" << std::endl;
    return;
  }

  std::cout << "Filter types: ";
  for(size_t i = 0; i < data.size(); i += linebytes)
  {
    std::cout << (int)(data[i]) << " ";
  }
  std::cout << std::endl;

}
Beispiel #19
0
void Evangelism::update(float delta) {
	x = members.front()->getPositionX();
	y = members.front()->getPositionY();

	//loop for followers
	for (int i = members.size() - 1; i > 0; i--) {
		members[i]->setPosition(members[i - 1]->getPositionX(), members[i - 1]->getPositionY());
		members[i]->setTexture(members[i - 1]->getTexture());	
	}
	switch (direction) {
	case LEFT:
		members.front()->setPosition(x - 45, y);
		members.front()->setTexture(CCTextureCache::sharedTextureCache()->addImage("leftpriest.png"));
		break;
	case RIGHT:
		members.front()->setPosition(x + 45, y);
		members.front()->setTexture(CCTextureCache::sharedTextureCache()->addImage("rightpriest.png"));
		break;
	case UP:
		members.front()->setPosition(x, y + 45);
		members.front()->setTexture(CCTextureCache::sharedTextureCache()->addImage("uppriest.png"));
		break;
	case DOWN:
		members.front()->setPosition(x, y - 45);
		members.front()->setTexture(CCTextureCache::sharedTextureCache()->addImage("downpriest.png"));
		break;
	}

	//loop for collision with followers
	for (int i = 1; i < members.size(); i++) {
		if (members[i]->getPosition() == members.front()->getPosition()) {
			Director::getInstance()->end();
		}
	}
	if ((members.front()->getPositionX() >= humanSprite->getPositionX() - 22 && 
		 members.front()->getPositionX() <= humanSprite->getPositionX() + 22)&& 
		(members.front()->getPositionY() >= humanSprite->getPositionY() - 22 &&
		members.front()->getPositionY() <= humanSprite->getPositionY() + 22)) {

		humanX = (1 + random() % 18) * 45;
		humanY = (1 + random() % 18) * 45;
		humanSprite->setPosition(humanX, humanY);
		score++;
		label->setString(std::to_string(score));
		int tempX = members.back()->getPositionX();
		int tempY = members.back()->getPositionY();
		Sprite* tempSprite = Sprite::create();
		switch (direction) {
		case LEFT:
			tempSprite = Sprite::create("leftpriest.png");
			tempSprite->setPosition(tempX + 45, tempY);

			break;
		case RIGHT:
			tempSprite = Sprite::create("rightpriest.png");
			tempSprite->setPosition(tempX - 45, tempY);

			break;
		case UP:
			tempSprite = Sprite::create("uppriest.png");
			tempSprite->setPosition(tempX, tempY + 45);

			break;
		case DOWN:
			tempSprite = Sprite::create("downpriest.png");
			tempSprite->setPosition(tempX, tempY - 45);

			break;
		}

		this->addChild(tempSprite);
		members.push_back(tempSprite);
		
	}

	//Outside of screen
	if (members.front()->getPositionX() >= width || members.front()->getPositionX() <= 0 || members.front()->getPositionY() >= height || members.front()->getPositionY() <= 0) {
		Director::getInstance()->end();
	}
}
void DouglasPeucker::Run(std::vector<SegmentInformation> &input_geometry, const unsigned zoom_level)
{
    input_geometry.front().necessary = true;
    input_geometry.back().necessary = true;

    BOOST_ASSERT_MSG(!input_geometry.empty(), "geometry invalid");
    if (input_geometry.size() < 2)
    {
        return;
    }

    SimpleLogger().Write() << "input_geometry.size()=" << input_geometry.size();

    {
        BOOST_ASSERT_MSG(zoom_level < 19, "unsupported zoom level");
        unsigned left_border = 0;
        unsigned right_border = 1;
        // Sweep over array and identify those ranges that need to be checked
        do
        {
            if (!input_geometry[left_border].necessary)
            {
              SimpleLogger().Write() << "broken interval [" << left_border << "," << right_border << "]";
            }
            BOOST_ASSERT_MSG(input_geometry[left_border].necessary,
                             "left border must be necessary");
            BOOST_ASSERT_MSG(input_geometry.back().necessary, "right border must be necessary");

            if (input_geometry[right_border].necessary)
            {
                recursion_stack.emplace(left_border, right_border);
                left_border = right_border;
            }
            ++right_border;
        } while (right_border < input_geometry.size());
    }
    while (!recursion_stack.empty())
    {
        // pop next element
        const GeometryRange pair = recursion_stack.top();
        recursion_stack.pop();
        BOOST_ASSERT_MSG(input_geometry[pair.first].necessary, "left border mus be necessary");
        BOOST_ASSERT_MSG(input_geometry[pair.second].necessary, "right border must be necessary");
        BOOST_ASSERT_MSG(pair.second < input_geometry.size(), "right border outside of geometry");
        BOOST_ASSERT_MSG(pair.first < pair.second, "left border on the wrong side");
        double max_distance = std::numeric_limits<double>::min();

        unsigned farthest_element_index = pair.second;
        // find index idx of element with max_distance
        for (unsigned i = pair.first + 1; i < pair.second; ++i)
        {
            const double temp_dist = FixedPointCoordinate::ComputePerpendicularDistance(
                input_geometry[i].location,
                input_geometry[pair.first].location,
                input_geometry[pair.second].location);
            const double distance = std::abs(temp_dist);
            if (distance > douglas_peucker_thresholds[zoom_level] && distance > max_distance)
            {
                farthest_element_index = i;
                max_distance = distance;
            }
        }
        if (max_distance > douglas_peucker_thresholds[zoom_level])
        {
            //  mark idx as necessary
            input_geometry[farthest_element_index].necessary = true;
            if (1 < (farthest_element_index - pair.first))
            {
                recursion_stack.emplace(pair.first, farthest_element_index);
            }
            if (1 < (pair.second - farthest_element_index))
            {
                recursion_stack.emplace(farthest_element_index, pair.second);
            }
        }
    }
}
 static type create(const std::vector<float>& t) { return type(&t.front()); }
const std::list<gp_Trsf> MultiTransform::getTransformations(const std::vector<App::DocumentObject*> originals)
{
    std::vector<App::DocumentObject*> transFeatures = Transformations.getValues();

    // Find centre of gravity of first original
    // FIXME: This method will NOT give the expected result for more than one original!
    Part::Feature* originalFeature = static_cast<Part::Feature*>(originals.front());
    TopoDS_Shape original;

    if (originalFeature->getTypeId().isDerivedFrom(PartDesign::FeatureAddSub::getClassTypeId())) {
        PartDesign::FeatureAddSub* addFeature = static_cast<PartDesign::FeatureAddSub*>(originalFeature);
        if(addFeature->getAddSubType() == FeatureAddSub::Additive)
            original = addFeature->AddSubShape.getShape()._Shape;
        else 
            original = addFeature->AddSubShape.getShape()._Shape;
    }

    GProp_GProps props;
    BRepGProp::VolumeProperties(original,props);
    gp_Pnt cog = props.CentreOfMass();

    std::list<gp_Trsf> result;
    std::list<gp_Pnt> cogs;
    std::vector<App::DocumentObject*>::const_iterator f;

    for (f = transFeatures.begin(); f != transFeatures.end(); ++f) {
        if (!((*f)->getTypeId().isDerivedFrom(PartDesign::Transformed::getClassTypeId())))
            throw Base::Exception("Transformation features must be subclasses of Transformed");
        PartDesign::Transformed* transFeature = static_cast<PartDesign::Transformed*>(*f);
        std::list<gp_Trsf> newTransformations = transFeature->getTransformations(originals);

        if (result.empty()) {
            // First transformation Feature
            result = newTransformations;
            for (std::list<gp_Trsf>::const_iterator nt = newTransformations.begin(); nt != newTransformations.end(); ++nt) {
                cogs.push_back(cog.Transformed(*nt));
            }
        } else {
            // Retain a copy of the first set of transformations for iterator ot
            // We can't iterate through result if we are also adding elements with push_back()!
            std::list<gp_Trsf> oldTransformations;
            result.swap(oldTransformations); // empty result to receive new transformations
            std::list<gp_Pnt> oldCogs;
            cogs.swap(oldCogs); // empty cogs to receive new cogs

            if ((*f)->getTypeId() == PartDesign::Scaled::getClassTypeId()) {
                // Diagonal method
                // Multiply every element in the old transformations' slices with the corresponding
                // element in the newTransformations. Example:
                // a11 a12 a13 a14          b1    a11*b1 a12*b1 a13*b1 a14*b1
                // a21 a22 a23 a24   diag   b2  = a21*b2 a22*b2 a23*b2 a24*b1
                // a31 a23 a33 a34          b3    a31*b3 a23*b3 a33*b3 a34*b1
                // In other words, the length of the result vector is equal to the length of the
                // oldTransformations vector

                if (oldTransformations.size() % newTransformations.size() != 0)
                    throw Base::Exception("Number of occurrences must be a divisor of previous number of occurrences");

                unsigned sliceLength = oldTransformations.size() / newTransformations.size();
                std::list<gp_Trsf>::const_iterator ot = oldTransformations.begin();
                std::list<gp_Pnt>::const_iterator oc = oldCogs.begin();

                for (std::list<gp_Trsf>::const_iterator nt = newTransformations.begin(); nt != newTransformations.end(); ++nt) {
                    for (unsigned s = 0; s < sliceLength; s++) {
                        gp_Trsf trans;
                        double factor = nt->ScaleFactor(); // extract scale factor

                        if (factor > Precision::Confusion()) {
                            trans.SetScale(*oc, factor); // recreate the scaled transformation to use the correct COG
                            trans = trans * (*ot);
                            cogs.push_back(*oc); // Scaling does not affect the COG
                        } else {
                            trans = (*nt) * (*ot);
                            cogs.push_back(oc->Transformed(*nt));
                        }
                        result.push_back(trans);
                        ++ot;
                        ++oc;
                    }
                }
            } else {
                // Multiplication method: Combine the new transformations with the old ones.
                // All old transformations are multiplied with all new ones, so that the length of the
                // result vector is the length of the old and new transformations multiplied.
                // a11 a12         b1    a11*b1 a12*b1 a11*b2 a12*b2 a11*b3 a12*b3
                // a21 a22   mul   b2  = a21*b1 a22*b1 a21*b2 a22*b2 a21*b3 a22*b3
                //                 b3
                for (std::list<gp_Trsf>::const_iterator nt = newTransformations.begin(); nt != newTransformations.end(); ++nt) {
                    std::list<gp_Pnt>::const_iterator oc = oldCogs.begin();

                    for (std::list<gp_Trsf>::const_iterator ot = oldTransformations.begin(); ot != oldTransformations.end(); ++ot) {
                        result.push_back((*nt) * (*ot));
                        cogs.push_back(oc->Transformed(*nt));
                        ++oc;
                    }
                }
            }
            // What about the Additive method: Take the last (set of) transformations and use them as
            // "originals" for the next transformationFeature, so that something similar to a sweep
            // for transformations could be put together?
        }
    }

    return result;
}
Beispiel #23
0
 const int* get() const {
     return &list.front();
 }
Beispiel #24
0
/** Executes the algorithm
 *
 *  @throw runtime_error Thrown if algorithm cannot execute
 */
void Fit1D::exec() {

  // Custom initialization
  prepare();

  // check if derivative defined in derived class
  bool isDerivDefined = true;
  gsl_matrix *M = NULL;
  try {
    const std::vector<double> inTest(m_parameterNames.size(), 1.0);
    std::vector<double> outTest(m_parameterNames.size());
    const double xValuesTest = 0;
    JacobianImpl J;
    M = gsl_matrix_alloc(m_parameterNames.size(), 1);
    J.setJ(M);
    // note nData set to zero (last argument) hence this should avoid further
    // memory problems
    functionDeriv(&(inTest.front()), &J, &xValuesTest, 0);
  } catch (Exception::NotImplementedError &) {
    isDerivDefined = false;
  }
  gsl_matrix_free(M);

  // Try to retrieve optional properties
  int histNumber = getProperty("WorkspaceIndex");
  const int maxInterations = getProperty("MaxIterations");

  // Get the input workspace
  MatrixWorkspace_const_sptr localworkspace = getProperty("InputWorkspace");

  // number of histogram is equal to the number of spectra
  const size_t numberOfSpectra = localworkspace->getNumberHistograms();
  // Check that the index given is valid
  if (histNumber >= static_cast<int>(numberOfSpectra)) {
    g_log.warning("Invalid Workspace index given, using first Workspace");
    histNumber = 0;
  }

  // Retrieve the spectrum into a vector
  const MantidVec &XValues = localworkspace->readX(histNumber);
  const MantidVec &YValues = localworkspace->readY(histNumber);
  const MantidVec &YErrors = localworkspace->readE(histNumber);

  // Read in the fitting range data that we were sent
  double startX = getProperty("StartX");
  double endX = getProperty("EndX");
  // check if the values had been set, otherwise use defaults
  if (isEmpty(startX)) {
    startX = XValues.front();
    modifyStartOfRange(startX); // does nothing by default but derived class may
                                // provide a more intelligent value
  }
  if (isEmpty(endX)) {
    endX = XValues.back();
    modifyEndOfRange(endX); // does nothing by default but derived class may
                            // previde a more intelligent value
  }

  int m_minX;
  int m_maxX;

  // Check the validity of startX
  if (startX < XValues.front()) {
    g_log.warning("StartX out of range! Set to start of frame.");
    startX = XValues.front();
  }
  // Get the corresponding bin boundary that comes before (or coincides with)
  // this value
  for (m_minX = 0; XValues[m_minX + 1] < startX; ++m_minX) {
  }

  // Check the validity of endX and get the bin boundary that come after (or
  // coincides with) it
  if (endX >= XValues.back() || endX < startX) {
    g_log.warning("EndX out of range! Set to end of frame");
    endX = XValues.back();
    m_maxX = static_cast<int>(YValues.size());
  } else {
    for (m_maxX = m_minX; XValues[m_maxX] < endX; ++m_maxX) {
    }
  }

  afterDataRangedDetermined(m_minX, m_maxX);

  // create and populate GSL data container warn user if l_data.n < l_data.p
  // since as a rule of thumb this is required as a minimum to obtained
  // 'accurate'
  // fitting parameter values.

  FitData l_data(this, getProperty("Fix"));

  l_data.n =
      m_maxX -
      m_minX; // m_minX and m_maxX are array index markers. I.e. e.g. 0 & 19.
  if (l_data.n == 0) {
    g_log.error("The data set is empty.");
    throw std::runtime_error("The data set is empty.");
  }
  if (l_data.n < l_data.p) {
    g_log.error(
        "Number of data points less than number of parameters to be fitted.");
    throw std::runtime_error(
        "Number of data points less than number of parameters to be fitted.");
  }
  l_data.X = new double[l_data.n];
  l_data.sigmaData = new double[l_data.n];
  l_data.forSimplexLSwrap = new double[l_data.n];
  l_data.parameters = new double[nParams()];

  // check if histogram data in which case use mid points of histogram bins

  const bool isHistogram = localworkspace->isHistogramData();
  for (unsigned int i = 0; i < l_data.n; ++i) {
    if (isHistogram)
      l_data.X[i] =
          0.5 * (XValues[m_minX + i] +
                 XValues[m_minX + i + 1]); // take mid-point if histogram bin
    else
      l_data.X[i] = XValues[m_minX + i];
  }

  l_data.Y = &YValues[m_minX];

  // check that no error is negative or zero
  for (unsigned int i = 0; i < l_data.n; ++i) {
    if (YErrors[m_minX + i] <= 0.0) {
      l_data.sigmaData[i] = 1.0;
    } else
      l_data.sigmaData[i] = YErrors[m_minX + i];
  }

  // create array of fitted parameter. Take these to those input by the user.
  // However, for doing the
  // underlying fitting it might be more efficient to actually perform the
  // fitting on some of other
  // form of the fitted parameters. For instance, take the Gaussian sigma
  // parameter. In practice it
  // in fact more efficient to perform the fitting not on sigma but 1/sigma^2.
  // The methods
  // modifyInitialFittedParameters() and modifyFinalFittedParameters() are used
  // to allow for this;
  // by default these function do nothing.

  m_fittedParameter.clear();
  for (size_t i = 0; i < nParams(); i++) {
    m_fittedParameter.push_back(getProperty(m_parameterNames[i]));
  }
  modifyInitialFittedParameters(
      m_fittedParameter); // does nothing except if overwritten by derived class
  for (size_t i = 0; i < nParams(); i++) {
    l_data.parameters[i] = m_fittedParameter[i];
  }

  // set-up initial guess for fit parameters

  gsl_vector *initFuncArg;
  initFuncArg = gsl_vector_alloc(l_data.p);

  for (size_t i = 0, j = 0; i < nParams(); i++) {
    if (l_data.active[i])
      gsl_vector_set(initFuncArg, j++, m_fittedParameter[i]);
  }

  // set-up GSL container to be used with GSL simplex algorithm

  gsl_multimin_function gslSimplexContainer;
  gslSimplexContainer.n = l_data.p; // n here refers to number of parameters
  gslSimplexContainer.f = &gsl_costFunction;
  gslSimplexContainer.params = &l_data;

  // set-up GSL least squares container

  gsl_multifit_function_fdf f;
  f.f = &gsl_f;
  f.df = &gsl_df;
  f.fdf = &gsl_fdf;
  f.n = l_data.n;
  f.p = l_data.p;
  f.params = &l_data;

  // set-up remaining GSL machinery for least squared

  const gsl_multifit_fdfsolver_type *T = gsl_multifit_fdfsolver_lmsder;
  gsl_multifit_fdfsolver *s = NULL;
  if (isDerivDefined) {
    s = gsl_multifit_fdfsolver_alloc(T, l_data.n, l_data.p);
    gsl_multifit_fdfsolver_set(s, &f, initFuncArg);
  }

  // set-up remaining GSL machinery to use simplex algorithm

  const gsl_multimin_fminimizer_type *simplexType =
      gsl_multimin_fminimizer_nmsimplex;
  gsl_multimin_fminimizer *simplexMinimizer = NULL;
  gsl_vector *simplexStepSize = NULL;
  if (!isDerivDefined) {
    simplexMinimizer = gsl_multimin_fminimizer_alloc(simplexType, l_data.p);
    simplexStepSize = gsl_vector_alloc(l_data.p);
    gsl_vector_set_all(simplexStepSize,
                       1.0); // is this always a sensible starting step size?
    gsl_multimin_fminimizer_set(simplexMinimizer, &gslSimplexContainer,
                                initFuncArg, simplexStepSize);
  }

  // finally do the fitting

  int iter = 0;
  int status;
  double finalCostFuncVal;
  double dof = static_cast<double>(
      l_data.n - l_data.p); // dof stands for degrees of freedom

  // Standard least-squares used if derivative function defined otherwise
  // simplex
  Progress prog(this, 0.0, 1.0, maxInterations);
  if (isDerivDefined) {

    do {
      iter++;
      status = gsl_multifit_fdfsolver_iterate(s);

      if (status) // break if error
        break;

      status = gsl_multifit_test_delta(s->dx, s->x, 1e-4, 1e-4);
      prog.report();
    } while (status == GSL_CONTINUE && iter < maxInterations);

    double chi = gsl_blas_dnrm2(s->f);
    finalCostFuncVal = chi * chi / dof;

    // put final converged fitting values back into m_fittedParameter
    for (size_t i = 0, j = 0; i < nParams(); i++)
      if (l_data.active[i])
        m_fittedParameter[i] = gsl_vector_get(s->x, j++);
  } else {
    do {
      iter++;
      status = gsl_multimin_fminimizer_iterate(simplexMinimizer);

      if (status) // break if error
        break;

      double size = gsl_multimin_fminimizer_size(simplexMinimizer);
      status = gsl_multimin_test_size(size, 1e-2);
      prog.report();
    } while (status == GSL_CONTINUE && iter < maxInterations);

    finalCostFuncVal = simplexMinimizer->fval / dof;

    // put final converged fitting values back into m_fittedParameter
    for (unsigned int i = 0, j = 0; i < m_fittedParameter.size(); i++)
      if (l_data.active[i])
        m_fittedParameter[i] = gsl_vector_get(simplexMinimizer->x, j++);
  }

  modifyFinalFittedParameters(
      m_fittedParameter); // do nothing except if overwritten by derived class

  // Output summary to log file

  std::string reportOfFit = gsl_strerror(status);

  g_log.information() << "Iteration = " << iter << "\n"
                      << "Status = " << reportOfFit << "\n"
                      << "Chi^2/DoF = " << finalCostFuncVal << "\n";
  for (size_t i = 0; i < m_fittedParameter.size(); i++)
    g_log.information() << m_parameterNames[i] << " = " << m_fittedParameter[i]
                        << "  \n";

  // also output summary to properties

  setProperty("OutputStatus", reportOfFit);
  setProperty("OutputChi2overDoF", finalCostFuncVal);
  for (size_t i = 0; i < m_fittedParameter.size(); i++)
    setProperty(m_parameterNames[i], m_fittedParameter[i]);

  std::string output = getProperty("Output");
  if (!output.empty()) {
    // calculate covariance matrix if derivatives available

    gsl_matrix *covar(NULL);
    std::vector<double> standardDeviations;
    std::vector<double> sdExtended;
    if (isDerivDefined) {
      covar = gsl_matrix_alloc(l_data.p, l_data.p);
      gsl_multifit_covar(s->J, 0.0, covar);

      int iPNotFixed = 0;
      for (size_t i = 0; i < nParams(); i++) {
        sdExtended.push_back(1.0);
        if (l_data.active[i]) {
          sdExtended[i] = sqrt(gsl_matrix_get(covar, iPNotFixed, iPNotFixed));
          iPNotFixed++;
        }
      }
      modifyFinalFittedParameters(sdExtended);
      for (size_t i = 0; i < nParams(); i++)
        if (l_data.active[i])
          standardDeviations.push_back(sdExtended[i]);

      declareProperty(
          new WorkspaceProperty<API::ITableWorkspace>(
              "OutputNormalisedCovarianceMatrix", "", Direction::Output),
          "The name of the TableWorkspace in which to store the final "
          "covariance matrix");
      setPropertyValue("OutputNormalisedCovarianceMatrix",
                       output + "_NormalisedCovarianceMatrix");

      Mantid::API::ITableWorkspace_sptr m_covariance =
          Mantid::API::WorkspaceFactory::Instance().createTable(
              "TableWorkspace");
      m_covariance->addColumn("str", "Name");
      std::vector<std::string>
          paramThatAreFitted; // used for populating 1st "name" column
      for (size_t i = 0; i < nParams(); i++) {
        if (l_data.active[i]) {
          m_covariance->addColumn("double", m_parameterNames[i]);
          paramThatAreFitted.push_back(m_parameterNames[i]);
        }
      }

      for (size_t i = 0; i < l_data.p; i++) {

        Mantid::API::TableRow row = m_covariance->appendRow();
        row << paramThatAreFitted[i];
        for (size_t j = 0; j < l_data.p; j++) {
          if (j == i)
            row << 1.0;
          else {
            row << 100.0 * gsl_matrix_get(covar, i, j) /
                       sqrt(gsl_matrix_get(covar, i, i) *
                            gsl_matrix_get(covar, j, j));
          }
        }
      }

      setProperty("OutputNormalisedCovarianceMatrix", m_covariance);
    }

    declareProperty(new WorkspaceProperty<API::ITableWorkspace>(
                        "OutputParameters", "", Direction::Output),
                    "The name of the TableWorkspace in which to store the "
                    "final fit parameters");
    declareProperty(
        new WorkspaceProperty<MatrixWorkspace>("OutputWorkspace", "",
                                               Direction::Output),
        "Name of the output Workspace holding resulting simlated spectrum");

    setPropertyValue("OutputParameters", output + "_Parameters");
    setPropertyValue("OutputWorkspace", output + "_Workspace");

    // Save the final fit parameters in the output table workspace
    Mantid::API::ITableWorkspace_sptr m_result =
        Mantid::API::WorkspaceFactory::Instance().createTable("TableWorkspace");
    m_result->addColumn("str", "Name");
    m_result->addColumn("double", "Value");
    if (isDerivDefined)
      m_result->addColumn("double", "Error");
    Mantid::API::TableRow row = m_result->appendRow();
    row << "Chi^2/DoF" << finalCostFuncVal;

    for (size_t i = 0; i < nParams(); i++) {
      Mantid::API::TableRow row = m_result->appendRow();
      row << m_parameterNames[i] << m_fittedParameter[i];
      if (isDerivDefined && l_data.active[i]) {
        // perhaps want to scale standard deviations with sqrt(finalCostFuncVal)
        row << sdExtended[i];
      }
    }
    setProperty("OutputParameters", m_result);

    // Save the fitted and simulated spectra in the output workspace
    MatrixWorkspace_const_sptr inputWorkspace = getProperty("InputWorkspace");
    int iSpec = getProperty("WorkspaceIndex");
    const MantidVec &inputX = inputWorkspace->readX(iSpec);
    const MantidVec &inputY = inputWorkspace->readY(iSpec);

    int histN = isHistogram ? 1 : 0;
    Mantid::DataObjects::Workspace2D_sptr ws =
        boost::dynamic_pointer_cast<Mantid::DataObjects::Workspace2D>(
            Mantid::API::WorkspaceFactory::Instance().create(
                "Workspace2D", 3, l_data.n + histN, l_data.n));
    ws->setTitle("");
    ws->getAxis(0)->unit() =
        inputWorkspace->getAxis(0)
            ->unit(); //    UnitFactory::Instance().create("TOF");

    for (int i = 0; i < 3; i++)
      ws->dataX(i)
          .assign(inputX.begin() + m_minX, inputX.begin() + m_maxX + histN);

    ws->dataY(0).assign(inputY.begin() + m_minX, inputY.begin() + m_maxX);

    MantidVec &Y = ws->dataY(1);
    MantidVec &E = ws->dataY(2);

    double *lOut =
        new double[l_data.n]; // to capture output from call to function()
    modifyInitialFittedParameters(m_fittedParameter); // does nothing except if
                                                      // overwritten by derived
                                                      // class
    function(&m_fittedParameter[0], lOut, l_data.X, l_data.n);
    modifyInitialFittedParameters(m_fittedParameter); // reverse the effect of
    // modifyInitialFittedParameters - if any

    for (unsigned int i = 0; i < l_data.n; i++) {
      Y[i] = lOut[i];
      E[i] = l_data.Y[i] - Y[i];
    }

    delete[] lOut;

    setProperty("OutputWorkspace",
                boost::dynamic_pointer_cast<MatrixWorkspace>(ws));

    if (isDerivDefined)
      gsl_matrix_free(covar);
  }

  // clean up dynamically allocated gsl stuff

  if (isDerivDefined)
    gsl_multifit_fdfsolver_free(s);
  else {
    gsl_vector_free(simplexStepSize);
    gsl_multimin_fminimizer_free(simplexMinimizer);
  }

  delete[] l_data.X;
  delete[] l_data.sigmaData;
  delete[] l_data.forSimplexLSwrap;
  delete[] l_data.parameters;
  gsl_vector_free(initFuncArg);

  return;
}
Beispiel #25
0
 std::string hash(const unsigned char* input, size_t length) const
 {
     mbedtls_md(md, input, length, &buf.front());
     return BinToHex(&buf.front(), buf.size());
 }
Beispiel #26
0
void pca::set_weights(std::vector<double> &weights)
{
    w_.resize(weights.size());
    arma::Col<double> col(&weights.front(), weights.size());
    w_.col(0) = std::move(col);
}
Beispiel #27
0
static void getResultStructure(
    CodeCompletion::SwiftResult *result, bool leadingPunctuation,
    CodeCompletionInfo::DescriptionStructure &structure,
    std::vector<CodeCompletionInfo::ParameterStructure> &parameters) {
  auto *CCStr = result->getCompletionString();
  auto FirstTextChunk = CCStr->getFirstTextChunkIndex(leadingPunctuation);

  if (!FirstTextChunk.hasValue())
    return;

  bool isOperator = result->isOperator();

  auto chunks = CCStr->getChunks();
  using ChunkKind = CodeCompletionString::Chunk::ChunkKind;

  unsigned i = *FirstTextChunk;
  unsigned textSize = 0;

  // The result name.
  for (; i < chunks.size(); ++i) {
    auto C = chunks[i];
    if (C.is(ChunkKind::TypeAnnotation) ||
        C.is(ChunkKind::CallParameterClosureType) ||
        C.is(ChunkKind::Whitespace))
      continue;

    if (C.is(ChunkKind::LeftParen) || C.is(ChunkKind::LeftBracket) ||
        C.is(ChunkKind::BraceStmtWithCursor) ||
        C.is(ChunkKind::CallParameterBegin))
      break;

    if (C.is(ChunkKind::Equal))
      isOperator = true;

    if (C.hasText())
      textSize += C.getText().size();
  }

  structure.baseName.begin = 0;
  structure.baseName.end = textSize;

  // The parameters.
  for (; i < chunks.size(); ++i) {
    auto C = chunks[i];
    if (C.is(ChunkKind::TypeAnnotation) ||
        C.is(ChunkKind::CallParameterClosureType) ||
        C.is(ChunkKind::Whitespace))
      continue;

    if (C.is(ChunkKind::BraceStmtWithCursor))
      break;

    if (C.is(ChunkKind::ThrowsKeyword) ||
        C.is(ChunkKind::RethrowsKeyword)) {
      structure.throwsRange.begin = textSize;
      structure.throwsRange.end = textSize + C.getText().size();
    }

    if (C.is(ChunkKind::CallParameterBegin)) {
      CodeCompletionInfo::ParameterStructure param;

      ++i;
      bool inName = false;
      bool inAfterColon = false;
      for (; i < chunks.size(); ++i) {
        if (chunks[i].endsPreviousNestedGroup(C.getNestingLevel()))
          break;
        if (chunks[i].is(ChunkKind::CallParameterClosureType))
          continue;
        if (isOperator && chunks[i].is(ChunkKind::CallParameterType))
          continue;

        // Parameter name
        if (chunks[i].is(ChunkKind::CallParameterName) ||
            chunks[i].is(ChunkKind::CallParameterInternalName)) {
          param.name.begin = textSize;
          param.isLocalName =
              chunks[i].is(ChunkKind::CallParameterInternalName);
          inName = true;
        }

        // Parameter type
        if (chunks[i].is(ChunkKind::CallParameterType)) {
          unsigned start = textSize;
          unsigned prev = i - 1; // if i == 0, prev = ~0u.

          // Combine & for inout into the type name.
          if (prev != ~0u && chunks[prev].is(ChunkKind::Ampersand)) {
            start -= chunks[prev].getText().size();
            prev -= 1;
          }

          // Combine the whitespace after ':' into the type name.
          if (prev != ~0u && chunks[prev].is(ChunkKind::CallParameterColon))
            start -= 1;

          param.afterColon.begin = start;
          inAfterColon = true;
          if (inName) {
            param.name.end = start;
            inName = false;
          }
        }

        if (chunks[i].hasText())
          textSize += chunks[i].getText().size();
      }

      // If we had a name with no type following it, finish it now.
      if (inName)
        param.name.end = textSize;

      // Finish the type name.
      if (inAfterColon)
        param.afterColon.end = textSize;
      if (!param.range().empty())
        parameters.push_back(std::move(param));

      if (chunks[i].hasText())
        textSize += chunks[i].getText().size();
    }

    if (C.hasText())
      textSize += C.getText().size();
  }

  if (!parameters.empty()) {
    structure.parameterRange.begin = parameters.front().range().begin;
    structure.parameterRange.end = parameters.back().range().end;
  }
}
Beispiel #28
0
void PrivateKeyInfoCodec::PrependInteger(const std::vector<uint8>& in,
                                         std::list<uint8>* out) {
  uint8* ptr = const_cast<uint8*>(&in.front());
  PrependIntegerImpl(ptr, in.size(), out, big_endian_);
}
jintArray AndroidUtil::createJavaIntArray(JNIEnv *env, const std::vector<jint> &data) {
	std::size_t size = data.size();
	jintArray array = env->NewIntArray(size);
	env->SetIntArrayRegion(array, 0, size, &data.front());
	return array;
}
Beispiel #30
0
Color Ray::computeColor(const Pos3 &camPos, const std::vector<Object*> &obj, const std::vector<Light*> &lights, unsigned iteration){
    // Loop through the scene for each ray to determine intersection points
    float distanceAlongRay;
    std::vector<distMatPair> depthTest;
    Direction surfaceNormal;

    //store the distance and surface normal from ray origin to intersection and color
    for(unsigned i = 0; i < obj.size(); ++i)
         if(obj[i]->calculateIntersection(startPoint_, direction_, distanceAlongRay, &surfaceNormal))
            depthTest.push_back( distMatPair( Pos4(surfaceNormal, distanceAlongRay ), obj[i]->getMaterial()) );


    Color localLighting = BLACK;
    Color reflectedRayColor = BLACK;
    Color refractedRayColor = BLACK;

    if(!depthTest.empty()){
        // sort intersections, we only care about the closest intersection
        std::sort(depthTest.begin(), depthTest.end(), compareDistance);
        distMatPair closestIntersection = depthTest.front();

        if(russianRoulette(closestIntersection.second) ){ /* keep this for whitted ray tracing */ // iteration <= RAY_MAX_BOUNCE){

            surfaceNormal = Direction(closestIntersection.first);

            switch(closestIntersection.second.property){
                case LAMBERTIAN:
                {
                    float childImportance = 0.f;
                    //if(NO_MT_CARLO_RAYS != 0){
                    for(unsigned i = 0; i < NO_MT_CARLO_RAYS; ++i){
                        Ray reflectedRay = computeReflectionRay(surfaceNormal, lights, closestIntersection);
                        reflectedRay.setImportance(reflectedRay.importance_*COLOR_BLEED/NO_MT_CARLO_RAYS);
                        childImportance += reflectedRay.importance_;
                        if(childImportance > 0.f)
                            reflectedRayColor += reflectedRay.computeColor(camPos, obj, lights, ++iteration);
                    }
                    localLighting = (1.f-childImportance)*computeLocalLighting(camPos, obj, lights, closestIntersection);
                    break;
                }

                case GLOSSY:
                {
                    Ray reflectedRay = computeReflectionRay(surfaceNormal, lights, closestIntersection);
                    reflectedRayColor = reflectedRay.computeColor(camPos, obj, lights, ++iteration);
                    break;
                }

                case TRANSPARENT:
                {
                    Ray refractedRay;
                    bool refraction = false;
                    if(insideObject_){
                        //alpha testing, if ray can be transmitted to air again
                        float alpha = std::acos(glm::dot(surfaceNormal, direction_));       //want positive angle
                        surfaceNormal = -surfaceNormal;
                        float alphaMax = std::asin(AIR_INDEX/GLASS_INDEX);

                        if(alpha < alphaMax){
                            refractedRay = computeRefractionRay(surfaceNormal, closestIntersection);
                            refraction = true;
                        }
                    }
                    else{
                        refractedRay = computeRefractionRay(surfaceNormal, closestIntersection);
                        refraction = true;
                    }
                    Ray reflectedRay = computeReflectionRay(surfaceNormal, lights, closestIntersection);
                    //if frefraction ray, compensate importance
                    if(refraction){
                        reflectedRay.setImportance(1.f - refractedRay.importance_);
                        refractedRayColor = refractedRay.computeColor(camPos, obj, lights, ++iteration);
                    }

                    reflectedRayColor = reflectedRay.computeColor(camPos, obj, lights, ++iteration);
                    break;
                }

                case EMISSIVE:
                {
                    localLighting = lights.front()->getColor();
                    break;
                }
            }
        }
    }

    return importance_*(localLighting + reflectedRayColor + refractedRayColor)/russianP_;
};