示例#1
0
void Chest::receiveChestInfo(int chestType){
    clearContent();
    if (chestType == 1){
        Item item1("Mace of destruction","mace","none",12,2);
        Item item2("Small health potion","health potion","none",50,1);
        addContent(item1);
        addContent(item2);
    }
    else if (chestType == 2){
        Item item1("Savage axe","axe","none",18,4);
        Item item2("Small health potion","health potion","none",50,1);
        addContent(item1);
        addContent(item2);
    }
}
void UT_CMceCsReceiveQueue::UT_CMceCsReceiveQueue_IsEmptyL(  )
    {
    TMceIds ids;

    // Test empty
    EUNIT_ASSERT (iReceiveQueue->IsEmpty());
	EUNIT_ASSERT_EQUALS (0, iReceiveQueue->iReceiveItems.Count());

    // Add first item
    HBufC8* headers = HBufC8::NewL(1);
    CleanupStack::PushL (headers);
    HBufC8* content = HBufC8::NewLC(1);
    TMceCSReceiveItem item1(ids,headers,content,ETrue);
	User::LeaveIfError(iReceiveQueue->AddLast(item1));
    CleanupStack::Pop (2); // content, headers 
    EUNIT_ASSERT (!iReceiveQueue->IsEmpty());
    EUNIT_ASSERT_EQUALS (1, iReceiveQueue->iReceiveItems.Count());

    // Add second item
    TMceCSReceiveItem item2(ids,KErrGeneral);
    User::LeaveIfError(iReceiveQueue->AddLast(item2));
    EUNIT_ASSERT (!iReceiveQueue->IsEmpty());
	EUNIT_ASSERT_EQUALS (2, iReceiveQueue->iReceiveItems.Count());

    // Test remove first item
    iReceiveQueue->RemoveFirst();
    EUNIT_ASSERT (!iReceiveQueue->IsEmpty());
	EUNIT_ASSERT_EQUALS (1, iReceiveQueue->iReceiveItems.Count());

    // Test remove second item
    iReceiveQueue->RemoveFirst();
    EUNIT_ASSERT (iReceiveQueue->IsEmpty());
    EUNIT_ASSERT_EQUALS (0, iReceiveQueue->iReceiveItems.Count());
    }
void
dmz::QtLuaProfilerTable::on_saveButton_clicked () {

   QString fileName =
      QFileDialog::getSaveFileName (
         this,
         tr ("Save Profiler Results"),
         "", // _get_last_path (),
         QString ("*.txt"));

   if (!fileName.isEmpty ()) {

      FILE *file = open_file (qPrintable (fileName), "wb");

      if (file) {

         StreamFile out (file);

         const int Rows (model.rowCount ());

         for (int ix = 0; ix < Rows; ix++) {

            QStandardItem *item1 (model.item (ix, 1));
            QStandardItem *item2 (model.item (ix, 2));
            QStandardItem *item3 (model.item (ix, 3));

            out << qPrintable (item1->text ()) << endl
               << qPrintable (item2->text ()) << endl
               << qPrintable (item3->text ()) << endl;
         }

         close_file (file);
      }
   }
}
示例#4
0
int main() {
	Sales_data item("s-001", 10, 5);
	Sales_data item2("s-001", 20, 3);
	item += item2;
	std::cout << item;
	system("pause");
	return 0;
}
示例#5
0
TEST(TodoListTest, TestListHasItem) {
  RTT::TodoList list;
  RTT::TodoItem item1;
  RTT::TodoItem item2("Hejsan");
  item1.buildItem(ITEM1);
  list.buildList(RAWLIST1);
  EXPECT_TRUE(list.hasItem(item1));
  EXPECT_FALSE(list.hasItem(item2));
}
示例#6
0
static int
p_item2(void)
{
  YAP_Term titem;
  int x = YAP_IntOfTerm(YAP_ARG2);
  int y = YAP_IntOfTerm(YAP_ARG3);

  titem = YAP_ARG4;
  return item2(YAP_ARG1,titem,x,y);
}
示例#7
0
static int
p_item2_1(void)
{
  YAP_Term titem;
  int offx = YAP_IntOfTerm(YAP_ARG2)-1;
  int offy = YAP_IntOfTerm(YAP_ARG3)-1;

  titem = YAP_ARG4;
  return item2(YAP_ARG1,titem,offx,offy);
}
示例#8
0
void MainWindow::fillBIItemsList()
{    
    // fill list with call to library or interface
    // maybe do this in the constructor instead
    BIItem item("/Users/Eric/Desktop/test.exe", "/Users/Eric/Pictures/Deadmau5.png", "Testing");
    BIItem item2("/Users/Eric/Desktop/test.exe", "/Users/eric/Documents/School/UTC [Past]/CPSC 261 (C++)/Game.ico", "Testing Again");
    BIItem item3("/Users/Eric/Desktop/test.exe", "/Users/Eric/Pictures/appletimeline.tiff", "Testing Some More");

    //list.push_back(item);
    //list.push_back(item2);
    //list.push_back(item3);
}
示例#9
0
TEST(MooseEnumItem, assignment_and_copy)
{
  MooseEnumItem item("Andrew", 1980);
  MooseEnumItem item2("Edward", 1949);
  item = item2;
  EXPECT_EQ(item.name(), "EDWARD");
  EXPECT_EQ(item.id(), 1949);
  EXPECT_EQ(item.rawName(), "Edward");

  MooseEnumItem item3(item2);
  EXPECT_EQ(item3.name(), "EDWARD");
  EXPECT_EQ(item3.id(), 1949);
  EXPECT_EQ(item3.rawName(), "Edward");
}
示例#10
0
TEST(TestFileOperationJob, ActionDelete)
{
    XFILE::CFile *tmpfile;
    CStdString tmpfilepath, destpath, destfile;
    CFileItemList items;
    CFileOperationJob job;

    ASSERT_TRUE((tmpfile = XBMC_CREATETEMPFILE("")));
    tmpfilepath = XBMC_TEMPFILEPATH(tmpfile);
    tmpfile->Close();

    CFileItemPtr item(new CFileItem(tmpfilepath));
    item->SetPath(tmpfilepath);
    item->m_bIsFolder = false;
    item->Select(true);
    items.Add(item);

    URIUtils::GetDirectory(tmpfilepath, destpath);
    destpath = URIUtils::AddFileToFolder(destpath, "delete");
    destfile = URIUtils::AddFileToFolder(destpath, URIUtils::GetFileName(tmpfilepath));
    ASSERT_FALSE(XFILE::CFile::Exists(destfile));

    job.SetFileOperation(CFileOperationJob::ActionCopy, items, destpath);
    EXPECT_EQ(CFileOperationJob::ActionCopy, job.GetAction());

    EXPECT_TRUE(job.DoWork());
    EXPECT_TRUE(XFILE::CFile::Exists(tmpfilepath));
    EXPECT_TRUE(XFILE::CFile::Exists(destfile));

    job.SetFileOperation(CFileOperationJob::ActionDelete, items, "");
    EXPECT_EQ(CFileOperationJob::ActionDelete, job.GetAction());

    EXPECT_TRUE(job.DoWork());
    EXPECT_FALSE(XFILE::CFile::Exists(tmpfilepath));

    items.Clear();
    CFileItemPtr item2(new CFileItem(destfile));
    item2->SetPath(destfile);
    item2->m_bIsFolder = false;
    item2->Select(true);
    items.Add(item2);

    job.SetFileOperation(CFileOperationJob::ActionDelete, items, "");
    EXPECT_EQ(CFileOperationJob::ActionDelete, job.GetAction());

    EXPECT_TRUE(job.DoWork());
    EXPECT_FALSE(XFILE::CFile::Exists(destfile));
    EXPECT_TRUE(XFILE::CDirectory::Remove(destpath));
}
int main(int argc, char** argv) {
    
    gnt::ItemDemanda item1;                      // Construtor Default
    gnt::ItemDemanda item2(27.3, 300);           // Contrutor
    gnt::ItemDemanda item3(item2);               // Construtor de copia
    
    
    std::cout << "Impressao do item 1 -> " << item1 << std::endl;
    std::cout << "Impressao do item 2 -> " << item2 << std::endl;
    std::cout << "Impressao do item 3 -> " << item3 << std::endl;
    
    std::cout << "\nTamanho do item 3 = " << item3.Largura() << std::endl;
    std::cout << "Quantidade do item 3 = " << item3.Quantidade() << std::endl;
    return 0;
}
示例#12
0
int main()
{
    Sales_data item1;
    print(std::cout, item1) << std::endl;
    
    Sales_data item2("0-201-78345-X");
    print(std::cout, item2) << std::endl;
    
    Sales_data item3("0-201-78345-X", 3, 20.00);
    print(std::cout, item3) << std::endl;
    
    Sales_data item4(std::cin);
    print(std::cout, item4) << std::endl;
    
    return 0;
}
示例#13
0
TEST(Test_ThreadSafeSet, Add)
{
	Item item1(10);
	Item item2(2);
	Item item3(11);

	SafeSet<Item, ItemLess> set;

	ASSERT_EQ(set.Insert(item1), true);
	ASSERT_EQ(set.Size(), 1);
	ASSERT_EQ(set.Insert(item1), false);
	ASSERT_EQ(set.Size(), 1);
	ASSERT_EQ(set.Insert(item2), true);
	ASSERT_EQ(set.Size(), 2);
	ASSERT_EQ(set.Insert(item3), true);
	ASSERT_EQ(set.Size(), 3);
}
示例#14
0
void TimeAccessor_removeShortTimeSpans()
{
    TempDB db;
    std::shared_ptr<TimeAccessor> timeAccessor = std::dynamic_pointer_cast<TimeAccessor>(db.getTimeAccessor());
    std::shared_ptr<IExtendedTaskAccessor> taskAccessor = db.getExtendedTaskAccessor();
    const int64_t taskId = taskAccessor->newTask("test", 0);
    TimeEntry item1(0, UUID::randomUUID(), taskId, "", 100, 110, false, false, 200);
    TimeEntry item2(0, UUID::randomUUID(), taskId, "", 100, 160, false, false, 200);

    timeAccessor->newEntry(item1);
    timeAccessor->newEntry(item2);
    timeAccessor->removeShortTimeSpans();

    std::vector<TimeEntry> items = timeAccessor->getDetailTimeList(taskId, 0, 1000);

    ASSERT_EQUAL(1, items.size());
}
示例#15
0
文件: main.cpp 项目: Hidestorm/15.8.3
int main()
{
	Basket basket;
	Sales_item item1(Bulk_item("0-0001-0001-1", 99, 20, 0.5));
	Sales_item item2(Bulk_item("0-0001-0001-2", 50));
	Sales_item item3(Bulk_item("0-0001-0001-3", 59, 200, 0.3));
	Sales_item item4(Bulk_item("0-0001-0001-1", 99, 20, 0.2));

	basket.add_item(item1);
	basket.add_item(item2);
	basket.add_item(item3);
	basket.add_item(item4);

	cout << basket.total() << endl;
	system("pause");
	return 0;
}
示例#16
0
TEST(TestFileOperationJob, ActionDelete)
{
  XFILE::CFile *tmpfile;
  CStdString tmpfilepath, destpath;
  CFileItemList items;
  CFileOperationJob job;

  ASSERT_TRUE((tmpfile = XBMC_CREATETEMPFILE("")));
  tmpfilepath = XBMC_TEMPFILEPATH(tmpfile);

  CFileItemPtr item(new CFileItem(tmpfilepath));
  item->SetPath(tmpfilepath);
  item->m_bIsFolder = false;
  item->Select(true);
  items.Add(item);

  destpath = tmpfilepath;
  destpath += ".delete";
  ASSERT_FALSE(XFILE::CFile::Exists(destpath));

  job.SetFileOperation(CFileOperationJob::ActionCopy, items, destpath);
  EXPECT_EQ(CFileOperationJob::ActionCopy, job.GetAction());

  EXPECT_TRUE(job.DoWork());
  EXPECT_TRUE(XFILE::CFile::Exists(tmpfilepath));
  EXPECT_TRUE(XFILE::CFile::Exists(destpath));

  job.SetFileOperation(CFileOperationJob::ActionDelete, items, "");
  EXPECT_EQ(CFileOperationJob::ActionDelete, job.GetAction());

  EXPECT_TRUE(job.DoWork());
  EXPECT_FALSE(XFILE::CFile::Exists(tmpfilepath));

  items.Clear();
  CFileItemPtr item2(new CFileItem(destpath));
  item->SetPath(destpath);
  item->m_bIsFolder = false;
  item->Select(true);
  items.Add(item2);

  job.SetFileOperation(CFileOperationJob::ActionDelete, items, "");
  EXPECT_EQ(CFileOperationJob::ActionDelete, job.GetAction());

  EXPECT_TRUE(job.DoWork());
  EXPECT_FALSE(XFILE::CFile::Exists(destpath));
}
示例#17
0
TEST(MooseEnumItem, lessthan)
{
  MooseEnumItem item1("Andrew", 1980);
  MooseEnumItem item2("Deanne", 1980);
  MooseEnumItem item3("Isaac", 2011);
  MooseEnumItem item4("Allison", 2013);

  std::set<MooseEnumItem> items;
  items.insert(item4);
  items.insert(item3);
  items.insert(item2);
  items.insert(item1);
  EXPECT_NE(items.find(item1), items.end());
  EXPECT_NE(items.find(item2), items.end());
  EXPECT_NE(items.find(item3), items.end());
  EXPECT_NE(items.find(item4), items.end());
  EXPECT_EQ(items.find(MooseEnumItem("Edward", 1949)), items.end());
}
void UT_CMceCsReceiveQueue::UT_CMceCsReceiveQueue_Add_RemoveL(  )
    {
    TMceIds ids;

    EUNIT_ASSERT (iReceiveQueue->IsEmpty());
    iReceiveQueue->RemoveFirst();
    EUNIT_ASSERT (iReceiveQueue->IsEmpty());

    // Add first item
	ids.iSessionID = 1;
    HBufC8* headers = HBufC8::NewL(1);
    CleanupStack::PushL (headers);
    HBufC8* content = HBufC8::NewLC(1);
    TMceCSReceiveItem item1(ids,headers,content);
	User::LeaveIfError(iReceiveQueue->AddLast(item1));
    CleanupStack::Pop (2); // content, headers
    EUNIT_ASSERT (iReceiveQueue->First().Ids().iSessionID ==  1);
    EUNIT_ASSERT (iReceiveQueue->First().Context() == headers);
    EUNIT_ASSERT (iReceiveQueue->First().Content() == content);
    EUNIT_ASSERT (iReceiveQueue->First().Error() == KErrNone);

    // Add second item to the end of the queue.
    // Test that first added is still first in queue
	ids.iSessionID = 2;
    TMceCSReceiveItem item2(ids,KErrGeneral);
    User::LeaveIfError(iReceiveQueue->AddLast(item2));
    EUNIT_ASSERT (iReceiveQueue->First().Ids().iSessionID == 1);
    EUNIT_ASSERT (iReceiveQueue->First().Context() == headers);
    EUNIT_ASSERT (iReceiveQueue->First().Content() == content);
    EUNIT_ASSERT (iReceiveQueue->First().Error() == KErrNone);

    // Remove first. Last added should be first now.
    iReceiveQueue->RemoveFirst();
    EUNIT_ASSERT (iReceiveQueue->First().Ids().iSessionID == 2);
    EUNIT_ASSERT (iReceiveQueue->First().Context() == 0);
    EUNIT_ASSERT (iReceiveQueue->First().Content() == 0);
    EUNIT_ASSERT (iReceiveQueue->First().Error() == KErrGeneral);

    // Test that the queue is empty after removing the only item:
    iReceiveQueue->RemoveFirst();
    EUNIT_ASSERT (iReceiveQueue->IsEmpty());
    }
示例#19
0
void TestMessageManager::testNotify()
{
	DummyMessageListener listener;
	DummyMessageGetter getter;
	MessageManager manager(&getter, &listener);

	Message item1("Title 1","Summary 1","Author 1","Email 1");
	getter.items_.push_back(item1);
	manager.fetchMessages();
	CPPUNIT_ASSERT_EQUAL(0U, listener.nb_nomessages_called_);
	CPPUNIT_ASSERT_EQUAL(1U, (unsigned int) listener.items_.size());
	CPPUNIT_ASSERT(item1 == listener.items_[0]);

	listener.items_.clear();
	manager.fetchMessages();
	CPPUNIT_ASSERT_EQUAL(0U, listener.nb_nomessages_called_);
	CPPUNIT_ASSERT_EQUAL(0U, (unsigned int) listener.items_.size());

	Message item2("Title 2","Summary 2","Author 2","Email 2");
	Message item3("Title 3","Summary 3","Author 3","Email 3");
	getter.items_.push_back(item2);
	getter.items_.push_back(item3);
	manager.fetchMessages();
	CPPUNIT_ASSERT_EQUAL(0U, listener.nb_nomessages_called_);
	CPPUNIT_ASSERT_EQUAL(2U, (unsigned int) listener.items_.size());
	CPPUNIT_ASSERT(item2 == listener.items_[0]);
	CPPUNIT_ASSERT(item3 == listener.items_[1]);

	getter.items_.clear();
	listener.items_.clear();
	manager.fetchMessages();
	CPPUNIT_ASSERT_EQUAL(1U, listener.nb_nomessages_called_);
	CPPUNIT_ASSERT_EQUAL(0U, (unsigned int) listener.items_.size());

	manager.fetchMessages();
	CPPUNIT_ASSERT_EQUAL(1U, listener.nb_nomessages_called_);
	CPPUNIT_ASSERT_EQUAL(0U, (unsigned int) listener.items_.size());
}
示例#20
0
文件: main.cpp 项目: jonnenauha/code
QtApplication::QtApplication (int &argc, char **argv) :
    QApplication (argc, argv)
{
    //view_ = new RedirectedGraphicsView ();
    view_ = new QGraphicsView ();
    scene_ = new QGraphicsScene ();

    QDialog *dialog1 = new QDialog ();
    QDialog *dialog2 = new QDialog ();

    dialog1-> setWindowOpacity (0.8);
    dialog1-> setWindowTitle ("testing baby");
    dialog1-> setLayout (new QVBoxLayout);
    dialog1-> layout()-> addWidget (new QLineEdit);

    dialog2-> setWindowOpacity (0.8);
    dialog2-> setWindowTitle ("you suck");
    dialog2-> setLayout (new QVBoxLayout);
    dialog2-> layout()-> addWidget (new QLineEdit);

    scene_-> addWidget (dialog1);
    scene_-> addWidget (dialog2);
    view_-> setScene (scene_);
    view_-> setViewportUpdateMode (QGraphicsView::FullViewportUpdate);

    QGraphicsItem *item1 (view_-> items().takeAt (0));
    item1-> setFlag (QGraphicsItem::ItemIsMovable);
    item1-> setCacheMode (QGraphicsItem::DeviceCoordinateCache);
    item1-> setPos (10, 50);

    QGraphicsItem *item2 (view_-> items().takeAt (1));
    item2-> setFlag (QGraphicsItem::ItemIsMovable);
    item2-> setCacheMode (QGraphicsItem::DeviceCoordinateCache);
    item2-> setPos (10, 100);

    view_-> show();
}
示例#21
0
TEST(Test_ThreadSafeSet, Remove)
{
	Item item1(10);
	Item item2(2);
	Item item3(11);

	SafeSet<Item, ItemLess> set;
	set.Remove(item1);
	ASSERT_EQ(set.Size(), 0);

	set.Insert(item1);
	set.Insert(item2);
	set.Insert(item3);

	SafeSet<Item, ItemLess> set2 = set;
	ASSERT_EQ(set2.Size(), 3);

	set.Remove(item1);
	ASSERT_EQ(set.Size(), 2);
	set.Remove(item3);
	ASSERT_EQ(set.Size(), 1);
	set.Remove(item2);
	ASSERT_EQ(set.Size(), 0);
}
示例#22
0
文件: Pr13-12.cpp 项目: Hongclass/C-
int main()
{
	// Create an InventoryItem object and call
	// the default constructor.
	InventoryItem item1;
	item1.setDescription("Hammer");	// Set the description
	item1.setCost(6.95);			// Set the cost
	item1.setUnits(12);				// Set the units

	// Create an InventoryItem object and call
	// constructor #2.
	InventoryItem item2("Pliers");

	// Create an InventoryItem object and call
	// constructor #3.
	InventoryItem item3("Wrench", 8.75, 20);

	cout << "The following items are in inventory:\n";
	cout << setprecision(2) << fixed << showpoint;

	// Display the data for item 1.
	cout << "Description: " << item1.getDescription() << endl;
	cout << "Cost: $" << item1.getCost() << endl;
	cout << "Units on Hand: " << item1.getUnits() << endl << endl;

	// Display the data for item 2.
	cout << "Description: " << item2.getDescription() << endl;
	cout << "Cost: $" << item2.getCost() << endl;
	cout << "Units on Hand: " << item2.getUnits() << endl << endl;

	// Display the data for item 3.
	cout << "Description: " << item3.getDescription() << endl;
	cout << "Cost: $" << item3.getCost() << endl;
	cout << "Units on Hand: " << item3.getUnits() << endl;
	return 0;
}
void UT_CMceCsReceiverBase::UT_CMceCsReceiverBase_ClientReadyToReceiveLL()
    {
    
    EUNIT_ASSERT( iReceiver->iReceiveQueue->IsEmpty() );
    
     // Test with nothing in the receive queue
    EUNIT_ASSERT( !iReceiver->iClientReadyToReceive );
    iReceiver->ClientReadyToReceiveL( RMessage2() );
    EUNIT_ASSERT( iReceiver->iClientReadyToReceive );
    
    iReceiver->iClientReadyToReceive = ETrue;
    EUNIT_ASSERT( iReceiver->iClientReadyToReceive );
    EUNIT_ASSERT_LEAVE( iReceiver->ClientReadyToReceiveL( RMessage2() ) );
    EUNIT_ASSERT( iReceiver->iClientReadyToReceive );
    
    iReceiver->iClientReadyToReceive = EFalse;

    TMceIds ids;
	TMceCSReceiveItem item1( ids, KErrNone );

    iReceiver->iReceiveQueue->AddLast( item1 );
    iReceiver->ClientReadyToReceiveL( RMessage2() );
    
    EUNIT_ASSERT( iReceiver->iReceiveQueue->IsEmpty() );

    HBufC8* context = _L8("context").AllocLC();
    HBufC8* content = NULL;
    
	TMceCSReceiveItem item2( ids, context, content );
    iReceiver->iReceiveQueue->AddLast( item2 );
	CleanupStack::Pop( context );
    
    iReceiver->ClientReadyToReceiveL( RMessage2() );
    
    EUNIT_ASSERT( !iReceiver->iReceiveQueue->IsEmpty() );
	iReceiver->ReceiveL( RMessage2() );
    EUNIT_ASSERT( iReceiver->iReceiveQueue->IsEmpty() );

    context = _L8("context").AllocLC();
    content = _L8("content").AllocLC();
    
	TMceCSReceiveItem item3( ids, context, content );
	CleanupStack::Pop( content );
	CleanupStack::Pop( context );

    iReceiver->iReceiveQueue->AddLast( item3 );
    iReceiver->ClientReadyToReceiveL( RMessage2() );
    
    EUNIT_ASSERT( !iReceiver->iReceiveQueue->IsEmpty() );
	iReceiver->ReceiveL( RMessage2() );
    EUNIT_ASSERT( iReceiver->iReceiveQueue->IsEmpty() );

    context = NULL;
    content = _L8("content").AllocLC();
    
	TMceCSReceiveItem item4( ids, context, content );
    iReceiver->iReceiveQueue->AddLast( item4 );
	CleanupStack::Pop( content );
    
    iReceiver->ClientReadyToReceiveL( RMessage2() );
    
    EUNIT_ASSERT( !iReceiver->iReceiveQueue->IsEmpty() );
	iReceiver->ReceiveL( RMessage2() );
    EUNIT_ASSERT( iReceiver->iReceiveQueue->IsEmpty() );
    

    }
示例#24
0
void PyHelpersTest::RunTests()
{
  // Test py::Ptr construction
  {
    {
      // NULL pointer
      PyObject * p  = NULL;
      SHOULDFAIL(py::Ptr(p, /* allowNULL: */false));

      py::Ptr pp1(p, /* allowNULL: */true);
      TEST((PyObject *)pp1 == NULL);
      TEST(pp1.isNULL());
    }

    // Non-NULL pointer
    {
      PyObject * p = PyTuple_New(1);
      py::Ptr pp2(p);
      TEST(!pp2.isNULL());
      TEST((PyObject *)pp2 == p);
      pp2.release();
      TEST(pp2.isNULL());
      Py_DECREF(p);
    }
    
    // assign
    {
      PyObject * p = PyTuple_New(1);
      TEST(p->ob_refcnt == 1);
      py::Ptr pp(NULL, /* allowNULL */ true);
      TEST(pp.isNULL());
      NTA_DEBUG << "*** Before assign";
      pp.assign(p);
      NTA_DEBUG << "*** After assign";
      TEST(p->ob_refcnt == 2);
      TEST(!(pp.isNULL()));
      Py_DECREF(p);
      TEST(p->ob_refcnt == 1);
    }
  }

  // py::String
  {
    py::String ps1(std::string("123"));
    TEST(PyString_Check(ps1) != 0);

    py::String ps2("123", size_t(3));
    TEST(PyString_Check(ps2) != 0);

    py::String ps3("123");
    TEST(PyString_Check(ps3) != 0);

    std::string s1(PyString_AsString(ps1));
    std::string s2(PyString_AsString(ps2));
    std::string s3(PyString_AsString(ps3));
    std::string expected("123");
    TEST(s1 == expected);
    TEST(s2 == expected);
    TEST(s3 == expected);
  
    TEST(std::string(ps1) == expected);
    TEST(std::string(ps2) == expected);
    TEST(std::string(ps3) == expected);

    PyObject * p = PyString_FromString("777");
    py::String ps4(p);
    TEST(std::string(ps4) == std::string("777"));
  }

  // py::Int
  {
    py::Int n1(-5);
    py::Int n2(-6666);
    py::Int n3(long(0));
    py::Int n4(555);
    py::Int n5(6666);
    
    TEST(n1 == -5);
    int x = n2; 
    int expected = -6666;
    TEST(x == expected);
    TEST(n3 == 0);
    TEST(n4 == 555);
    x = n5;
    expected = 6666;
    TEST(x == expected);
  }

  // py::Long
  {
    py::Long n1(-5);
    py::Long n2(-66666666);
    py::Long n3(long(0));
    py::Long n4(555);
    py::Long n5(66666666);
    
    TEST(n1 == -5);
    long x = n2; 
    long expected = -66666666;
    TEST(x == expected);
    TEST(n3 == 0);
    TEST(n4 == 555);
    x = n5;
    expected = 66666666;
    TEST(x == expected);
  }

  // py::UnsignedLong
  {
    py::UnsignedLong n1((unsigned long)(-5));
    py::UnsignedLong n2((unsigned long)(-66666666));
    py::UnsignedLong n3((unsigned long)(0));
    py::UnsignedLong n4(555);
    py::UnsignedLong n5(66666666);
    
    TEST(n1 == (unsigned long)(-5));
    TEST(n2 == (unsigned long)(-66666666));
    TEST(n3 == 0);
    TEST(n4 == 555);
    TEST(n5 == 66666666);
  }

  // py::Float
  {
    TEST(py::Float::getMax() == std::numeric_limits<double>::max());
    TEST(py::Float::getMin() == std::numeric_limits<double>::min());

    py::Float max(std::numeric_limits<double>::max());
    py::Float min(std::numeric_limits<double>::min());
    py::Float n1(-0.5);
    py::Float n2(double(0));
    py::Float n3(333.555);
    py::Float n4(0.02);
    py::Float n5("0.02");
    
    TEST(max == py::Float::getMax());
    TEST(min == py::Float::getMin());
    TEST(n1 == -0.5);
    TEST(n2 == 0);
    TEST(n3 == 333.555);
    TEST(n4 == 0.02);
    TEST(n5 == 0.02);
  }

  // py::Tuple
  {
    py::String s1("item_1");
    py::String s2("item_2");

    // Empty tuple
    {
      py::Tuple empty;
      TEST(PyTuple_Check(empty) != 0);
      TEST(empty.getCount() == 0);
      
      SHOULDFAIL(empty.setItem(0, s1));
      SHOULDFAIL(empty.getItem(0));
    }

    // One item tuple
    {
      py::Tuple t1(1);
      TEST(PyTuple_Check(t1) != 0);
      TEST(t1.getCount() == 1);

      t1.setItem(0, s1);
      py::String item1(t1.getItem(0));
      TEST(std::string(item1) == std::string(s1));
      
      py::String fastItem1(t1.fastGetItem(0));
      TEST(std::string(fastItem1) == std::string(s1));
      fastItem1.release();
      
      SHOULDFAIL(t1.setItem(1, s2));
      SHOULDFAIL(t1.getItem(1));

      TEST(t1.getCount() == 1);
    }

    // 2 items tuple
    {
      py::Tuple t2(2);
      TEST(PyTuple_Check(t2) != 0);
      TEST(t2.getCount() == 2);

      t2.setItem(0, s1);
      py::String item1(t2.getItem(0));
      TEST(std::string(item1) == std::string(s1));
      py::String fastItem1(t2.fastGetItem(0));
      TEST(std::string(fastItem1) == std::string(s1));
      fastItem1.release();

      t2.setItem(1, s2);
      py::String item2(t2.getItem(1));
      TEST(std::string(item2) == std::string(s2));
      py::String fastItem2(t2.fastGetItem(1));
      TEST(std::string(fastItem2) == std::string(s2));
      fastItem2.release();


      SHOULDFAIL(t2.setItem(2, s2));
      SHOULDFAIL(t2.getItem(2));

      TEST(t2.getCount() == 2);
    }
  }

  // py::List
  {
    py::String s1("item_1");
    py::String s2("item_2");

    // Empty list
    {
      py::List empty;
      TEST(PyList_Check(empty) != 0);
      TEST(empty.getCount() == 0);
      
      SHOULDFAIL(empty.setItem(0, s1));
      SHOULDFAIL(empty.getItem(0));
    }

    // One item list
    {
      py::List t1;
      TEST(PyList_Check(t1) != 0);
      TEST(t1.getCount() == 0);

      t1.append(s1);
      py::String item1(t1.getItem(0));
      TEST(std::string(item1) == std::string(s1));
      py::String fastItem1(t1.fastGetItem(0));
      TEST(std::string(fastItem1) == std::string(s1));
      fastItem1.release();

      TEST(t1.getCount() == 1);
      TEST(std::string(item1) == std::string(s1));
      
      SHOULDFAIL(t1.getItem(1));
    }

    // Two items list
    {
      py::List t2;
      TEST(PyList_Check(t2) != 0);
      TEST(t2.getCount() == 0);

      t2.append(s1);
      py::String item1(t2.getItem(0));
      TEST(std::string(item1) == std::string(s1));
      py::String fastItem1(t2.fastGetItem(0));
      TEST(std::string(fastItem1) == std::string(s1));
      fastItem1.release();

      t2.append(s2);
      TEST(t2.getCount() == 2);
      
      py::String item2(t2.getItem(1));
      TEST(std::string(item2) == std::string(s2));
      py::String fastItem2(t2.fastGetItem(1));
      TEST(std::string(fastItem2) == std::string(s2));
      fastItem2.release();


      SHOULDFAIL(t2.getItem(2));
    }
  }

  // py::Dict
  {
    // Empty dict
    {
      py::Dict d;
      TEST(PyDict_Size(d) == 0);

      TEST(d.getItem("blah") == NULL);
    }

    // Failed External PyObject *
    {
      // NULL object
      SHOULDFAIL(py::Dict(NULL));

      // Wrong type (must be a dictionary)
      py::String s("1234");
      try
      {
        py::Dict d(s.release());
        NTA_THROW << "py::Dict d(s) Should fail!!!";
      }
      catch(...)
      {
      }
      // SHOULDFAIL fails to fail :-)
      //SHOULDFAIL(py::Dict(s));
    }

    // Successful external PyObject *
    {

      PyObject * p = PyDict_New();
      PyDict_SetItem(p, py::String("1234"), py::String("5678"));
      
      py::Dict d(p);

      TEST(PyDict_Contains(d, py::String("1234")) == 1);

      PyDict_SetItem(d, py::String("777"), py::String("999"));

      TEST(PyDict_Contains(d, py::String("777")) == 1);

    }
    
    // getItem with default (exisiting and non-exisitng key)
    {
      py::Dict d;
      d.setItem("A", py::String("AAA"));

      PyObject * defaultItem = (PyObject *)123;
      
      py::String A(d.getItem("A"));             
      TEST(std::string(A) == std::string("AAA"));

      // No "B" in the dict, so expect to get the default item
      PyObject * B = (d.getItem("B", defaultItem));
      TEST(B == defaultItem);

      PyDict_SetItem(d, py::String("777"), py::String("999"));
      TEST(PyDict_Contains(d, py::String("777")) == 1);
    }
    
    
    //NTA_DEBUG << ss << ": " << ss->ob_refcnt;
  }

  // py::Module
  {
    py::Module module("sys");
    TEST(std::string(PyModule_GetName(module)) == std::string("sys"));
  }

  // py::Class
  {
    py::Class c("datetime", "date");
  }

  // py::Instance
  {
    
    py::Tuple args(3);
    args.setItem(0, py::Long(2000));
    args.setItem(1, py::Long(11));
    args.setItem(2, py::Long(5));
    py::Instance date("datetime", "date", args, py::Dict());

    // Test invoke()
    {
      py::String result(date.invoke("__str__", py::Tuple(), py::Dict()));
      std::string res((const char *)result);
      std::string expected("2000-11-05");
      TEST(res == expected);
    }

    // Test hasAttr()
    {
      py::String result(date.invoke("__str__", py::Tuple(), py::Dict()));
      std::string res((const char *)result);
      std::string expected("2000-11-05");
      TEST(!(date.hasAttr("No such attribute")));
      TEST(date.hasAttr("year"));
    }

    // Test getAttr()
    {
      py::Int year(date.getAttr("year"));
      TEST(2000 == long(year));
    }

    // Test toString()
    {
      std::string res((const char *)py::String(date.toString()));
      std::string expected("2000-11-05");
      TEST(res == expected);
    }
  }

  // Test custom exception
  {
    py::Tuple args(1);
    args.setItem(0, py::String("error message!"));
    py::Instance e(PyExc_RuntimeError, args);
    e.setAttr("traceback", py::String("traceback!!!"));

    PyErr_SetObject(PyExc_RuntimeError, e);

    try
    {
      py::checkPyError(0);
    }
    catch (const nta::Exception & e)
    {
      NTA_DEBUG << e.getMessage();
    }
  }
}
示例#25
0
void ArticleView::append_data_parse_result(const gchar *real_oword, 
	ParseResult& parse_result)
{
	/* Why ParseResultItem's cannot be inserted into the pango_view_ in the 
	 * order they appear in the parse_result list? 
	 * 
	 * They can, but that limits use of the pango markup language when markup 
	 * intermixed with objects that are not expressed in pango markup. 
	 * For instance we cannot handle the following piece of data:
	 * markup: "<span foreground=\"purple\">some text"
	 * res: some image
	 * markup: "text continues</span>" 
	 * The first markup string cannot be committed because it is not a valid 
	 * markup - span tag is not closed. But if we piece two markup strings 
	 * together, commit markup and then insert the resource, everything will be
	 * fine.
	 * 
	 * Here is an outline of the rules parse_result list must adhere to.
	 * 
	 * - each list item with pango markup must contain only complete tags. Tag 
	 * may not be opened in one list item and closed in another. For example
	 * this list is not allowed:
	 * markup: "<span foreground=\"purple\" "
	 * markup: "size=\"x-large\">"
	 * 
	 * - after combining all list items with pango markup the resultant string
	 * must constitute a valid markup (correct order of tags, each tag must have
	 * a corresponding closing tag and so on). For example, the following text 
	 * is not allowed: "<b> bla bla </b><i>text end".
	 * Note: list item may contain incomplete markup like "<b>text begins".
	 * 
	 * - Delayed insert items must generate only valid markup. Items 
	 * representing images, widgets generate a pango-formated error message
	 * if the primary object cannot be inserted.
	 * 
	 * 
	 * Position in the pango markup string cannot be exactly specified by 
	 * character offset only. That is especially important for LabelPangoWidget
	 * where markup is stored in a string. In order to insert delayed insert 
	 * items in the correct place it was decided to add a temporary character
	 * in the string in the place where the delayed item must be inserted.
	 * Temporary characters are deleted at the end.
	 * 
	 * In addition to character offsets marks are used to specify position in 
	 * the text. Marks must be used instead of char offsets when possible.
	 * Marks are preferred over offsets because they preserve position across
	 * text modifications, they have a notion of right and left gravity.
	 * In general we do not know how many character would be inserted in the 
	 * text after the call the method insert_pixbuf. Normally it is only one,
	 * but it may be any number in case of error.
	 * 
	 * */
	Marks marks(pango_view_.get());
	std::string start_mark = marks.append_mark(true);
	std::list<ParseResultItemWithMark> delayed_insert_list;
	// compose markup
	{
		std::string markup_str;
		int char_offset = 0;
		const char tmp_char = 'x'; // may be any unicode char excluding '<', '&', '>'

		for (std::list<ParseResultItem>::iterator it = parse_result.item_list.begin(); 
			it != parse_result.item_list.end(); ++it) {
			switch (it->type) {
				case ParseResultItemType_mark:
					char_offset += xml_utf8_strlen(it->mark->pango.c_str());
					markup_str += it->mark->pango;
					break;
				case ParseResultItemType_link:
				{
					/* links do not insert any text, so exact mark position is
					 * not important. */
					ParseResultItemWithMark item(&*it, char_offset);
					delayed_insert_list.push_back(item);
					char_offset += xml_utf8_strlen(it->link->pango.c_str());
					markup_str += it->link->pango;
					break;
				}
				case ParseResultItemType_res:
				case ParseResultItemType_widget:
				{
					ParseResultItemWithMark item1(NULL, char_offset, true);
					delayed_insert_list.push_back(item1);
					char_offset += 1;
					markup_str += tmp_char;
					ParseResultItemWithMark item2(&*it, char_offset, true);
					delayed_insert_list.push_back(item2);
					char_offset += 1;
					markup_str += tmp_char;
					break;
				}
				case ParseResultItemType_FormatBeg:
				case ParseResultItemType_FormatEnd:
				{
					/* formats do not insert any text, so exact mark position is
					 * not important. */
					ParseResultItemWithMark item2(&*it, char_offset);
					delayed_insert_list.push_back(item2);
					break;
				}
				default:
					g_warning("Unsupported item type.");
					break;
			}
		}
		append_and_mark_orig_word(markup_str, real_oword, LinksPosList());
		markup_str.clear();
		pango_view_->flush();
	}
	// Marks that precede tmp chars. One mark - one char next to it that must be 
	// deleted. Different marks do not refer to the same char.
	std::list<std::string> tmp_char_mark_list;
	// insert marks
	for(std::list<ParseResultItemWithMark>::iterator it = delayed_insert_list.begin(); 
		it != delayed_insert_list.end(); ) {
		it->mark = marks.insert_mark(start_mark, it->char_offset, false);
		if(it->tmp_char)
			tmp_char_mark_list.push_back(it->mark);
		if(it->item)
			++it;
		else
			it = delayed_insert_list.erase(it);
	}
#ifdef DDEBUG
	std::cout << "ArticleView::append_data_parse_result. marks inserted." 
		<< std::endl; 
#endif
	// insert delayed items
	for(std::list<ParseResultItemWithMark>::iterator it = delayed_insert_list.begin(); 
		it != delayed_insert_list.end(); ) {
		bool EraseCurrent = true;
		switch(it->item->type) {
		case ParseResultItemType_link:
			pango_view_->insert_pango_text_with_links("", it->item->link->links_list, 
				it->mark.c_str());
			break;
		case ParseResultItemType_res:
		{
			bool loaded = false;
			if (it->item->res->type == "image") {
				append_data_res_image(it->item->res->key, it->mark, loaded);
			} else if (it->item->res->type == "sound") {
				append_data_res_sound(it->item->res->key, it->mark, loaded);
			} else if (it->item->res->type == "video") {
				append_data_res_video(it->item->res->key, it->mark, loaded);
			} else {
				append_data_res_attachment(it->item->res->key, it->mark, loaded);
			}
			if (!loaded) {
				std::string tmark;
				tmark += "<span foreground=\"red\">";
				glib::CharStr m_str(g_markup_escape_text(it->item->res->key.c_str(), -1));
				tmark += get_impl(m_str);
				tmark += "</span>";
				pango_view_->insert_pango_text(tmark.c_str(), it->mark.c_str());
			}
			break;
		}
		case ParseResultItemType_widget:
			pango_view_->insert_widget(it->item->widget->widget, it->mark.c_str());
			break;
		case ParseResultItemType_FormatBeg:
			// change gravity of the mark
			it->mark = marks.clone_mark(it->mark, true);
			EraseCurrent = false;
			break;
		case ParseResultItemType_FormatEnd:
		{
			// find paired ParseResultItemType_FormatBeg item
			std::list<ParseResultItemWithMark>::reverse_iterator it2(it);
			for(; it2 != delayed_insert_list.rend(); ++it2)
				if(it2->item->type == ParseResultItemType_FormatBeg)
					break;
			if(it2 != delayed_insert_list.rend() && it2->item->format_beg->type 
				== it->item->format_end->type) {
				if(it->item->format_end->type == ParseResultItemFormatType_Indent)
					pango_view_->indent_region(it2->mark.c_str(), 0, it->mark.c_str());
				std::list<ParseResultItemWithMark>::iterator it3(it2.base());
				delayed_insert_list.erase(--it3);
			} else
				g_warning("Not paired ParseResultItemType_FormatEnd item");
			break;
		}
		default:
			g_assert_not_reached();
			break;
		}
		if(EraseCurrent)
			it = delayed_insert_list.erase(it);
		else
			++it;
	}
	// remove tmp chars
	for(std::list<std::string>::iterator it = tmp_char_mark_list.begin(); 
		it != tmp_char_mark_list.end(); ++it) {
#ifdef DDEBUG
		std::cout << "tmp char mark " << *it << std::endl;
#endif
		pango_view_->delete_text(it->c_str(), 1, 0);
	}
	pango_view_->reindent();
	if(!delayed_insert_list.empty())
		g_warning("delayed_insert_list is not empty. "
			"parse_result contains not paired items.");
}
示例#26
0
void ImageProvider::onNewObservation(Observ &obs) 
{
  //TODO write observation
  Value item(TypeLibrary::getType(TID_INT64));
  //DEBUG
  //Coordinates pos = _oidCItr->getPosition();
  PixVect pixels = obs.pixels;
  CoordVect polygons = obs.polygons;

  item.setInt64(obs.observId);
  Value item2(TypeLibrary::getType(TID_BOOL));
  item2.setBool(true);
 
  Coordinates pos(3);
  pos[zIdx] = _imageId;
  for(vector<PixVal>::iterator pixel = pixels.begin(); pixel != pixels.end(); ++pixel) 
  {
    pos[yIdx] = pixel->coord.second;
    pos[xIdx] = pixel->coord.first;
    //cout << pos[0] << "," << pos[1] << "," << pos[2] << endl; flush(cout);
    // Mark the point oid
    setOutputPosition(_oidIterator,_oidCItr,pos);
    //cout << "position was set" << endl; flush(cout);
    _oidCItr->writeItem(item);
    // Write out all the Points related to the observation
    setOutputPosition(_pointIterator,_pointCItr, pos);
    _pointCItr->writeItem(item2);
  }   
  //cout << " wrote the points " << endl; flush(cout);
  // Now move to the center
  pos[yIdx] = obs.centroidY;
  pos[xIdx] = obs.centroidX;
   
  // mark the center's oid
  setOutputPosition(_oidIterator, _oidCItr, pos);
  _oidCItr->writeItem(item);
  
  // center
  setOutputPosition(_centerIterator, _centerCItr, pos);
  _centerCItr->writeItem(item2);
 
  // sumpix
  Value item4(TypeLibrary::getType(TID_INT64));
  item4.setInt64(obs.pixelSum);
  setOutputPosition(_sumpixIterator, _sumpixCItr, pos);
  _sumpixCItr->writeItem(item4);

  // Avg Distributtion
  Value item5(TypeLibrary::getType(TID_DOUBLE));
  item5.setDouble(obs.averageDist);
  setOutputPosition(_avgdistIterator, _avgdistCItr, pos);
  _avgdistCItr->writeItem(item5);

  // Polygon's point
  // Oid is marked already
  Value item6(TypeLibrary::getType(TID_INT32));
  int i=1;
  for (vector<pair<Idx,Idx> >::iterator polygon =polygons.begin();  polygon != polygons.end(); ++polygon) 
  {
    pos[yIdx] = polygon->second;
    pos[xIdx] = polygon->first;
    setOutputPosition(_polygonIterator, _polygonCItr, pos);
    item6.setInt32(i++);
    _polygonCItr->writeItem(item6);
  }
}