本文整理汇总了C++中std::vector::front方法的典型用法代码示例。如果您正苦于以下问题:C++ vector::front方法的具体用法?C++ vector::front怎么用?C++ vector::front使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类std::vector
的用法示例。
在下文中一共展示了vector::front方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C++代码示例。
示例1: addGeometry
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 !
//.........这里部分代码省略.........
示例2: Solver
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)
{
//.........这里部分代码省略.........
示例3:
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)
//.........这里部分代码省略.........
示例4: create
static type create(const std::vector<double>& t) { return type(&t.front()); }
示例5: get
const mbedtls_ecp_group_id* get() const {
return &list.front();
}
示例6: init
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;
}
示例7: InterpretType
//.........这里部分代码省略.........
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);
}
}
示例8: insert_in_parent
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;
//.........这里部分代码省略.........
示例9: Solver
/**
* 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)
//.........这里部分代码省略.........
示例10: ProcessWordsBackTrack
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);
}
}
示例11: solve
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
}
}
示例12: recursiveSearchKNearestNeighbours
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);
}
}
}
示例13: compute_shared_key
bool diffie_hellman::compute_shared_key( const std::vector<char>& pubk ) {
return compute_shared_key( &pubk.front(), pubk.size() );
}
示例14: splitChunkAtMultiplePoints
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>();
}
示例15: DeadlyImportError
// ------------------------------------------------------------------------------------------------
// 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;
}
}