<commit_before>#include "environment.h"

environment::environment()
{
    //curBudget_ = 0;
    algo_ = ml::LINEAR_REGRESSION;
    budget_ = 1;
}

void environment::read_from_stream(vw* model, istream &fin)
{
    string line;
    while (true)
    {
	getline(fin, line, '\n');
	if ( line.empty())
	    break;
	item tmp;
	tmp.init_example(model, &line[0]);
	items_.push_back(tmp);
    }
}

void environment::linear_regression(vw* model, int numPasses)
{
    for (int ct = 0; ct < numPasses; ct++)
	{
	    //   cout << "Passes " << ct << endl;
	    for (int i = 0; i < items_.size(); i++)
		{
		    //  cout << "regress on " << i <<endl;
		    items_[i].vw_create_example(model);
		    model->learn(items_[i].ex);
		    items_[i].release_vwexample(model);
		    //   cout << "train " << ((label_data*) items_[i].ex->ld)->label << " ::: " << items_[i].ex->final_prediction << endl;
		}
	}
}

void environment::svm_rank(vw* model, int numPasses)
{
    cout << "start svm_rank binary classification" <<endl;
    for (int ct = 0; ct < numPasses; ct++)
	{
	    for (int i = 0; i < items_.size(); i++)
		{
		    for (int j = 0; j < items_.size(); j++)
			if (i != j)
			    {

				//	cout << i << ";" << j <<endl;
				//	cout << "progress " << double(i)/items_.size() <<endl;
				char str[charN];
				// char *str = new char[charN];
				//  str = NULL;
				//  strcpy(str, items_[i].get_diff_str(items_[j]));
				items_[i].get_diff_str(items_[j], str);
				if (!strcmp(str, "\0"))
				    {
					//			cout << "label equal" <<endl;
					continue;
				    }

				// items_[i].get_diff_str(items_[j], str);
				//	cout <<"str:" << str <<endl;
				example *ex = VW::read_example(*model, str);
				model->learn(ex);
				//				cout << "learn" <<endl;
				VW::finish_example(*model, ex);
				//cout << "free example" <<endl;
				// delete []str;
			    }
		    //   items_[i].release_vwexample(model);
		}
	}
}

double environment::get_dis2set(item & itm)
{
    //return sum of distance
    double sumDis = 0;
    for (int i = 0; i < predList_.size(); i++)
	{
	    sumDis += itm.compute_simDis(items_[predList_[i]]);
	}
       return sumDis;
}
vector<double> environment::getVecSimVals()
{
    //return the normalized inverse sum of distance similarity
    double sumDisVal = 0;
    double minDisVal = 0;
    vector<double> recSumDists;
    double maxSumDis = -1e+9;
    for (int i = 0; i < items_.size(); i++)
	{
	    //sum of dis
	    sumDisVal = get_dis2set(items_[i]);
	    recSumDists.push_back(sumDisVal);
	    maxSumDis = (maxSumDis > sumDisVal)? maxSumDis: sumDisVal;
	}

    for (int i = 0; i < items_.size(); i++)
	{
	    recSumDists[i] = 1 - recSumDists[i]/maxSumDis;
	}

    return recSumDists;
}
void environment::updateSimFeatures(vw* model, submodOracle & fOracle)
{
    //get the submodular values for things in the predList_
    // double predListScore = 0;
    cout << "updateFeatures" << endl;
    vector<simpleItem> predListItems;
    for (int i = 0; i < predList_.size(); i++)
	{
	    simpleItem tmpItem;
	    tmpItem.itemId = predList_[i];
	    tmpItem.envId = items_[tmpItem.itemId].get_envId();
	    tmpItem.label = items_[tmpItem.itemId].get_label();
	    predListItems.push_back(tmpItem);
	}

    vector<double> vecSumSim = getVecSimVals();
    double newLabel = 0;
    for (int i = 0; i < items_.size(); i++)
	{
	    vector<feat_pair> vec_feat;
	    feat_pair featPair;
	    featPair.featId = featIndex::SUMSIM;
	    featPair.val = vecSumSim[i];
	    //    cout << "Similarity for item " << i << " to predList :" << featPair.val << endl;

	    vec_feat.push_back(featPair);

	    // compute marginal gain and update label
	    simpleItem tmpItem;
	    tmpItem.itemId = i;
	    tmpItem.envId = items_[tmpItem.itemId].get_envId();
	    tmpItem.label = items_[tmpItem.itemId].get_label();
	    newLabel = fOracle.getMarginalScore(predListItems, tmpItem);
	    //    cout << "newLabel " <<newLabel << endl;
	    items_[i].update_example(model, vec_feat, newLabel, true);
	    //need to check whether budget overflow
	}
}

void environment::updateSimFeaturesPredictOnly(vw* model)
{
    vector<double> vecSumSim = getVecSimVals();
    for (int i = 0; i < items_.size(); i++)
	{
	    vector<feat_pair> vec_feat;
	    feat_pair featPair;
	    featPair.featId = featIndex::SUMSIM;
	    featPair.val = vecSumSim[i];
	    vec_feat.push_back(featPair);

	    // no need to update label, cuz it's prediction only
	    items_[i].update_example(model, vec_feat);
	    //need to check whether budget overflow
	}
}

void environment::oneRoundTrain(vw* model, int numPasses)
{
    cout <<"startOneRoundTraining" <<endl;
    model->training = true;
    if (algo_ == ml::LINEAR_REGRESSION)
	{
	    linear_regression(model, numPasses);
	}
    else if (algo_ == ml::SVM_RANK)
	{
	    svm_rank(model, numPasses);
	}
}

void environment::oneRoundPrediction(vw* model, bool useGreedyOracle )
{
    cout << "startoneRoundPrediction" <<endl;
    double maxValue = -1e10;
    int maxItemId = -1;
    double modelPredScore = 0;
    model->training = false;
    haveSpace_ = false;
    for (int i = 0; i < items_.size(); i++)
	{
	    if (!useGreedyOracle)  //if use model prediction
		{
		    //vw will produce warning here because it will see non-binary labels, but for prediction, label does not matter
		    items_[i].vw_create_example(model);
		    if (algo_ == ml::SVM_RANK)
			((label_data*) items_[i].ex->ld)->label = 1;
		    model->learn(items_[i].ex);
		    modelPredScore = items_[i].ex->final_prediction;
		    items_[i].release_vwexample(model);
		}
	    else  //if use greedy ground truth, note label is updated as marginal gain
		{
		    // modelPredScore  = ((label_data*) items_[i].ex->ld)->label;
		    modelPredScore = items_[i].get_label();
		}
	    //    cout << "predictStatus for Item " << i << ": gdScore " << ((label_data*) items_[i].ex->ld)->label << " vwScore " << items_[i].ex->final_prediction <<endl;
	    if ( curBudget_ + items_[i].size > budget_ )
		{
		    tag_usable[i] = false;
		}
	    if ( modelPredScore > maxValue && tag_usable[i])  //find largest
		{
		    maxValue = modelPredScore;
		    maxItemId = i;
		    if (curBudget_ + items_[i].size < budget_)
			haveSpace_ = true;
		}
	}
    if (maxItemId != -1)
	{
	    predList_.push_back(maxItemId);
	    curBudget_ += items_[maxItemId].size;
	    //both for cardinality and knapsack constraint
	    curSubModScore_ += maxValue * items_[maxItemId].size;
	    tag_usable[maxItemId] = false;
	}
    //display prediction information
    for (int i = 0; i < predList_.size(); i++)
	{
	    cout << predList_[i] << ",";
	}
    cout << " currentSubModScore:  " << curSubModScore_ << endl;
    cout << " currentBudget: " << curBudget_<< endl;
}

void environment::multiRoundTrain(vw* model, submodOracle & fOracle, bool useGreedyPolicy, int numPasses)
{
    curBudget_ = 0;
    curSubModScore_ = 0;
    haveSpace_ = true;
    tag_usable = new bool[items_.size()];
    memset(tag_usable, true , sizeof(bool) * items_.size());
    while (haveSpace_)
	{
	    cout << "trainingOneRound" << endl;
	    oneRoundTrain(model, numPasses);
	    //if useGreedyPolicy is true
	    oneRoundPrediction(model, useGreedyPolicy);
	    updateSimFeatures(model, fOracle);
	}

     getPerSlotScore(fOracle);
     //  release_items_vwexample(model);
}

void environment::multiRoundPredictOnly(vw* model)
{
    curBudget_ = 0;
    curSubModScore_ = 0;
    haveSpace_ = true;
    tag_usable = new bool[items_.size()];
    memset(tag_usable, true , sizeof(bool) * items_.size());
    while (haveSpace_)
	{
	    oneRoundPrediction(model);
	    updateSimFeaturesPredictOnly(model);
	}
    //   release_items_vwexample(model);
}

vector<double> environment::getPerSlotScore( submodOracle & fOracle)
{
    vector<simpleItem> predListItems;
    double gain = 0 ;
    double fVal = 0;
    vector<double> perSlotScore;
    for (int pos = 0; pos < predList_.size(); pos++)
	{
	    //create partial list
	    predListItems.clear();
	    for (int i = 0; i < pos; i++)
		{
		    simpleItem tmpItem;
		    tmpItem.itemId = predList_[i];
		    tmpItem.envId = items_[tmpItem.itemId].get_envId();
		    tmpItem.label = items_[tmpItem.itemId].get_label();
		    predListItems.push_back(tmpItem);
		}
	    simpleItem tmpItem;
	    tmpItem.itemId = predList_[pos];
	    tmpItem.envId = items_[tmpItem.itemId].get_envId();
	    tmpItem.label = items_[tmpItem.itemId].get_label();
	    gain = fOracle.getMarginalScore(predListItems, tmpItem)  ;
	    //	    cout << "PredictList at Pos " << pos << " have marginal gain : " << gain <<endl;
	    fVal += gain;
	    perSlotScore.push_back(fVal);
	    cout << "PredictList at Pos " << pos << " is " << predList_[pos] << " , has submod value : " << fVal << endl;
	}
    return perSlotScore;
}

void environment::release_items_vwexample(vw* model)
{
    for (int i = 0; i < items_.size(); i++)
	{
	    items_[i].release_vwexample(model);
	}
}

<commit_msg>Delete environment.cpp<commit_after><|endoftext|>


<commit_before>#include "csvmodelwriter.h"

#include <QAbstractItemModel>
#include <QFile>
#include <QTextStream>

CSVModelWriter::CSVModelWriter(const QString &filename, QObject *parent) :
    QObject(parent),
    filename(filename)
{
}

void CSVModelWriter::setModel(const QAbstractItemModel *model)
{
    this->model = model;
}

void CSVModelWriter::addColumn(const QString &title, int column, int role)
{
    Column col;
    col.title = title;
    col.column = column;
    col.role = role;

    columns.append(col);
}

static void writeValue(QTextStream &f, const QString &value)
{
    // TODO: quoting if " or \n in string
    f << "\"" << value << "\"";
}

static void writeSep(QTextStream &f)
{
    f << ",";
}

static void writeNewline(QTextStream &f)
{
    f << "\n";
}

bool CSVModelWriter::write()
{
    QFile file(filename);
    if(!file.open(QIODevice::WriteOnly | QIODevice::Text))
        return false;
    QTextStream out(&file);

    int numRows = 0;
    if(model)
    {
        numRows = model->rowCount();
    }

    // Header row
    for(int i=0; i<columns.size(); ++i)
    {
        if(i!=0)
        {
            writeSep(out);
        }
        writeValue(out, columns[i].title);
    }
    writeNewline(out);

    // Data rows
    for(int j=0; j<numRows; ++j)
    {
        for(int i=0; i<columns.size(); ++i)
        {
            if(i!=0)
            {
                writeSep(out);
            }
            QVariant data = model->index(j, columns[i].column).data(columns[i].role);
            writeValue(out, data.toString());
        }
        writeNewline(out);
    }

    file.close();

    return file.error() == QFile::NoError;
}

<commit_msg>Add forgotten initializer<commit_after>#include "csvmodelwriter.h"

#include <QAbstractItemModel>
#include <QFile>
#include <QTextStream>

CSVModelWriter::CSVModelWriter(const QString &filename, QObject *parent) :
    QObject(parent),
    filename(filename), model(0)
{
}

void CSVModelWriter::setModel(const QAbstractItemModel *model)
{
    this->model = model;
}

void CSVModelWriter::addColumn(const QString &title, int column, int role)
{
    Column col;
    col.title = title;
    col.column = column;
    col.role = role;

    columns.append(col);
}

static void writeValue(QTextStream &f, const QString &value)
{
    // TODO: quoting if " or \n in string
    f << "\"" << value << "\"";
}

static void writeSep(QTextStream &f)
{
    f << ",";
}

static void writeNewline(QTextStream &f)
{
    f << "\n";
}

bool CSVModelWriter::write()
{
    QFile file(filename);
    if(!file.open(QIODevice::WriteOnly | QIODevice::Text))
        return false;
    QTextStream out(&file);

    int numRows = 0;
    if(model)
    {
        numRows = model->rowCount();
    }

    // Header row
    for(int i=0; i<columns.size(); ++i)
    {
        if(i!=0)
        {
            writeSep(out);
        }
        writeValue(out, columns[i].title);
    }
    writeNewline(out);

    // Data rows
    for(int j=0; j<numRows; ++j)
    {
        for(int i=0; i<columns.size(); ++i)
        {
            if(i!=0)
            {
                writeSep(out);
            }
            QVariant data = model->index(j, columns[i].column).data(columns[i].role);
            writeValue(out, data.toString());
        }
        writeNewline(out);
    }

    file.close();

    return file.error() == QFile::NoError;
}

<|endoftext|>


<commit_before>// Copyright (c) 2011-2014 The Bitcoin developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.

#include "lookupspdialog.h"
#include "ui_lookupspdialog.h"

#include "guiutil.h"
#include "optionsmodel.h"
#include "walletmodel.h"
#include "wallet.h"
#include "base58.h"
#include "ui_interface.h"

#include <boost/filesystem.hpp>

#include "leveldb/db.h"
#include "leveldb/write_batch.h"

// potentially overzealous includes here
#include "base58.h"
#include "rpcserver.h"
#include "init.h"
#include "util.h"
#include <fstream>
#include <algorithm>
#include <vector>
#include <utility>
#include <string>
#include <boost/assign/list_of.hpp>
#include <boost/algorithm/string.hpp>
#include <boost/algorithm/string/find.hpp>
#include <boost/algorithm/string/join.hpp>
#include <boost/lexical_cast.hpp>
#include <boost/format.hpp>
#include <boost/filesystem.hpp>
#include "json/json_spirit_utils.h"
#include "json/json_spirit_value.h"
#include "leveldb/db.h"
#include "leveldb/write_batch.h"
// end potentially overzealous includes

using namespace json_spirit;
#include "mastercore.h"
using namespace mastercore;

// potentially overzealous using here
using namespace std;
using namespace boost;
using namespace boost::assign;
using namespace leveldb;
// end potentially overzealous using

#include "mastercore_dex.h"
#include "mastercore_tx.h"
#include "mastercore_sp.h"

#include <QMessageBox>
#include <QScrollBar>
#include <QTextDocument>
#include <QDateTime>

LookupSPDialog::LookupSPDialog(QWidget *parent) :
    QDialog(parent),
    ui(new Ui::LookupSPDialog),
    model(0)
{
    ui->setupUi(this);
    this->model = model;

    // populate placeholder text
    ui->searchLineEdit->setPlaceholderText("ID, name or issuer");

    // connect actions
    connect(ui->matchingComboBox, SIGNAL(activated(int)), this, SLOT(matchingComboBoxChanged(int)));
    connect(ui->searchButton, SIGNAL(clicked()), this, SLOT(searchButtonClicked()));

    // hide crowd info
    ui->desired->setVisible(false);
    ui->tokensperunit->setVisible(false);
    ui->deadline->setVisible(false);
    ui->bonus->setVisible(false);
    ui->issuerperc->setVisible(false);
    ui->desiredLabel->setVisible(false);
    ui->tokensPerUnitLabel->setVisible(false);
    ui->deadlineLabel->setVisible(false);
    ui->bonusLabel->setVisible(false);
    ui->issuerPercLabel->setVisible(false);
    ui->activeLabel->setVisible(false);
    ui->active->setText("Not applicable.");
    ui->topFrame->setVisible(false);
    ui->leftFrame->setVisible(false);
    ui->rightFrame->setVisible(false);
}

void LookupSPDialog::searchSP()
{
    // search function to lookup properties, we want this search function to be as capable as possible to
    // help users find the property they're looking for via search terms they may want to use
    int searchParamType = 0;
    string searchText = ui->searchLineEdit->text().toStdString();
    unsigned int searchPropertyId = 0;

    // first let's check if we have a searchText, if not do nothing
    if (searchText.empty()) return;

    // try seeing if we have a numerical search string, if so treat it as a property ID search
    try
    {
        searchPropertyId = boost::lexical_cast<int64_t>(searchText);
        searchParamType = 1; // search by propertyId
    }
    catch(const boost::bad_lexical_cast &e) { }
    if (searchParamType == 1 && 0 >= searchPropertyId) searchParamType = 0; // we got a number but it's <=0

    // next if not positive numerical, lets see if the string is a valid bitcoin address for issuer search
    if (searchParamType == 0)
    {
        CBitcoinAddress address;
        address.SetString(searchText); // no null check on searchText required we've already checked it's not empty above
        if (address.IsValid()) searchParamType = 2; // search by address;
    }

    // if we still don't have a param we'll search against free text in the name
    if (searchParamType == 0) searchParamType = 3; // search by free text

    // clear matching results combo
    ui->matchingComboBox->clear();
    bool spExists;
    unsigned int tmpPropertyId;
    unsigned int nextSPID;
    unsigned int nextTestSPID;
    unsigned int propertyId;
    QString strId;
    switch(searchParamType)
    {
        case 1: //search by property Id
           // convert search string to ID
           strId = QString::fromStdString(searchText);
           propertyId = strId.toUInt();
           // check if this property ID exists, if not no match to populate and just return
           spExists = _my_sps->hasSP(propertyId);
           if (spExists)
           {
               addSPToMatchingResults(propertyId);
               updateDisplayedProperty(); //show straight away, only one to select
           }
           else
           {
               return;
           }
        break;
        case 2: //search by address
           // iterate through my_sps looking for the issuer address and add any properties issued by said address to matchingcombo
           // talk with @Michael @Bart to see if perhaps a more efficient way to do this, but not major issue as only run on user request
           nextSPID = _my_sps->peekNextSPID(1);
           nextTestSPID = _my_sps->peekNextSPID(2);
           for (tmpPropertyId = 1; tmpPropertyId<nextSPID; tmpPropertyId++)
           {
               CMPSPInfo::Entry sp;
               if (false != _my_sps->getSP(tmpPropertyId, sp))
               {
                   if (sp.issuer == searchText)
                   {
                       addSPToMatchingResults(tmpPropertyId);
                   }
               }
           }
           for (tmpPropertyId = TEST_ECO_PROPERTY_1; tmpPropertyId<nextTestSPID; tmpPropertyId++)
           {
               CMPSPInfo::Entry sp;
               if (false != _my_sps->getSP(tmpPropertyId, sp))
               {
                   if (sp.issuer == searchText)
                   {
                       addSPToMatchingResults(tmpPropertyId);
                   }
               }
           }
        break;
        case 3: //search by freetext
           // iterate through my_sps and see if property name contains the search text
           nextSPID = _my_sps->peekNextSPID(1);
           nextTestSPID = _my_sps->peekNextSPID(2);
           for (tmpPropertyId = 1; tmpPropertyId<nextSPID; tmpPropertyId++)
           {
               CMPSPInfo::Entry sp;
               if (false != _my_sps->getSP(tmpPropertyId, sp))
               {
                   // make the search case insensitive
                   string lowerName = sp.name;
                   std::transform(lowerName.begin(), lowerName.end(), lowerName.begin(), ::tolower);
                   string lowerSearch = searchText;
                   std::transform(lowerSearch.begin(), lowerSearch.end(), lowerSearch.begin(), ::tolower);
                   size_t loc = lowerName.find(lowerSearch);
                   if (loc!=std::string::npos)
                   {
                       addSPToMatchingResults(tmpPropertyId);
                   }
               }
           }
           for (tmpPropertyId = TEST_ECO_PROPERTY_1; tmpPropertyId<nextTestSPID; tmpPropertyId++)
           {
               CMPSPInfo::Entry sp;
               if (false != _my_sps->getSP(tmpPropertyId, sp))
               {
                   // make the search case insensitive
                   string lowerName = sp.name;
                   std::transform(lowerName.begin(), lowerName.end(), lowerName.begin(), ::tolower);
                   string lowerSearch = searchText;
                   std::transform(lowerSearch.begin(), lowerSearch.end(), lowerSearch.begin(), ::tolower);
                   size_t loc = lowerName.find(lowerSearch);
                   if (loc!=std::string::npos)
                   {
                       addSPToMatchingResults(tmpPropertyId);
                   }
               }
           }
        break;
    }

}

void LookupSPDialog::addSPToMatchingResults(unsigned int propertyId)
{
    // verify the supplied property exists (sanity check) then populate the matching results combo box
    bool spExists = _my_sps->hasSP(propertyId);
    if (spExists)
    {
        string spName;
        spName = getPropertyName(propertyId).c_str();
        if(spName.size()>50) spName=spName.substr(0,50)+"...";
        string spId = static_cast<ostringstream*>( &(ostringstream() << propertyId) )->str();
        spName += " (#" + spId + ")";
        ui->matchingComboBox->addItem(spName.c_str(),spId.c_str());
    }
    else
    {
        return;
    }
}

void LookupSPDialog::updateDisplayedProperty()
{
    QString strId = ui->matchingComboBox->itemData(ui->matchingComboBox->currentIndex()).toString();
    // protect against an empty matchedComboBox
    if (strId.toStdString().empty()) return;

    // map property Id
    unsigned int propertyId = strId.toUInt();
    CMPSPInfo::Entry sp;
    if (false == _my_sps->getSP(propertyId, sp)) { return; } // something has gone wrong, don't attempt to display non-existent property

    // populate the fields
    bool divisible=sp.isDivisible();
    if (divisible) { ui->divisibleLabel->setText("Yes"); } else { ui->divisibleLabel->setText("No"); }
    if (propertyId>2147483647) { ui->ecosystemLabel->setText("Test"); } else { ui->ecosystemLabel->setText("Production"); }
    ui->propertyIDLabel->setText(QString::fromStdString(FormatIndivisibleMP(propertyId)));
    ui->nameLabel->setText(QString::fromStdString(sp.name));
    ui->categoryLabel->setText(QString::fromStdString(sp.category + " > " + sp.subcategory));
    ui->dataLabel->setText(QString::fromStdString(sp.data));
    ui->urlLabel->setText(QString::fromStdString(sp.url));
    string strTotalTokens;
    string strWalletTokens;
    int64_t totalTokens = getTotalTokens(propertyId);
    int64_t walletTokens = 0;
    if (propertyId<2147483648)
    { walletTokens = global_balance_money_maineco[propertyId]; }
    else
    { walletTokens = global_balance_money_testeco[propertyId-2147483647]; }
    string tokenLabel;
    if (propertyId > 2)
    {
       tokenLabel = " SPT";
    }
    else
    {
       if (propertyId == 1) { tokenLabel = " MSC"; } else { tokenLabel = " TMSC"; }
    }
    if (divisible) { strTotalTokens = FormatDivisibleMP(totalTokens); } else { strTotalTokens = FormatIndivisibleMP(totalTokens); }
    if (divisible) { strWalletTokens = FormatDivisibleMP(walletTokens); } else { strWalletTokens = FormatIndivisibleMP(walletTokens); }
    ui->totalTokensLabel->setText(QString::fromStdString(strTotalTokens + tokenLabel));
    ui->walletBalanceLabel->setText(QString::fromStdString(strWalletTokens + tokenLabel));
    ui->issuerLabel->setText(QString::fromStdString(sp.issuer));
    bool fixedIssuance = sp.fixed;
    bool manualIssuance = sp.manual;
    if ((!fixedIssuance) && (!manualIssuance) && (propertyId > 2))
    {
        ui->issuanceTypeLabel->setText("Crowdsale");
        // obtain crowdinfo
        bool active = isCrowdsaleActive(propertyId);
        int64_t deadline = sp.deadline;
        uint8_t earlyBonus = sp.early_bird;
        uint8_t percentToIssuer = sp.percentage;
        int64_t tokensPerUnit = sp.num_tokens;
        int64_t propertyIdDesired = sp.property_desired;
        QDateTime qDeadline;
        qDeadline.setTime_t(deadline);
        string desiredText = getPropertyName(propertyIdDesired).c_str();
        if(desiredText.size()>22) desiredText=desiredText.substr(0,22)+"...";
        string spId = static_cast<ostringstream*>( &(ostringstream() << propertyIdDesired) )->str();
        desiredText += " (#" + spId + ")";
        string tokensPerUnitText;
        if (divisible) { tokensPerUnitText = FormatDivisibleMP(tokensPerUnit); } else { tokensPerUnitText = FormatIndivisibleMP(tokensPerUnit); }
        if (active) { ui->activeLabel->setText("Yes"); } else { ui->activeLabel->setText("No"); }
        // populate crowdinfo
        ui->desiredLabel->setText(QString::fromStdString(desiredText));
        ui->tokensPerUnitLabel->setText(QString::fromStdString(tokensPerUnitText));
        ui->deadlineLabel->setText(qDeadline.toString(Qt::SystemLocaleShortDate));
        ui->bonusLabel->setText(QString::fromStdString(FormatIndivisibleMP((int64_t)earlyBonus) + "%"));
        ui->issuerPercLabel->setText(QString::fromStdString(FormatIndivisibleMP((int64_t)percentToIssuer) + "%"));
        // show crowdinfo
        ui->desired->setVisible(true);
        ui->tokensperunit->setVisible(true);
        ui->deadline->setVisible(true);
        ui->bonus->setVisible(true);
        ui->issuerperc->setVisible(true);
        ui->desiredLabel->setVisible(true);
        ui->tokensPerUnitLabel->setVisible(true);
        ui->deadlineLabel->setVisible(true);
        ui->bonusLabel->setVisible(true);
        ui->issuerPercLabel->setVisible(true);
        ui->activeLabel->setVisible(true);
        ui->active->setText("Active:");
    }
    else
    {
        ui->issuanceTypeLabel->setText("Exodus");
        if (fixedIssuance) ui->issuanceTypeLabel->setText("Fixed");
        if (manualIssuance) ui->issuanceTypeLabel->setText("Manual");
        // hide crowdinfo
        ui->desired->setVisible(false);
        ui->tokensperunit->setVisible(false);
        ui->deadline->setVisible(false);
        ui->bonus->setVisible(false);
        ui->issuerperc->setVisible(false);
        ui->desiredLabel->setVisible(false);
        ui->tokensPerUnitLabel->setVisible(false);
        ui->deadlineLabel->setVisible(false);
        ui->bonusLabel->setVisible(false);
        ui->issuerPercLabel->setVisible(false);
        ui->activeLabel->setVisible(false);
        ui->active->setText("Not applicable.");
    }
    ui->topFrame->setVisible(true);
    ui->leftFrame->setVisible(true);
    ui->rightFrame->setVisible(true);
}

void LookupSPDialog::searchButtonClicked()
{
    searchSP();
}

void LookupSPDialog::matchingComboBoxChanged(int idx)
{
    updateDisplayedProperty();
}
<commit_msg>Fix ecosystem display on property lookup<commit_after>// Copyright (c) 2011-2014 The Bitcoin developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.

#include "lookupspdialog.h"
#include "ui_lookupspdialog.h"

#include "guiutil.h"
#include "optionsmodel.h"
#include "walletmodel.h"
#include "wallet.h"
#include "base58.h"
#include "ui_interface.h"

#include <boost/filesystem.hpp>

#include "leveldb/db.h"
#include "leveldb/write_batch.h"

// potentially overzealous includes here
#include "base58.h"
#include "rpcserver.h"
#include "init.h"
#include "util.h"
#include <fstream>
#include <algorithm>
#include <vector>
#include <utility>
#include <string>
#include <boost/assign/list_of.hpp>
#include <boost/algorithm/string.hpp>
#include <boost/algorithm/string/find.hpp>
#include <boost/algorithm/string/join.hpp>
#include <boost/lexical_cast.hpp>
#include <boost/format.hpp>
#include <boost/filesystem.hpp>
#include "json/json_spirit_utils.h"
#include "json/json_spirit_value.h"
#include "leveldb/db.h"
#include "leveldb/write_batch.h"
// end potentially overzealous includes

using namespace json_spirit;
#include "mastercore.h"
using namespace mastercore;

// potentially overzealous using here
using namespace std;
using namespace boost;
using namespace boost::assign;
using namespace leveldb;
// end potentially overzealous using

#include "mastercore_dex.h"
#include "mastercore_tx.h"
#include "mastercore_sp.h"

#include <QMessageBox>
#include <QScrollBar>
#include <QTextDocument>
#include <QDateTime>

LookupSPDialog::LookupSPDialog(QWidget *parent) :
    QDialog(parent),
    ui(new Ui::LookupSPDialog),
    model(0)
{
    ui->setupUi(this);
    this->model = model;

    // populate placeholder text
    ui->searchLineEdit->setPlaceholderText("ID, name or issuer");

    // connect actions
    connect(ui->matchingComboBox, SIGNAL(activated(int)), this, SLOT(matchingComboBoxChanged(int)));
    connect(ui->searchButton, SIGNAL(clicked()), this, SLOT(searchButtonClicked()));

    // hide crowd info
    ui->desired->setVisible(false);
    ui->tokensperunit->setVisible(false);
    ui->deadline->setVisible(false);
    ui->bonus->setVisible(false);
    ui->issuerperc->setVisible(false);
    ui->desiredLabel->setVisible(false);
    ui->tokensPerUnitLabel->setVisible(false);
    ui->deadlineLabel->setVisible(false);
    ui->bonusLabel->setVisible(false);
    ui->issuerPercLabel->setVisible(false);
    ui->activeLabel->setVisible(false);
    ui->active->setText("Not applicable.");
    ui->topFrame->setVisible(false);
    ui->leftFrame->setVisible(false);
    ui->rightFrame->setVisible(false);
}

void LookupSPDialog::searchSP()
{
    // search function to lookup properties, we want this search function to be as capable as possible to
    // help users find the property they're looking for via search terms they may want to use
    int searchParamType = 0;
    string searchText = ui->searchLineEdit->text().toStdString();
    unsigned int searchPropertyId = 0;

    // first let's check if we have a searchText, if not do nothing
    if (searchText.empty()) return;

    // try seeing if we have a numerical search string, if so treat it as a property ID search
    try
    {
        searchPropertyId = boost::lexical_cast<int64_t>(searchText);
        searchParamType = 1; // search by propertyId
    }
    catch(const boost::bad_lexical_cast &e) { }
    if (searchParamType == 1 && 0 >= searchPropertyId) searchParamType = 0; // we got a number but it's <=0

    // next if not positive numerical, lets see if the string is a valid bitcoin address for issuer search
    if (searchParamType == 0)
    {
        CBitcoinAddress address;
        address.SetString(searchText); // no null check on searchText required we've already checked it's not empty above
        if (address.IsValid()) searchParamType = 2; // search by address;
    }

    // if we still don't have a param we'll search against free text in the name
    if (searchParamType == 0) searchParamType = 3; // search by free text

    // clear matching results combo
    ui->matchingComboBox->clear();
    bool spExists;
    unsigned int tmpPropertyId;
    unsigned int nextSPID;
    unsigned int nextTestSPID;
    unsigned int propertyId;
    QString strId;
    switch(searchParamType)
    {
        case 1: //search by property Id
           // convert search string to ID
           strId = QString::fromStdString(searchText);
           propertyId = strId.toUInt();
           // check if this property ID exists, if not no match to populate and just return
           spExists = _my_sps->hasSP(propertyId);
           if (spExists)
           {
               addSPToMatchingResults(propertyId);
               updateDisplayedProperty(); //show straight away, only one to select
           }
           else
           {
               return;
           }
        break;
        case 2: //search by address
           // iterate through my_sps looking for the issuer address and add any properties issued by said address to matchingcombo
           // talk with @Michael @Bart to see if perhaps a more efficient way to do this, but not major issue as only run on user request
           nextSPID = _my_sps->peekNextSPID(1);
           nextTestSPID = _my_sps->peekNextSPID(2);
           for (tmpPropertyId = 1; tmpPropertyId<nextSPID; tmpPropertyId++)
           {
               CMPSPInfo::Entry sp;
               if (false != _my_sps->getSP(tmpPropertyId, sp))
               {
                   if (sp.issuer == searchText)
                   {
                       addSPToMatchingResults(tmpPropertyId);
                   }
               }
           }
           for (tmpPropertyId = TEST_ECO_PROPERTY_1; tmpPropertyId<nextTestSPID; tmpPropertyId++)
           {
               CMPSPInfo::Entry sp;
               if (false != _my_sps->getSP(tmpPropertyId, sp))
               {
                   if (sp.issuer == searchText)
                   {
                       addSPToMatchingResults(tmpPropertyId);
                   }
               }
           }
        break;
        case 3: //search by freetext
           // iterate through my_sps and see if property name contains the search text
           nextSPID = _my_sps->peekNextSPID(1);
           nextTestSPID = _my_sps->peekNextSPID(2);
           for (tmpPropertyId = 1; tmpPropertyId<nextSPID; tmpPropertyId++)
           {
               CMPSPInfo::Entry sp;
               if (false != _my_sps->getSP(tmpPropertyId, sp))
               {
                   // make the search case insensitive
                   string lowerName = sp.name;
                   std::transform(lowerName.begin(), lowerName.end(), lowerName.begin(), ::tolower);
                   string lowerSearch = searchText;
                   std::transform(lowerSearch.begin(), lowerSearch.end(), lowerSearch.begin(), ::tolower);
                   size_t loc = lowerName.find(lowerSearch);
                   if (loc!=std::string::npos)
                   {
                       addSPToMatchingResults(tmpPropertyId);
                   }
               }
           }
           for (tmpPropertyId = TEST_ECO_PROPERTY_1; tmpPropertyId<nextTestSPID; tmpPropertyId++)
           {
               CMPSPInfo::Entry sp;
               if (false != _my_sps->getSP(tmpPropertyId, sp))
               {
                   // make the search case insensitive
                   string lowerName = sp.name;
                   std::transform(lowerName.begin(), lowerName.end(), lowerName.begin(), ::tolower);
                   string lowerSearch = searchText;
                   std::transform(lowerSearch.begin(), lowerSearch.end(), lowerSearch.begin(), ::tolower);
                   size_t loc = lowerName.find(lowerSearch);
                   if (loc!=std::string::npos)
                   {
                       addSPToMatchingResults(tmpPropertyId);
                   }
               }
           }
        break;
    }

}

void LookupSPDialog::addSPToMatchingResults(unsigned int propertyId)
{
    // verify the supplied property exists (sanity check) then populate the matching results combo box
    bool spExists = _my_sps->hasSP(propertyId);
    if (spExists)
    {
        string spName;
        spName = getPropertyName(propertyId).c_str();
        if(spName.size()>50) spName=spName.substr(0,50)+"...";
        string spId = static_cast<ostringstream*>( &(ostringstream() << propertyId) )->str();
        spName += " (#" + spId + ")";
        ui->matchingComboBox->addItem(spName.c_str(),spId.c_str());
    }
    else
    {
        return;
    }
}

void LookupSPDialog::updateDisplayedProperty()
{
    QString strId = ui->matchingComboBox->itemData(ui->matchingComboBox->currentIndex()).toString();
    // protect against an empty matchedComboBox
    if (strId.toStdString().empty()) return;

    // map property Id
    unsigned int propertyId = strId.toUInt();
    CMPSPInfo::Entry sp;
    if (false == _my_sps->getSP(propertyId, sp)) { return; } // something has gone wrong, don't attempt to display non-existent property

    // populate the fields
    bool divisible=sp.isDivisible();
    if (divisible) { ui->divisibleLabel->setText("Yes"); } else { ui->divisibleLabel->setText("No"); }
    if (isTestEcosystemProperty(propertyId)) { ui->ecosystemLabel->setText("Test"); } else { ui->ecosystemLabel->setText("Production"); }
    ui->propertyIDLabel->setText(QString::fromStdString(FormatIndivisibleMP(propertyId)));
    ui->nameLabel->setText(QString::fromStdString(sp.name));
    ui->categoryLabel->setText(QString::fromStdString(sp.category + " > " + sp.subcategory));
    ui->dataLabel->setText(QString::fromStdString(sp.data));
    ui->urlLabel->setText(QString::fromStdString(sp.url));
    string strTotalTokens;
    string strWalletTokens;
    int64_t totalTokens = getTotalTokens(propertyId);
    int64_t walletTokens = 0;
    if (propertyId<2147483648)
    { walletTokens = global_balance_money_maineco[propertyId]; }
    else
    { walletTokens = global_balance_money_testeco[propertyId-2147483647]; }
    string tokenLabel;
    if (propertyId > 2)
    {
       tokenLabel = " SPT";
    }
    else
    {
       if (propertyId == 1) { tokenLabel = " MSC"; } else { tokenLabel = " TMSC"; }
    }
    if (divisible) { strTotalTokens = FormatDivisibleMP(totalTokens); } else { strTotalTokens = FormatIndivisibleMP(totalTokens); }
    if (divisible) { strWalletTokens = FormatDivisibleMP(walletTokens); } else { strWalletTokens = FormatIndivisibleMP(walletTokens); }
    ui->totalTokensLabel->setText(QString::fromStdString(strTotalTokens + tokenLabel));
    ui->walletBalanceLabel->setText(QString::fromStdString(strWalletTokens + tokenLabel));
    ui->issuerLabel->setText(QString::fromStdString(sp.issuer));
    bool fixedIssuance = sp.fixed;
    bool manualIssuance = sp.manual;
    if ((!fixedIssuance) && (!manualIssuance) && (propertyId > 2))
    {
        ui->issuanceTypeLabel->setText("Crowdsale");
        // obtain crowdinfo
        bool active = isCrowdsaleActive(propertyId);
        int64_t deadline = sp.deadline;
        uint8_t earlyBonus = sp.early_bird;
        uint8_t percentToIssuer = sp.percentage;
        int64_t tokensPerUnit = sp.num_tokens;
        int64_t propertyIdDesired = sp.property_desired;
        QDateTime qDeadline;
        qDeadline.setTime_t(deadline);
        string desiredText = getPropertyName(propertyIdDesired).c_str();
        if(desiredText.size()>22) desiredText=desiredText.substr(0,22)+"...";
        string spId = static_cast<ostringstream*>( &(ostringstream() << propertyIdDesired) )->str();
        desiredText += " (#" + spId + ")";
        string tokensPerUnitText;
        if (divisible) { tokensPerUnitText = FormatDivisibleMP(tokensPerUnit); } else { tokensPerUnitText = FormatIndivisibleMP(tokensPerUnit); }
        if (active) { ui->activeLabel->setText("Yes"); } else { ui->activeLabel->setText("No"); }
        // populate crowdinfo
        ui->desiredLabel->setText(QString::fromStdString(desiredText));
        ui->tokensPerUnitLabel->setText(QString::fromStdString(tokensPerUnitText));
        ui->deadlineLabel->setText(qDeadline.toString(Qt::SystemLocaleShortDate));
        ui->bonusLabel->setText(QString::fromStdString(FormatIndivisibleMP((int64_t)earlyBonus) + "%"));
        ui->issuerPercLabel->setText(QString::fromStdString(FormatIndivisibleMP((int64_t)percentToIssuer) + "%"));
        // show crowdinfo
        ui->desired->setVisible(true);
        ui->tokensperunit->setVisible(true);
        ui->deadline->setVisible(true);
        ui->bonus->setVisible(true);
        ui->issuerperc->setVisible(true);
        ui->desiredLabel->setVisible(true);
        ui->tokensPerUnitLabel->setVisible(true);
        ui->deadlineLabel->setVisible(true);
        ui->bonusLabel->setVisible(true);
        ui->issuerPercLabel->setVisible(true);
        ui->activeLabel->setVisible(true);
        ui->active->setText("Active:");
    }
    else
    {
        ui->issuanceTypeLabel->setText("Exodus");
        if (fixedIssuance) ui->issuanceTypeLabel->setText("Fixed");
        if (manualIssuance) ui->issuanceTypeLabel->setText("Manual");
        // hide crowdinfo
        ui->desired->setVisible(false);
        ui->tokensperunit->setVisible(false);
        ui->deadline->setVisible(false);
        ui->bonus->setVisible(false);
        ui->issuerperc->setVisible(false);
        ui->desiredLabel->setVisible(false);
        ui->tokensPerUnitLabel->setVisible(false);
        ui->deadlineLabel->setVisible(false);
        ui->bonusLabel->setVisible(false);
        ui->issuerPercLabel->setVisible(false);
        ui->activeLabel->setVisible(false);
        ui->active->setText("Not applicable.");
    }
    ui->topFrame->setVisible(true);
    ui->leftFrame->setVisible(true);
    ui->rightFrame->setVisible(true);
}

void LookupSPDialog::searchButtonClicked()
{
    searchSP();
}

void LookupSPDialog::matchingComboBoxChanged(int idx)
{
    updateDisplayedProperty();
}
<|endoftext|>


<commit_before>#include <QTest>
#include <QObject>

#include "uritests.h"

// This is all you need to run all the tests
int main(int argc, char *argv[])
{
    URITests test1;
    QTest::qExec(&test1);
}
<commit_msg>Return !0 when qt tests fail.<commit_after>#include <QTest>
#include <QObject>

#include "uritests.h"

// This is all you need to run all the tests
int main(int argc, char *argv[])
{
    bool fInvalid = false;

    URITests test1;
    if (QTest::qExec(&test1) != 0)
        fInvalid = true;

    return fInvalid;
}
<|endoftext|>


<commit_before>#include "cinder/app/App.h"
#include "cinder/app/RendererGl.h"
#include "cinder/ConvexHull.h"
#include "cinder/Rand.h"
#include "cinder/params/Params.h"
#include "cinder/Font.h"

using namespace ci;
using namespace ci::app;
using namespace std;

class ConvexHullApp : public App {
  public:
	void setup();
	void makeNewLetter();
	void mouseDown( MouseEvent event );
	void mouseDrag( MouseEvent event );
	void update();
	void draw();

	bool				mUsingShape;
	vector<vec2>		mPoints;
	Shape2d				mShape;

	PolyLine2f			mConvexHull;

	params::InterfaceGlRef	mParams;
};

void ConvexHullApp::setup()
{
	mUsingShape = true;
	mParams = params::InterfaceGl::create( "App parameters", ivec2( 180, 100 ) );
	mParams->addParam( "Use Glyph", &mUsingShape );
	mParams->addButton( "Clear Points", [&] { mPoints.clear(); } );

	if( mUsingShape )
		makeNewLetter();
}

void ConvexHullApp::makeNewLetter()
{
	Font arial( "Times", 512 );
	mShape = arial.getGlyphShape( arial.getGlyphChar( '!' + randInt( 92 ) ) );
//	mat2 transform = MatrixAffine2f::makeTranslate( vec2( 100, getWindowHeight() - 100 ) );
	mShape.transform( translate( mat3(), vec2( 100, getWindowHeight() - 100 ) ) );
}

void ConvexHullApp::update()
{
	// this should be cached but doesn't matter for this demo
	if( mUsingShape )
		mConvexHull = calcConvexHull( mShape );
	else
		mConvexHull = calcConvexHull( mPoints );
}

void ConvexHullApp::mouseDown( MouseEvent event )
{
	if( mUsingShape )
		makeNewLetter();
	else
		mPoints.push_back( event.getPos() );
}

void ConvexHullApp::mouseDrag( MouseEvent event )
{
	if( mUsingShape )
		makeNewLetter();
	else
		mPoints.back() = event.getPos();
}

void ConvexHullApp::draw()
{
	// clear out the window with black
	gl::clear( Color( 0, 0, 0 ) );
	gl::enableAlphaBlending();

	// draw solid convex hull
	gl::color( ColorA( 0.8f, 0, 1.0f, 0.2f ) );
	gl::drawSolid( mConvexHull );
	gl::color( ColorA( 0.8f, 0, 1.0f, 0.8f ) );
	gl::draw( mConvexHull );

	// draw convex hull points
	gl::color( Color( 0.0f, 0, 1.0f ) );
	for( auto ptIt = mConvexHull.begin(); ptIt != mConvexHull.end(); ++ptIt ) {
		gl::drawSolidCircle( *ptIt, 4 );
	}

	gl::color( ColorA( 1.0f, 0.8f, 0, 0.6f ) );
	if( mUsingShape ) {
		gl::draw( mShape );
	}
	else {
		for( auto ptIt = mPoints.begin(); ptIt != mPoints.end(); ++ptIt ) {
			gl::drawSolidCircle( *ptIt, 3 );
		}
	}

	mParams->draw();
}

CINDER_APP( ConvexHullApp, RendererGl )<commit_msg>Fixing missing #include in ConvexHull sample<commit_after>#include "cinder/app/App.h"
#include "cinder/app/RendererGl.h"
#include "cinder/gl/gl.h"
#include "cinder/ConvexHull.h"
#include "cinder/Rand.h"
#include "cinder/params/Params.h"
#include "cinder/Font.h"

using namespace ci;
using namespace ci::app;
using namespace std;

class ConvexHullApp : public App {
  public:
	void setup();
	void makeNewLetter();
	void mouseDown( MouseEvent event );
	void mouseDrag( MouseEvent event );
	void update();
	void draw();

	bool				mUsingShape;
	vector<vec2>		mPoints;
	Shape2d				mShape;

	PolyLine2f			mConvexHull;

	params::InterfaceGlRef	mParams;
};

void ConvexHullApp::setup()
{
	mUsingShape = true;
	mParams = params::InterfaceGl::create( "App parameters", ivec2( 180, 100 ) );
	mParams->addParam( "Use Glyph", &mUsingShape );
	mParams->addButton( "Clear Points", [&] { mPoints.clear(); } );

	if( mUsingShape )
		makeNewLetter();
}

void ConvexHullApp::makeNewLetter()
{
	Font arial( "Times", 512 );
	mShape = arial.getGlyphShape( arial.getGlyphChar( '!' + randInt( 92 ) ) );
//	mat2 transform = MatrixAffine2f::makeTranslate( vec2( 100, getWindowHeight() - 100 ) );
	mShape.transform( translate( mat3(), vec2( 100, getWindowHeight() - 100 ) ) );
}

void ConvexHullApp::update()
{
	// this should be cached but doesn't matter for this demo
	if( mUsingShape )
		mConvexHull = calcConvexHull( mShape );
	else
		mConvexHull = calcConvexHull( mPoints );
}

void ConvexHullApp::mouseDown( MouseEvent event )
{
	if( mUsingShape )
		makeNewLetter();
	else
		mPoints.push_back( event.getPos() );
}

void ConvexHullApp::mouseDrag( MouseEvent event )
{
	if( mUsingShape )
		makeNewLetter();
	else
		mPoints.back() = event.getPos();
}

void ConvexHullApp::draw()
{
	// clear out the window with black
	gl::clear( Color( 0, 0, 0 ) );
	gl::enableAlphaBlending();

	// draw solid convex hull
	gl::color( ColorA( 0.8f, 0, 1.0f, 0.2f ) );
	gl::drawSolid( mConvexHull );
	gl::color( ColorA( 0.8f, 0, 1.0f, 0.8f ) );
	gl::draw( mConvexHull );

	// draw convex hull points
	gl::color( Color( 0.0f, 0, 1.0f ) );
	for( auto ptIt = mConvexHull.begin(); ptIt != mConvexHull.end(); ++ptIt ) {
		gl::drawSolidCircle( *ptIt, 4 );
	}

	gl::color( ColorA( 1.0f, 0.8f, 0, 0.6f ) );
	if( mUsingShape ) {
		gl::draw( mShape );
	}
	else {
		for( auto ptIt = mPoints.begin(); ptIt != mPoints.end(); ++ptIt ) {
			gl::drawSolidCircle( *ptIt, 3 );
		}
	}

	mParams->draw();
}

CINDER_APP( ConvexHullApp, RendererGl )<|endoftext|>


<commit_before>#include "planner_modules_pr2/putdown_modules.h"
#include "planner_modules_pr2/module_param_cache.h"
//#include "tidyup_utils/arm_state.h"
//#include "tidyup_utils/planning_scene_interface.h"
#include "planner_modules_pr2/tidyup_planning_scene_updater.h"
#include "tidyup_utils/planning_scene_interface.h"
//#include "tidyup_utils/transformer.h"
#include <ros/ros.h>
#include <geometry_msgs/PoseStamped.h>
#include <map>
#include <set>
using std::set;
using std::map;
#include <utility>
using std::pair; using std::make_pair;
//#include <boost/foreach.hpp>
//#ifdef __CDT_PARSER__
//#define forEach(a, b) for(a : b)
//#else
//#define forEach BOOST_FOREACH
//#endif
#include <sys/times.h>
//#include <tf/tf.h>
//#include <tf/transform_listener.h>
#include <arm_navigation_msgs/ArmNavigationErrorCodes.h>
#include <arm_navigation_msgs/convert_messages.h>
//#include <boost/tuple/tuple.hpp>
//#include <boost/tuple/tuple_comparison.hpp>
#include <tidyup_msgs/GetPutdownPose.h>
#include <sstream>
#include "tidyup_utils/stringutil.h"

VERIFY_CONDITIONCHECKER_DEF(canPutdown);
VERIFY_APPLYEFFECT_DEF(updatePutdownPose);

string g_WorldFrame;
ros::NodeHandle* g_NodeHandle = NULL;
ros::ServiceClient g_GetPutdownPose;

ModuleParamCacheString paramCache;
string separator = " ";

string logName;
geometry_msgs::Pose defaultAttachPose;

void putdown_init(int argc, char** argv)
{
    ROS_ASSERT(argc == 2);
    logName = "[putdownModule]";

    g_NodeHandle = new ros::NodeHandle();
    string service_name = "/tidyup/request_putdown_pose";

    while (!ros::service::waitForService(service_name, ros::Duration(3.0)))
    {
        ROS_ERROR("%s Service %s not available - waiting.", logName.c_str(), service_name.c_str());
    }

    g_GetPutdownPose = g_NodeHandle->serviceClient<tidyup_msgs::GetPutdownPose>(service_name, true);
    if (!g_GetPutdownPose)
    {
        ROS_FATAL("%s Could not initialize get putdown service from %s (client name: %s)", logName.c_str(), service_name.c_str(), g_GetPutdownPose.getService().c_str());
    }

    // initialize cache
    paramCache.initialize("putdown", g_NodeHandle);

    defaultAttachPose.position.x = 0.032;
    defaultAttachPose.position.y = 0.015;
    defaultAttachPose.position.z = 0.0;
    defaultAttachPose.orientation.x = 0.707;
    defaultAttachPose.orientation.y = -0.106;
    defaultAttachPose.orientation.z = -0.690;
    defaultAttachPose.orientation.w = 0.105;

    ROS_INFO("%s Initialized Putdown Module.\n", logName.c_str());
}

bool callFindPutdownPoseService(tidyup_msgs::GetPutdownPose & srv)
{
    if (!g_GetPutdownPose)
    {
        ROS_ERROR("%s Persistent service connection to %s failed.", logName.c_str(), g_GetPutdownPose.getService().c_str());
        // FIXME reconnect - this shouldn't happen.
        return false;
    }

    // statistics about using the ros service
    static double plannerCalls = 0;
    static ros::Duration totalCallsTime = ros::Duration(0.0);
    plannerCalls += 1.0;
    ros::Time callStartTime = ros::Time::now();

    // perform the actual path planner call
    if (! g_GetPutdownPose.call(srv))
    {
        ROS_ERROR("%s Failed to call service %s.", logName.c_str(), g_GetPutdownPose.getService().c_str());
        return false;
    }
    if (g_Debug)
    {
        ros::Time callEndTime = ros::Time::now();
        ros::Duration dt = callEndTime - callStartTime;
        totalCallsTime += dt;
        ROS_DEBUG("%s ServiceCall took: %f, avg: %f (num %f).", logName.c_str(),
                dt.toSec(), totalCallsTime.toSec()/plannerCalls, plannerCalls);
    }
//
//    if (srv.response.error_code.val == arm_navigation_msgs::ArmNavigationErrorCodes::SUCCESS)
//    {
//        ROS_INFO("%s Got a putdown pose.", logName.c_str());
//        return true;
//    }
//
//    ROS_WARN("%s GetPutdownPose failed. Reason: %s (%d)", logName.c_str(),
//            arm_navigation_msgs::armNavigationErrorCodeToString(srv.response.error_code).c_str(),
//            srv.response.error_code.val);
    return true;
}

string writePoseToString(const geometry_msgs::Pose& pose)
{
    std::stringstream stream;
    stream.precision(3);
    stream << std::fixed;
    stream << pose.position.x << separator;
    stream << pose.position.y << separator;
    stream << pose.position.z << separator;
    stream << pose.orientation.x << separator;
    stream << pose.orientation.y << separator;
    stream << pose.orientation.z << separator;
    stream << pose.orientation.w << separator;
    return stream.str();
}

bool readPoseFromString(const string cacheValue, geometry_msgs::Pose& pose)
{
    std::stringstream stream;
    stream << cacheValue;
    vector<double> coordinates;
    coordinates.resize(7);
    for(size_t i = 0; ! stream.eof() && i < coordinates.size(); i++)
    {
        stream >> coordinates[i];
    }
    if (!stream.good())
        return false;
    pose.position.x = coordinates[0];
    pose.position.y = coordinates[1];
    pose.position.z = coordinates[2];
    pose.orientation.x = coordinates[3];
    pose.orientation.y = coordinates[4];
    pose.orientation.z = coordinates[5];
    pose.orientation.w = coordinates[6];
    return true;
}

string createCacheKey(const string& putdownObject,
        const string& arm,
        const string& staticObject,
        const map<string, geometry_msgs::Pose>& movableObjects,
        const map<string, string>& objectsOnStatic)
{
    ROS_DEBUG("%s createCacheKey %s %s %s", logName.c_str(), putdownObject.c_str(), arm.c_str(), staticObject.c_str());
    std::stringstream stream;
    stream.precision(3);
    stream << std::fixed << putdownObject << arm << staticObject;
    for (map<string, string>::const_iterator objectIt = objectsOnStatic.begin(); objectIt != objectsOnStatic.end(); objectIt++)
    {
        ROS_DEBUG("%s object %s on %s", logName.c_str(), objectIt->first.c_str(), objectIt->second.c_str());
        if (objectIt->second == staticObject)
        {
            const geometry_msgs::Pose& pose = movableObjects.find(objectIt->first)->second;
            stream << pose.position.x;
            stream << pose.position.y;
            stream << pose.position.z;
            stream << pose.orientation.x;
            stream << pose.orientation.y;
            stream << pose.orientation.z;
            stream << pose.orientation.w;
        }
    }
    return stream.str();
}

bool findPutdownPose(const ParameterList & parameterList,
        predicateCallbackType predicateCallback,
        numericalFluentCallbackType numericalFluentCallback,
        geometry_msgs::Pose& putdown_pose)
{
    // (canPutdown ?o - movable_object ?a - arm ?s - static_object ?g - manipulation_location)
    ROS_ASSERT(parameterList.size() == 4);
    Parameter putdown_object = parameterList[0];
    Parameter arm = parameterList[1];
    Parameter static_object = parameterList[2];
    Parameter robot_location = parameterList[3];

    // read state
    geometry_msgs::Pose robotPose;
    map<string, geometry_msgs::Pose> movableObjects;
    map<string, string> graspedObjects;
    map<string, string> objectsOnStatic;
    set<string> openDoors;
    arm_navigation_msgs::PlanningScene world = PlanningSceneInterface::instance()->getCurrentScene();
    if (! TidyupPlanningSceneUpdater::readState(robot_location.value, predicateCallback, numericalFluentCallback, robotPose, movableObjects, graspedObjects, objectsOnStatic, openDoors))
    {
        ROS_ERROR("%s read state failed.", logName.c_str());
        return false;
    }

    tidyup_msgs::GetPutdownPose srv;
    srv.request.static_object = static_object.value;
    srv.request.putdown_object = putdown_object.value;
    srv.request.arm = arm.value;
    ROS_INFO("%s putdown request: %s, %s, %s, %s", logName.c_str(), parameterList[0].value.c_str(), parameterList[1].value.c_str(), parameterList[2].value.c_str(), parameterList[3].value.c_str());

    string cacheKey = createCacheKey(srv.request.putdown_object, srv.request.arm, srv.request.static_object, movableObjects, objectsOnStatic);
    ROS_DEBUG("%s cacheKey: %s", logName.c_str(), cacheKey.c_str());
    // retrieved cached result
    string cacheValue;
    if (paramCache.get(cacheKey, cacheValue))
    {
        // cache hit. either 'impossible' or a valid pose
        if (cacheValue == "impossible")
        {
            ROS_DEBUG("%s cache hit: impossible", logName.c_str());
            return false;
        }
        else
        {
            if (! readPoseFromString(cacheValue, putdown_pose))
            {
                ROS_ERROR("%s could not read cached value. cache may be corrupt.", logName.c_str());
                return false;
            }
            ROS_DEBUG("%s cache hit: pose from cache", logName.c_str());
            return true;
        }
    }

    // no cache entry, set planning scene
    PlanningSceneInterface::instance()->resetPlanningScene();
    ROS_DEBUG("%s set planning scene", logName.c_str());
    if (! TidyupPlanningSceneUpdater::update(robotPose, movableObjects, graspedObjects, openDoors))
    {
        ROS_ERROR("%s update planning scene failed.", logName.c_str());
        return false;
    }

    // call putdown service
    ROS_INFO("%s call putdown service", logName.c_str());
    if (! callFindPutdownPoseService(srv))
    {
        ROS_ERROR("%s service call failed", logName.c_str());
        return false;
    }
    if (srv.response.error_code.val == srv.response.error_code.PLANNING_FAILED)
    {
        ROS_INFO("%s service returned: impossible", logName.c_str());
        paramCache.set(cacheKey, "impossible", true);
        return false;
    }
    if  (srv.response.error_code.val == srv.response.error_code.SUCCESS)
    {
        // insert results into cache
        ROS_INFO("%s service returned: pose found, adding to cache", logName.c_str());
        putdown_pose = srv.response.putdown_pose.pose;
        paramCache.set(cacheKey, writePoseToString(putdown_pose), true);
        return true;
    }

    ROS_ERROR("%s GetPutdownPose failed. Reason: %s (%d)", logName.c_str(),
            arm_navigation_msgs::armNavigationErrorCodeToString(srv.response.error_code).c_str(),
            srv.response.error_code.val);
    return false;
}

double canPutdown(const ParameterList & parameterList,
        predicateCallbackType predicateCallback,
        numericalFluentCallbackType numericalFluentCallback,
        int relaxed)
{
    if (g_Debug)
    { // prevent spamming ROS_DEBUG calls unless we really want debug
        // debugging raw planner calls
        static unsigned int calls = 0;
        calls++;
        if (calls % 10000 == 0)
        {
            ROS_DEBUG("%s Got %d putdown module calls.\n", logName.c_str(), calls);
        }
    }

    geometry_msgs::Pose putdownPose;
    if (! findPutdownPose(parameterList, predicateCallback, numericalFluentCallback, putdownPose))
    {
        return INFINITE_COST;
    }
    return 0;
}

int updatePutdownPose(const ParameterList & parameterList, predicateCallbackType predicateCallback,
        numericalFluentCallbackType numericalFluentCallback, std::vector<double> & writtenVars)
{
    geometry_msgs::Pose putdownPose;
    if (! findPutdownPose(parameterList, predicateCallback, numericalFluentCallback, putdownPose))
    {
        return 1;
    }
    // write the pose to state:
    writtenVars[0] = putdownPose.position.x;
    writtenVars[1] = putdownPose.position.y;
    writtenVars[2] = putdownPose.position.z;
    writtenVars[3] = putdownPose.orientation.x;
    writtenVars[4] = putdownPose.orientation.y;
    writtenVars[5] = putdownPose.orientation.z;
    writtenVars[6] = putdownPose.orientation.w;
    return 0;
}

<commit_msg>compute correct cache keys for param server<commit_after>#include "planner_modules_pr2/putdown_modules.h"
#include "planner_modules_pr2/module_param_cache.h"
//#include "tidyup_utils/arm_state.h"
//#include "tidyup_utils/planning_scene_interface.h"
#include "planner_modules_pr2/tidyup_planning_scene_updater.h"
#include "tidyup_utils/planning_scene_interface.h"
//#include "tidyup_utils/transformer.h"
#include <ros/ros.h>
#include <geometry_msgs/PoseStamped.h>
#include <map>
#include <set>
using std::set;
using std::map;
#include <utility>
using std::pair; using std::make_pair;
//#include <boost/foreach.hpp>
//#ifdef __CDT_PARSER__
//#define forEach(a, b) for(a : b)
//#else
//#define forEach BOOST_FOREACH
//#endif
#include <sys/times.h>
//#include <tf/tf.h>
//#include <tf/transform_listener.h>
#include <arm_navigation_msgs/ArmNavigationErrorCodes.h>
#include <arm_navigation_msgs/convert_messages.h>
//#include <boost/tuple/tuple.hpp>
//#include <boost/tuple/tuple_comparison.hpp>
#include <tidyup_msgs/GetPutdownPose.h>
#include <sstream>
#include "tidyup_utils/stringutil.h"

VERIFY_CONDITIONCHECKER_DEF(canPutdown);
VERIFY_APPLYEFFECT_DEF(updatePutdownPose);

string g_WorldFrame;
ros::NodeHandle* g_NodeHandle = NULL;
ros::ServiceClient g_GetPutdownPose;

ModuleParamCacheString paramCache;
string separator = " ";

string logName;
geometry_msgs::Pose defaultAttachPose;

void putdown_init(int argc, char** argv)
{
    ROS_ASSERT(argc == 2);
    logName = "[putdownModule]";

    g_NodeHandle = new ros::NodeHandle();
    string service_name = "/tidyup/request_putdown_pose";

    while (!ros::service::waitForService(service_name, ros::Duration(3.0)))
    {
        ROS_ERROR("%s Service %s not available - waiting.", logName.c_str(), service_name.c_str());
    }

    g_GetPutdownPose = g_NodeHandle->serviceClient<tidyup_msgs::GetPutdownPose>(service_name, true);
    if (!g_GetPutdownPose)
    {
        ROS_FATAL("%s Could not initialize get putdown service from %s (client name: %s)", logName.c_str(), service_name.c_str(), g_GetPutdownPose.getService().c_str());
    }

    // initialize cache
    paramCache.initialize("putdown", g_NodeHandle);

    defaultAttachPose.position.x = 0.032;
    defaultAttachPose.position.y = 0.015;
    defaultAttachPose.position.z = 0.0;
    defaultAttachPose.orientation.x = 0.707;
    defaultAttachPose.orientation.y = -0.106;
    defaultAttachPose.orientation.z = -0.690;
    defaultAttachPose.orientation.w = 0.105;

    ROS_INFO("%s Initialized Putdown Module.\n", logName.c_str());
}

bool callFindPutdownPoseService(tidyup_msgs::GetPutdownPose & srv)
{
    if (!g_GetPutdownPose)
    {
        ROS_ERROR("%s Persistent service connection to %s failed.", logName.c_str(), g_GetPutdownPose.getService().c_str());
        // FIXME reconnect - this shouldn't happen.
        return false;
    }

    // statistics about using the ros service
    static double plannerCalls = 0;
    static ros::Duration totalCallsTime = ros::Duration(0.0);
    plannerCalls += 1.0;
    ros::Time callStartTime = ros::Time::now();

    // perform the actual path planner call
    if (! g_GetPutdownPose.call(srv))
    {
        ROS_ERROR("%s Failed to call service %s.", logName.c_str(), g_GetPutdownPose.getService().c_str());
        return false;
    }
    if (g_Debug)
    {
        ros::Time callEndTime = ros::Time::now();
        ros::Duration dt = callEndTime - callStartTime;
        totalCallsTime += dt;
        ROS_DEBUG("%s ServiceCall took: %f, avg: %f (num %f).", logName.c_str(),
                dt.toSec(), totalCallsTime.toSec()/plannerCalls, plannerCalls);
    }
//
//    if (srv.response.error_code.val == arm_navigation_msgs::ArmNavigationErrorCodes::SUCCESS)
//    {
//        ROS_INFO("%s Got a putdown pose.", logName.c_str());
//        return true;
//    }
//
//    ROS_WARN("%s GetPutdownPose failed. Reason: %s (%d)", logName.c_str(),
//            arm_navigation_msgs::armNavigationErrorCodeToString(srv.response.error_code).c_str(),
//            srv.response.error_code.val);
    return true;
}

string writePoseToString(const geometry_msgs::Pose& pose)
{
    std::stringstream stream;
    stream.precision(0);
    stream << std::fixed;
    stream << pose.position.x << separator;
    stream << pose.position.y << separator;
    stream << pose.position.z << separator;
    stream << pose.orientation.x << separator;
    stream << pose.orientation.y << separator;
    stream << pose.orientation.z << separator;
    stream << pose.orientation.w << separator;
    return stream.str();
}

bool readPoseFromString(const string cacheValue, geometry_msgs::Pose& pose)
{
    std::stringstream stream;
    stream << cacheValue;
    vector<double> coordinates;
    coordinates.resize(7);
    for(size_t i = 0; ! stream.eof() && i < coordinates.size(); i++)
    {
        stream >> coordinates[i];
    }
    if (!stream.good())
        return false;
    pose.position.x = coordinates[0];
    pose.position.y = coordinates[1];
    pose.position.z = coordinates[2];
    pose.orientation.x = coordinates[3];
    pose.orientation.y = coordinates[4];
    pose.orientation.z = coordinates[5];
    pose.orientation.w = coordinates[6];
    return true;
}

string createCacheKey(const string& putdownObject,
        const string& arm,
        const string& staticObject,
        const map<string, geometry_msgs::Pose>& movableObjects,
        const map<string, string>& objectsOnStatic)
{
    ROS_DEBUG("%s createCacheKey %s %s %s", logName.c_str(), putdownObject.c_str(), arm.c_str(), staticObject.c_str());
    std::stringstream stream;
    stream.precision(0);
    stream << std::fixed << putdownObject << arm << staticObject;
    for (map<string, string>::const_iterator objectIt = objectsOnStatic.begin(); objectIt != objectsOnStatic.end(); objectIt++)
    {
        ROS_DEBUG("%s object %s on %s", logName.c_str(), objectIt->first.c_str(), objectIt->second.c_str());
        if (objectIt->second == staticObject)
        {
            const geometry_msgs::Pose& pose = movableObjects.find(objectIt->first)->second;
            // the actual values don't matter as long as they are unique for this object
            // cannot use doubles here, as param keys are not allowed to contain '.'
            if(pose.position.x < 0)
                stream << "N";
            stream << abs(static_cast<int>(10000.0 * pose.position.x));
            if(pose.position.y < 0)
                stream << "N";
            stream << abs(static_cast<int>(10000.0 * pose.position.y));
            if(pose.position.z < 0)
                stream << "N";
            stream << abs(static_cast<int>(10000.0 * pose.position.z));
            if(pose.orientation.x < 0)
                stream << "N";
            stream << abs(static_cast<int>(10000.0 * pose.orientation.x));
            if(pose.orientation.y < 0)
                stream << "N";
            stream << abs(static_cast<int>(10000.0 * pose.orientation.y));
            if(pose.orientation.z < 0)
                stream << "N";
            stream << abs(static_cast<int>(10000.0 * pose.orientation.z));
            if(pose.orientation.w < 0)
                stream << "N";
            stream << abs(static_cast<int>(10000.0 * pose.orientation.w));
        }
    }
    return stream.str();
}

bool findPutdownPose(const ParameterList & parameterList,
        predicateCallbackType predicateCallback,
        numericalFluentCallbackType numericalFluentCallback,
        geometry_msgs::Pose& putdown_pose)
{
    // (canPutdown ?o - movable_object ?a - arm ?s - static_object ?g - manipulation_location)
    ROS_ASSERT(parameterList.size() == 4);
    Parameter putdown_object = parameterList[0];
    Parameter arm = parameterList[1];
    Parameter static_object = parameterList[2];
    Parameter robot_location = parameterList[3];

    // read state
    geometry_msgs::Pose robotPose;
    map<string, geometry_msgs::Pose> movableObjects;
    map<string, string> graspedObjects;
    map<string, string> objectsOnStatic;
    set<string> openDoors;
    arm_navigation_msgs::PlanningScene world = PlanningSceneInterface::instance()->getCurrentScene();
    if (! TidyupPlanningSceneUpdater::readState(robot_location.value, predicateCallback, numericalFluentCallback, robotPose, movableObjects, graspedObjects, objectsOnStatic, openDoors))
    {
        ROS_ERROR("%s read state failed.", logName.c_str());
        return false;
    }

    tidyup_msgs::GetPutdownPose srv;
    srv.request.static_object = static_object.value;
    srv.request.putdown_object = putdown_object.value;
    srv.request.arm = arm.value;
    ROS_INFO("%s putdown request: %s, %s, %s, %s", logName.c_str(), parameterList[0].value.c_str(), parameterList[1].value.c_str(), parameterList[2].value.c_str(), parameterList[3].value.c_str());

    string cacheKey = createCacheKey(srv.request.putdown_object, srv.request.arm, srv.request.static_object, movableObjects, objectsOnStatic);
    ROS_DEBUG("%s cacheKey: %s", logName.c_str(), cacheKey.c_str());
    // retrieved cached result
    string cacheValue;
    if (paramCache.get(cacheKey, cacheValue))
    {
        // cache hit. either 'impossible' or a valid pose
        if (cacheValue == "impossible")
        {
            ROS_DEBUG("%s cache hit: impossible", logName.c_str());
            return false;
        }
        else
        {
            if (! readPoseFromString(cacheValue, putdown_pose))
            {
                ROS_ERROR("%s could not read cached value. cache may be corrupt.", logName.c_str());
                return false;
            }
            ROS_DEBUG("%s cache hit: pose from cache", logName.c_str());
            return true;
        }
    }

    // no cache entry, set planning scene
    PlanningSceneInterface::instance()->resetPlanningScene();
    ROS_DEBUG("%s set planning scene", logName.c_str());
    if (! TidyupPlanningSceneUpdater::update(robotPose, movableObjects, graspedObjects, openDoors))
    {
        ROS_ERROR("%s update planning scene failed.", logName.c_str());
        return false;
    }

    // call putdown service
    ROS_INFO("%s call putdown service", logName.c_str());
    if (! callFindPutdownPoseService(srv))
    {
        ROS_ERROR("%s service call failed", logName.c_str());
        return false;
    }
    if (srv.response.error_code.val == srv.response.error_code.PLANNING_FAILED)
    {
        ROS_INFO("%s service returned: impossible", logName.c_str());
        paramCache.set(cacheKey, "impossible", true);
        return false;
    }
    if  (srv.response.error_code.val == srv.response.error_code.SUCCESS)
    {
        // insert results into cache
        ROS_INFO("%s service returned: pose found, adding to cache", logName.c_str());
        putdown_pose = srv.response.putdown_pose.pose;
        paramCache.set(cacheKey, writePoseToString(putdown_pose), true);
        return true;
    }

    ROS_ERROR("%s GetPutdownPose failed. Reason: %s (%d)", logName.c_str(),
            arm_navigation_msgs::armNavigationErrorCodeToString(srv.response.error_code).c_str(),
            srv.response.error_code.val);
    return false;
}

double canPutdown(const ParameterList & parameterList,
        predicateCallbackType predicateCallback,
        numericalFluentCallbackType numericalFluentCallback,
        int relaxed)
{
    if (g_Debug)
    { // prevent spamming ROS_DEBUG calls unless we really want debug
        // debugging raw planner calls
        static unsigned int calls = 0;
        calls++;
        if (calls % 10000 == 0)
        {
            ROS_DEBUG("%s Got %d putdown module calls.\n", logName.c_str(), calls);
        }
    }

    geometry_msgs::Pose putdownPose;
    if (! findPutdownPose(parameterList, predicateCallback, numericalFluentCallback, putdownPose))
    {
        return INFINITE_COST;
    }
    return 0;
}

int updatePutdownPose(const ParameterList & parameterList, predicateCallbackType predicateCallback,
        numericalFluentCallbackType numericalFluentCallback, std::vector<double> & writtenVars)
{
    geometry_msgs::Pose putdownPose;
    if (! findPutdownPose(parameterList, predicateCallback, numericalFluentCallback, putdownPose))
    {
        return 1;
    }
    // write the pose to state:
    writtenVars[0] = putdownPose.position.x;
    writtenVars[1] = putdownPose.position.y;
    writtenVars[2] = putdownPose.position.z;
    writtenVars[3] = putdownPose.orientation.x;
    writtenVars[4] = putdownPose.orientation.y;
    writtenVars[5] = putdownPose.orientation.z;
    writtenVars[6] = putdownPose.orientation.w;
    return 0;
}

<|endoftext|>


<commit_before><commit_msg>saving backface culling<commit_after><|endoftext|>


<commit_before>#include "branchmodel.h"
#include "gitclient.h"

#include <QtCore/QDebug>

enum { debug = 0 };

namespace Git {
    namespace Internal {

// Parse a branch line: " *name sha description".  Return  true if it is
// the current one
bool BranchModel::Branch::parse(const QString &lineIn, bool *isCurrent)
{
    if (debug)
        qDebug() << Q_FUNC_INFO << lineIn;

    *isCurrent = lineIn.startsWith(QLatin1String("* "));
    if (lineIn.size() < 3)
        return false;

    const QStringList tokens =lineIn.mid(2).split(QLatin1Char(' '), QString::SkipEmptyParts);
    if (tokens.size() < 2)
        return false;
    name = tokens.at(0);
    currentSHA= tokens.at(1);
    toolTip.clear();
    return true;
}

static inline Qt::ItemFlags typeToModelFlags(BranchModel::Type t)
{
    Qt::ItemFlags rc = Qt::ItemIsSelectable|Qt::ItemIsEnabled;
    if (t == BranchModel::BranchModel::LocalBranches)
        rc |= Qt::ItemIsUserCheckable;
    return rc;
}

// --- BranchModel
BranchModel::BranchModel(GitClient *client, Type type, QObject *parent) :
    QAbstractListModel(parent),
    m_type(type),
    m_flags(typeToModelFlags(type)),
    m_client(client),
    m_currentBranch(-1)
{
}

int BranchModel::currentBranch() const
{
    return m_currentBranch;
}

QString BranchModel::branchName(int row) const
{
    return m_branches.at(row).name;
}

int BranchModel::rowCount(const QModelIndex & /* parent */) const
{
    return m_branches.size();
}

QVariant BranchModel::data(const QModelIndex &index, int role) const
{
    const int row = index.row();
    switch (role) {
        case Qt::DisplayRole:
        return branchName(row);
        case Qt::ToolTipRole:
        if (m_branches.at(row).toolTip.isEmpty())
            m_branches.at(row).toolTip = toolTip(m_branches.at(row).currentSHA);
        return m_branches.at(row).toolTip;
        break;
        case Qt::CheckStateRole:
        if (m_type == RemoteBranches)
            return QVariant();
        return row == m_currentBranch ? Qt::Checked : Qt::Unchecked;
        default:
        break;
    }
    return QVariant();
}

Qt::ItemFlags BranchModel::flags(const QModelIndex & /*index */) const
{
    return m_flags;
}

bool BranchModel::refresh(const QString &workingDirectory, QString *errorMessage)
{
    // Run branch command with verbose.
    QStringList branchArgs(QLatin1String("-v"));
    QString output;
    if (m_type == RemoteBranches)
        branchArgs.push_back(QLatin1String("-r"));
    if (!m_client->synchronousBranchCmd(workingDirectory, branchArgs, &output, errorMessage))
        return false;
    if (debug)
        qDebug() << Q_FUNC_INFO << workingDirectory << output;
    // Parse output
    m_workingDirectory = workingDirectory;
    m_branches.clear();
    m_currentBranch = -1;
    const QStringList branches = output.split(QLatin1Char('\n'));
    const int branchCount = branches.size();
    bool isCurrent;
    for (int b = 0; b < branchCount; b++) {
        Branch newBranch;
        if (newBranch.parse(branches.at(b), &isCurrent)) {
            m_branches.push_back(newBranch);
            if (isCurrent)
                m_currentBranch = b;
        }
    }
    reset();
    return true;
}

QString BranchModel::toolTip(const QString &sha) const
{
    // Show the sha description excluding diff as toolTip
    QString output;
    QString errorMessage;
    if (!m_client->synchronousShow(m_workingDirectory, sha, &output, &errorMessage))
        return errorMessage;
    // Remove 'diff' output
    const int diffPos = output.indexOf(QLatin1String("\ndiff --"));
    if (diffPos != -1)
        output.remove(diffPos, output.size() - diffPos);
    return output;
}

}
}

<commit_msg>Compile Windows<commit_after>#include "branchmodel.h"
#include "gitclient.h"

#include <QtCore/QDebug>

enum { debug = 0 };

namespace Git {
    namespace Internal {

// Parse a branch line: " *name sha description".  Return  true if it is
// the current one
bool BranchModel::Branch::parse(const QString &lineIn, bool *isCurrent)
{
    if (debug)
        qDebug() << Q_FUNC_INFO << lineIn;

    *isCurrent = lineIn.startsWith(QLatin1String("* "));
    if (lineIn.size() < 3)
        return false;

    const QStringList tokens =lineIn.mid(2).split(QLatin1Char(' '), QString::SkipEmptyParts);
    if (tokens.size() < 2)
        return false;
    name = tokens.at(0);
    currentSHA= tokens.at(1);
    toolTip.clear();
    return true;
}

static inline Qt::ItemFlags typeToModelFlags(BranchModel::Type t)
{
    Qt::ItemFlags rc = Qt::ItemIsSelectable|Qt::ItemIsEnabled;
    if (t == BranchModel::LocalBranches)
        rc |= Qt::ItemIsUserCheckable;
    return rc;
}

// --- BranchModel
BranchModel::BranchModel(GitClient *client, Type type, QObject *parent) :
    QAbstractListModel(parent),
    m_type(type),
    m_flags(typeToModelFlags(type)),
    m_client(client),
    m_currentBranch(-1)
{
}

int BranchModel::currentBranch() const
{
    return m_currentBranch;
}

QString BranchModel::branchName(int row) const
{
    return m_branches.at(row).name;
}

int BranchModel::rowCount(const QModelIndex & /* parent */) const
{
    return m_branches.size();
}

QVariant BranchModel::data(const QModelIndex &index, int role) const
{
    const int row = index.row();
    switch (role) {
        case Qt::DisplayRole:
        return branchName(row);
        case Qt::ToolTipRole:
        if (m_branches.at(row).toolTip.isEmpty())
            m_branches.at(row).toolTip = toolTip(m_branches.at(row).currentSHA);
        return m_branches.at(row).toolTip;
        break;
        case Qt::CheckStateRole:
        if (m_type == RemoteBranches)
            return QVariant();
        return row == m_currentBranch ? Qt::Checked : Qt::Unchecked;
        default:
        break;
    }
    return QVariant();
}

Qt::ItemFlags BranchModel::flags(const QModelIndex & /*index */) const
{
    return m_flags;
}

bool BranchModel::refresh(const QString &workingDirectory, QString *errorMessage)
{
    // Run branch command with verbose.
    QStringList branchArgs(QLatin1String("-v"));
    QString output;
    if (m_type == RemoteBranches)
        branchArgs.push_back(QLatin1String("-r"));
    if (!m_client->synchronousBranchCmd(workingDirectory, branchArgs, &output, errorMessage))
        return false;
    if (debug)
        qDebug() << Q_FUNC_INFO << workingDirectory << output;
    // Parse output
    m_workingDirectory = workingDirectory;
    m_branches.clear();
    m_currentBranch = -1;
    const QStringList branches = output.split(QLatin1Char('\n'));
    const int branchCount = branches.size();
    bool isCurrent;
    for (int b = 0; b < branchCount; b++) {
        Branch newBranch;
        if (newBranch.parse(branches.at(b), &isCurrent)) {
            m_branches.push_back(newBranch);
            if (isCurrent)
                m_currentBranch = b;
        }
    }
    reset();
    return true;
}

QString BranchModel::toolTip(const QString &sha) const
{
    // Show the sha description excluding diff as toolTip
    QString output;
    QString errorMessage;
    if (!m_client->synchronousShow(m_workingDirectory, sha, &output, &errorMessage))
        return errorMessage;
    // Remove 'diff' output
    const int diffPos = output.indexOf(QLatin1String("\ndiff --"));
    if (diffPos != -1)
        output.remove(diffPos, output.size() - diffPos);
    return output;
}

}
}

<|endoftext|>


<commit_before>//calculates the worthiest pack to go for

void worthyPack() {
    for(int i = 0; i < 4; i++) {    //we ignore small packs, not worth at all
        getRank(i);
    }
    getWorthyPackInfo();
    setDist();
}

//details about position of the pack

int itemStat(int num) {
    if(game.itemInZone(num))  //in our zone
        return 3;

    if(packInTheirZone(num) && game.hasItem(num) == 0)  //in their zone
        return 4;

    return(game.hasItem(num));  //otherwise,
}

//get rating for each pack based on their status
void getRank(int num) {
    float target[3];
    getMyPos();
    game.getItemLoc(target, num);
    ranking[num] = 1/(dist(myPos, target)); //the closer it is, the worthier it gets
    switch(num){
        case 0:   //large
        case 1:
            ranking[num]*=4.5;
            break;
        case 2:   //medium
        case 3:
            ranking[num]*=2.5;
            break;
    }
    switch(itemStat(num)){
        case 0:
            ranking[num]*=1;  //no special case
            break;
        case 4:
            ranking[num]*=1.75; //in their zone
            break;
        default:
            ranking[num]*=-100; //don't even consider that pack
            break;
    }
}

//processes info about packs, determining the worthiest to go for
void getWorthyPackInfo(){
    targetNumber = 0;
    float max = ranking[0];
    for(int i = 0; i < 4; i++){
        if(ranking[i] > max){
            targetNumber = i;
            max = ranking[i];
        }
    }
    game.getItemLoc(actualTarget, targetNumber);
}

//set distances for docks based on our target
void setDist(){
    switch(targetNumber){
        case 0:   //large
        case 1:
            distFromTarget = .182;   //medium distance
            distMin = 0.151;
            distMax = 0.173;
            break;
        case 2: //medium
        case 3:
            distFromTarget = .1725;
            distMin = 0.138;
            distMax = 0.160;
            break;
    }
}
<commit_msg>Edited packs page<commit_after>void worthyPack() {
    for(int i = 0; i < 4; i++) {
        getRank(i);
    }
    getWorthyPackInfo();
    setDist();
}

/*cumulative function to learn which pack is the worthiest*/

int itemStat(int num) {
    if(game.itemInZone(num))
        return 3;

    if(packInTheirZone(num) && game.hasItem(num) == 0)
        return 4;

    return(game.hasItem(num));
}

/* we check if the pack is in our or their zone to calculate the real rating of the item*/

void getRank(int num) {
    float target[3];
    getMyPos();
    game.getItemLoc(target, num);
    ranking[num] = 1/(dist(myPos, target));
    switch(num){
        case 0:   //large
        case 1:
            ranking[num]*=4.5;
            break;
        case 2:   //medium
        case 3:
            ranking[num]*=2.5;
            break;
    }
    switch(itemStat(num)){
        case 0:
            ranking[num]*=1;
            break;
        case 4:
            ranking[num]*=1.75;
            break;
        default:
            ranking[num]*=-100;
            break;
    }
}

/* the rating is based on distance and points/second that the item gives*/

void getWorthyPackInfo(){
    targetNumber = 0;
    float max = ranking[0];
    for(int i = 0; i < 4; i++){
        if(ranking[i] > max){
            targetNumber = i;
            max = ranking[i];
        }
    }
    game.getItemLoc(actualTarget, targetNumber);
}

/*calculates the max valued pack */

void setDist(){
    switch(targetNumber){
        case 0:
        case 1:
            //distFromTarget = .182;
            distFromTarget = .162;
            distMin = 0.151;
            distMax = 0.173;
            break;
        case 2:
        case 3:
            //distFromTarget = .1725;
            distFromTarget = .143;
            distMin = 0.138;
            distMax = 0.160;
            break;
    }
}

/*set docking distances based on pack. (probably useless with the new functions we're using) */<|endoftext|>


<commit_before>#include "PrimitiveCreation.h"

#include "Sofa_test.h"
#include <sofa/component/collision/BarycentricContactMapper.h>
#include <sofa/component/mapping/BarycentricMapping.h>

namespace sofa {

typedef sofa::component::topology::MeshTopology MeshTopology;
typedef sofa::simulation::Node::SPtr NodePtr;
typedef sofa::component::collision::TriangleModel TriangleModel;
typedef sofa::defaulttype::Vec3Types DataTypes;
typedef DataTypes::VecCoord VecCoord;
struct BaryMapperTest  : public ::testing::Test{

    MeshTopology* initMesh(NodePtr & father);

    bool test_inside(double alpha,double beta);
    bool test_outside(int index);
    void initTriPts();

    VecCoord triPts;
    Vector3 norm;
};

void BaryMapperTest::initTriPts(){
    triPts.resize(3);
    triPts[0] = Vector3(-1,-1,0);
    triPts[1] = Vector3(1,-1,0);
    triPts[2] = Vector3(0,1,0);
}

double tol = 1e-6;
double tol2 = tol*tol;
//BaryMapperTest::initTriPts();

//Vector3 BaryMapperTest::triPts[] = {Vector3(-1,-1,0),Vector3(1,-1,0),Vector3(0,1,0)};

static bool equal(const Vector3 & v0,const Vector3 & v1){
    return (v0 - v1).norm2() <= tol2;
}

MeshTopology* BaryMapperTest::initMesh(NodePtr &father){
    makeTri(triPts[0],triPts[1],triPts[2],Vector3(0,0,0),father);
    norm = cross(-triPts[0] + triPts[1],triPts[2] - triPts[0]);
    norm.normalize();

    return father->getTreeObject<MeshTopology>();
}

//sofa::BaryMapperTest::triPts[0] = Vector3(-1,-1,0);
//triPts[0];// = Vector3(-1,-1,0);

//sofa::defaulttype::Rigid3Types zz;
//BarycentricMapperMeshTopology(core::topology::BaseMeshTopology* fromTopology,
//        component::topology::PointSetTopologyContainer* toTopology,
//        helper::ParticleMask *_maskFrom,
//        helper::ParticleMask *_maskTo)
//    : TopologyBarycentricMapper<In,Out>(fromTopology, toTopology),
//      maskFrom(_maskFrom), maskTo(_maskTo),
//      matrixJ(NULL), updateJ(true)
//{
//}

bool BaryMapperTest::test_inside(double alpha,double beta){
    initTriPts();
    sofa::simulation::Node::SPtr father = New<sofa::simulation::tree::GNode>();
    MeshTopology * topo = initMesh(father);
    //makeTri()
    component::mapping::BarycentricMapperMeshTopology<DataTypes, DataTypes>::SPtr mapper = sofa::core::objectmodel::New<component::mapping::BarycentricMapperMeshTopology<DataTypes, DataTypes> >(topo,(component::topology::PointSetTopologyContainer*)0x0,(helper::ParticleMask *)0x0,(helper::ParticleMask *)0x0/*model->getMeshTopology(), (topology::PointSetTopologyContainer*)NULL, &model->getMechanicalState()->forceMask, &mstate->forceMask*/);

    Vector3 the_point = (1 - alpha - beta) * triPts[0] + alpha * triPts[1] + beta * triPts[2];
    Vector3 the_point_trans = the_point + 10.0 * norm;
    mapper->createPointInTriangle( the_point_trans, 0, &triPts );

    VecCoord res;

    mapper->apply ( res, triPts );

    return equal(the_point,res[0]);
}

bool BaryMapperTest::test_outside(int index){
    initTriPts();
    sofa::simulation::Node::SPtr father = New<sofa::simulation::tree::GNode>();
    MeshTopology * topo = initMesh(father);
    //makeTri()
    component::mapping::BarycentricMapperMeshTopology<DataTypes, DataTypes>::SPtr mapper = sofa::core::objectmodel::New<component::mapping::BarycentricMapperMeshTopology<DataTypes, DataTypes> >(topo,(component::topology::PointSetTopologyContainer*)0x0,(helper::ParticleMask *)0x0,(helper::ParticleMask *)0x0/*model->getMeshTopology(), (topology::PointSetTopologyContainer*)NULL, &model->getMechanicalState()->forceMask, &mstate->forceMask*/);

    Vector3 the_point = 2.0 * triPts[index] + 10.0 * norm;

    mapper->createPointInTriangle( the_point, 0, &triPts );

    VecCoord res;

    mapper->apply ( res, triPts );

    return equal(triPts[index],res[0]);
}

TEST_F(BaryMapperTest, alpha0dot3_beta0dot2 ) { ASSERT_TRUE( test_inside(0.3,0.2)); }
TEST_F(BaryMapperTest, alpha0dot4_beta0dot6 ) { ASSERT_TRUE( test_inside(0.4,0.6)); }
TEST_F(BaryMapperTest, alpha0_beta0 ) { ASSERT_TRUE( test_inside(0,0)); }
TEST_F(BaryMapperTest, out_0 ) { ASSERT_TRUE( test_outside(0)); }
TEST_F(BaryMapperTest, out_1 ) { ASSERT_TRUE( test_outside(1)); }
TEST_F(BaryMapperTest, out_2 ) { ASSERT_TRUE( test_outside(2)); }

}

<commit_msg>r10427/sofa : Compilation fix number 3<commit_after>#include "PrimitiveCreation.h"

#include "Sofa_test.h"
#include <sofa/component/collision/BarycentricContactMapper.h>
#include <sofa/component/mapping/BarycentricMapping.h>

namespace sofa {

typedef sofa::component::topology::MeshTopology MeshTopology;
typedef sofa::simulation::Node::SPtr NodePtr;
typedef sofa::component::collision::TriangleModel TriangleModel;
typedef sofa::defaulttype::Vec3Types DataTypes;
typedef DataTypes::VecCoord VecCoord;
struct BaryMapperTest  : public ::testing::Test{

    MeshTopology* initMesh(NodePtr & father);

    bool test_inside(SReal alpha,SReal beta);
    bool test_outside(int index);
    void initTriPts();

    VecCoord triPts;
    Vector3 norm;
};

void BaryMapperTest::initTriPts(){
    triPts.resize(3);
    triPts[0] = Vector3(-1,-1,0);
    triPts[1] = Vector3(1,-1,0);
    triPts[2] = Vector3(0,1,0);
}

SReal tol = 1e-6;
SReal tol2 = tol*tol;
//BaryMapperTest::initTriPts();

//Vector3 BaryMapperTest::triPts[] = {Vector3(-1,-1,0),Vector3(1,-1,0),Vector3(0,1,0)};

static bool equal(const Vector3 & v0,const Vector3 & v1){
    return (v0 - v1).norm2() <= tol2;
}

MeshTopology* BaryMapperTest::initMesh(NodePtr &father){
    makeTri(triPts[0],triPts[1],triPts[2],Vector3(0,0,0),father);
    norm = cross(-triPts[0] + triPts[1],triPts[2] - triPts[0]);
    norm.normalize();

    return father->getTreeObject<MeshTopology>();
}

//sofa::BaryMapperTest::triPts[0] = Vector3(-1,-1,0);
//triPts[0];// = Vector3(-1,-1,0);

//sofa::defaulttype::Rigid3Types zz;
//BarycentricMapperMeshTopology(core::topology::BaseMeshTopology* fromTopology,
//        component::topology::PointSetTopologyContainer* toTopology,
//        helper::ParticleMask *_maskFrom,
//        helper::ParticleMask *_maskTo)
//    : TopologyBarycentricMapper<In,Out>(fromTopology, toTopology),
//      maskFrom(_maskFrom), maskTo(_maskTo),
//      matrixJ(NULL), updateJ(true)
//{
//}

bool BaryMapperTest::test_inside(SReal alpha,SReal beta){
    initTriPts();
    sofa::simulation::Node::SPtr father = New<sofa::simulation::tree::GNode>();
    MeshTopology * topo = initMesh(father);
    //makeTri()
    component::mapping::BarycentricMapperMeshTopology<DataTypes, DataTypes>::SPtr mapper = sofa::core::objectmodel::New<component::mapping::BarycentricMapperMeshTopology<DataTypes, DataTypes> >(topo,(component::topology::PointSetTopologyContainer*)0x0,(helper::ParticleMask *)0x0,(helper::ParticleMask *)0x0/*model->getMeshTopology(), (topology::PointSetTopologyContainer*)NULL, &model->getMechanicalState()->forceMask, &mstate->forceMask*/);

    Vector3 the_point = ((SReal)(1.0) - alpha - beta) * triPts[0] + alpha * triPts[1] + beta * triPts[2];
    Vector3 the_point_trans = the_point + (SReal)(10.0) * norm;
    mapper->createPointInTriangle( the_point_trans, 0, &triPts );

    VecCoord res;

    mapper->apply ( res, triPts );

    return equal(the_point,res[0]);
}

bool BaryMapperTest::test_outside(int index){
    initTriPts();
    sofa::simulation::Node::SPtr father = New<sofa::simulation::tree::GNode>();
    MeshTopology * topo = initMesh(father);
    //makeTri()
    component::mapping::BarycentricMapperMeshTopology<DataTypes, DataTypes>::SPtr mapper = sofa::core::objectmodel::New<component::mapping::BarycentricMapperMeshTopology<DataTypes, DataTypes> >(topo,(component::topology::PointSetTopologyContainer*)0x0,(helper::ParticleMask *)0x0,(helper::ParticleMask *)0x0/*model->getMeshTopology(), (topology::PointSetTopologyContainer*)NULL, &model->getMechanicalState()->forceMask, &mstate->forceMask*/);

    Vector3 the_point = (SReal)(2.0) * triPts[index] + (SReal)(10.0) * norm;

    mapper->createPointInTriangle( the_point, 0, &triPts );

    VecCoord res;

    mapper->apply ( res, triPts );

    return equal(triPts[index],res[0]);
}

TEST_F(BaryMapperTest, alpha0dot3_beta0dot2 ) { ASSERT_TRUE( test_inside((SReal)(0.3),(SReal)(0.2))); }
TEST_F(BaryMapperTest, alpha0dot4_beta0dot6 ) { ASSERT_TRUE( test_inside((SReal)(0.4),(SReal)(0.6))); }
TEST_F(BaryMapperTest, alpha0_beta0 ) { ASSERT_TRUE( test_inside((SReal)(0),(SReal)(0))); }
TEST_F(BaryMapperTest, out_0 ) { ASSERT_TRUE( test_outside(0)); }
TEST_F(BaryMapperTest, out_1 ) { ASSERT_TRUE( test_outside(1)); }
TEST_F(BaryMapperTest, out_2 ) { ASSERT_TRUE( test_outside(2)); }

}

<|endoftext|>