Beispiel #1
0
void CreateLobbyDialog::setShareList(const std::list<std::string>& friend_list)
{
    if (!rsPeers)
    {
            /* not ready yet! */
            return;
    }

    std::list<std::string> peers;
    std::list<std::string>::iterator it;

	 mShareList.clear() ;
    rsPeers->getFriendList(peers);

    /* get a link to the table */
    QTreeWidget *shareWidget = ui->keyShareList;

    QList<QTreeWidgetItem *> items;

    for(it = peers.begin(); it != peers.end(); it++)
	 {
		 RsPeerDetails detail;
		 if (!rsPeers->getPeerDetails(*it, detail))
		 {
			 continue; /* BAD */
		 }

		 /* make a widget per friend */
		 QTreeWidgetItem *item = new QTreeWidgetItem((QTreeWidget*)0);

		 item -> setText(0, PeerDefs::nameWithLocation(detail));
		 if (detail.state & RS_PEER_STATE_CONNECTED) {
			 item -> setTextColor(0,(Qt::darkBlue));
		 }
		 item -> setSizeHint(0,  QSize( 17,17 ) );
		 item -> setText(1, QString::fromStdString(detail.id));
		 item -> setFlags(Qt::ItemIsUserCheckable | Qt::ItemIsEnabled);

		 item -> setCheckState(0, Qt::Unchecked);

		 for(std::list<std::string>::const_iterator it2(friend_list.begin());it2!=friend_list.end();++it2)
			 if(*it == *it2)
			 {
				 item -> setCheckState(0, Qt::Checked);
				 mShareList.push_back(*it) ;
				 break ;
			 }

		 /* add to the list */
		 items.append(item);
	 }

    /* remove old items */
    shareWidget->clear();
    shareWidget->setColumnCount(1);

    /* add the items in! */
    shareWidget->insertTopLevelItems(0, items);

    shareWidget->update(); /* update display */
}
Beispiel #2
0
void test_iterators(test_harness& t, sam::alignment& aln) {
    sam::alignment::iterator it;
    it = aln.begin();
    sam::alignment::iterator it1 = it;
    sam::alignment::iterator it2(it);

    sam::alignment::const_iterator cit;
    cit = aln.begin();
    sam::alignment::const_iterator cit1 = cit;
    sam::alignment::const_iterator cit2(cit);

    t.check(it1 == it2, "iterator.==");
    t.check(!(it1 != it2), "iterator.!=");

    t.check(cit1 == cit2, "const_iterator.==");
    t.check(!(cit1 != cit2), "const_iterator.!=");

    t.check(it1 == cit2, "iterator__const_iterator.==");
    t.check(cit1 == it2, "const_iterator__iterator.==");
    t.check(!(it1 != cit2), "iterator__const_iterator.!=");
    t.check(!(cit1 != it2), "const_iterator__iterator.!=");

    std::cout << "begin: " << aln.begin() << ", end: " << aln.end() << "\n";

    std::string foo = "foo";
    int bar = 37;

    aln.dump_on(std::cout);
    std::cout << aln << "\npush_back.X1\n";
    aln.push_back("X1", foo);
    aln.dump_on(std::cout, aln.find("X1"));
    std::cout << aln << "\npush_back.X2\n";
    aln.push_back("X2", bar);
    //aln.push_back("X3", cit2);

    aln.dump_on(std::cout);
    std::cout << aln << "\ninsert.Y1\n";
    aln.insert(aln.begin(), "Y1", foo);
    aln.dump_on(std::cout, aln.begin());
    std::cout << aln << "\ninsert.Y2\n";
    aln.insert(aln.begin(), "Y2", bar);
    //aln.insert(aln.begin(), "Y3", cit2);

    //aln.replace(aln.begin(), aln.end(), "Y3", it2);

    aln.dump_on(std::cout);
    std::cout << aln << "\nset_aux.Z1\n";
    aln.set_aux("Z1", foo);
    aln.dump_on(std::cout);
    std::cout << aln << "\nset_aux.Z2\n";
    aln.set_aux("Z2", bar);
    aln.dump_on(std::cout);
    std::cout << aln << "\nset_aux.Z3\n";
    sam::alignment aln2 = aln;
    cit2 = aln2.find("X1");
    aln.set_aux("Z3", cit2);

    std::cout << "begin: " << aln.begin() << ", end: " << aln.end() << "\nauxen:";
    for (cit = aln.begin(); cit != aln.end(); ++cit)
        std::cout << " {" << *cit << "}";
    std::cout << "\n";

    it1 = aln.begin(), ++it1, ++it1;
    aln.dump_on(std::cout, it1);
    std::cout << aln << "\nset_aux.it1\n";
    aln.set_aux(it1, foo);
    aln.dump_on(std::cout, it1);
    std::cout << aln << "\nset_aux.it1\n";
    aln.set_aux(it1, bar);
    //aln.set_aux(it1, cit2);

    it = aln.begin();
    std::cout << "And finally...\n";
    aln.dump_on(std::cout, it);
    std::cout << "pre:  it: " << it << "\n";
    it++;
    std::cout << "post: it: " << it << "\n";
    aln.dump_on(std::cout, it);
    std::cout << "End of test_iterators()\n";
}
Beispiel #3
0
void output_special_tag(Context& ctx, std::string *out, const TreeNode& tag) {
	if (tag.mName == "lina:fireball") {
		const TreeAttribute *a1 = tag.Attrib("src");
		const TreeAttribute *a2 = tag.Attrib("dst");

		if (!a1 || !a2)
			error(ctx, "<lina:fireball> requires SRC and DST attributes");

		g_fileCopies[a2->mValue] = a1->mValue;
	} else if (tag.mName == "lina:write") {
		const TreeAttribute *a = tag.Attrib("file");

		if (!a)
			error(ctx, "<lina:write> must specify FILE");

		std::string s;

		std::list<TreeNode *> tempStack;
		ctx.construction_stack.swap(tempStack);
		int cdataCount = ctx.cdata_count;
		int preCount = ctx.pre_count;
		ctx.cdata_count = 0;
		ctx.pre_count = 0;
		bool bHoldingSpace = ctx.holding_space;
		bool bEatNextSpace = ctx.eat_next_space;
		ctx.holding_space = false;
		ctx.eat_next_space = true;
		output_tag_contents(ctx, &s, tag);
		ctx.holding_space = bHoldingSpace;
		ctx.eat_next_space = bEatNextSpace;
		ctx.pre_count = cdataCount;
		ctx.cdata_count = preCount;
		ctx.construction_stack.swap(tempStack);

		std::string filename(create_output_filename(a->mValue));

		FILE *f = fopen(filename.c_str(), "wb");
		if (!f)
			error(ctx, "couldn't create \"%s\"", a->mValue.c_str());
		fwrite(s.data(), s.length(), 1, f);
		fclose(f);

		printf("created file: %s\n", a->mValue.c_str());
	} else if (tag.mName == "lina:body") {

//		printf("outputting:\n");
//		dump_parse_tree(*ctx.invocation_stack.back(), 4);

		output_tag_contents(ctx, out, *ctx.invocation_stack.back());
	} else if (tag.mName == "lina:tag") {
		const TreeAttribute *a = tag.Attrib("name");
		if (!a)
			error(ctx, "<lina:tag> must have NAME attribute");

		ctx.construction_stack.push_back(ctx.mpDocument->AllocNode());
		TreeNode *new_tag = ctx.construction_stack.back();

		new_tag->mpLocation = tag.mpLocation;
		new_tag->mLineno = tag.mLineno;
		new_tag->mName = a->mValue;
		new_tag->mbIsText = false;
		new_tag->mbIsControl = false;

		// compatibility
		if (!new_tag->mName.compare(0, 2, "w:"))
			new_tag->mName.replace(0, 2, "lina:");

		output_tag_contents(ctx, NULL, tag);

		ctx.construction_stack.pop_back();
		output_tag(ctx, out, *new_tag);
	} else if (tag.mName == "lina:arg") {
		if (!out && ctx.construction_stack.empty())
			error(ctx, "<lina:arg> can only be used in an output context");
		const TreeAttribute *a = tag.Attrib("name");
		if (!a)
			error(ctx, "<lina:arg> must have NAME attribute");

		if (ctx.invocation_stack.empty())
			error(ctx, "<lina:arg> can only be used during macro expansion");

		std::list<const TreeNode *>::const_iterator it(ctx.invocation_stack.end());
		--it;

		int levels = 1;
		const char *name = a->mValue.c_str();
		while(*name == '^') {
			++levels;
			++name;

			if (it == ctx.invocation_stack.begin())
				error(ctx, "Number of up-scope markers in name exceeds macro nesting level");

			--it;
		}

		const TreeNode& macrotag = **it;
		const TreeAttribute *a2 = macrotag.Attrib(name);
		if (!a2)
			error(ctx, "macro invocation <%s> does not have an attribute \"%s\"", macrotag.mName.c_str(), name);

		if (out) {
			*out += a2->mValue;

			ctx.eat_next_space = false;
			ctx.holding_space = false;
		} else {
			TreeNode *t = ctx.mpDocument->AllocNode();

			t->mpLocation = tag.mpLocation;
			t->mLineno = tag.mLineno;
			t->mbIsControl = false;
			t->mbIsText = true;
			t->mName = a2->mValue;

			ctx.construction_stack.back()->mChildren.push_back(t);
		}
	} else if (tag.mName == "lina:if-arg") {
		const TreeAttribute *a = tag.Attrib("name");
		if (!a)
			error(ctx, "<lina:if-arg> must have NAME attribute");

		if (ctx.invocation_stack.empty())
			error(ctx, "<lina:if-arg> can only be used during macro expansion");

		const TreeNode& macrotag = *ctx.invocation_stack.back();
		const TreeAttribute *a2 = macrotag.Attrib(a->mValue);
		if (a2)
			output_tag_contents(ctx, out, tag);
	} else if (tag.mName == "lina:if-not-arg") {
		const TreeAttribute *a = tag.Attrib("name");
		if (!a)
			error(ctx, "<lina:if-not-arg> must have NAME attribute");

		if (ctx.invocation_stack.empty())
			error(ctx, "<lina:if-not-arg> can only be used during macro expansion");

		const TreeNode& macrotag = *ctx.invocation_stack.back();
		const TreeAttribute *a2 = macrotag.Attrib(a->mValue);
		if (!a2)
			output_tag_contents(ctx, out, tag);
	} else if (tag.mName == "lina:attrib") {
		if (ctx.construction_stack.empty())
			error(ctx, "<lina:attrib> can only be used in a <lina:tag> element");

		const TreeAttribute *a = tag.Attrib("name");
		if (!a)
			error(ctx, "<lina:attrib> must have NAME attribute");

		std::string s;
		std::list<TreeNode *> tempStack;
		ctx.construction_stack.swap(tempStack);
		++ctx.cdata_count;
		++ctx.pre_count;
		bool bHoldingSpace = ctx.holding_space;
		bool bEatNextSpace = ctx.eat_next_space;
		ctx.holding_space = false;
		ctx.eat_next_space = true;
		output_tag_contents(ctx, &s, tag);
		ctx.holding_space = bHoldingSpace;
		ctx.eat_next_space = bEatNextSpace;
		--ctx.pre_count;
		--ctx.cdata_count;
		ctx.construction_stack.swap(tempStack);

		TreeNode *t = ctx.construction_stack.back();
		TreeAttribute new_att;
		if (tag.Attrib("novalue")) {
			new_att.mbNoValue = true;
		} else {
			new_att.mbNoValue = false;
			new_att.mValue = s;
		}
		new_att.mName = a->mValue;
		t->mAttribs.push_back(new_att);
	} else if (tag.mName == "lina:pull") {
		if (ctx.invocation_stack.empty())
			error(ctx, "<lina:pull> can only be used during macro expansion");

		const TreeAttribute *a = tag.Attrib("name");
		if (!a)
			error(ctx, "<lina:pull> must have NAME attribute");

		const TreeNode *t = ctx.find_tag(a->mValue);
		
		if (!t)
			error(ctx, "cannot find tag <%s> referenced in <lina:pull>", a->mValue.c_str());

		output_tag_contents(ctx, out, *t);		
	} else if (tag.mName == "lina:for-each") {
		const TreeAttribute *a = tag.Attrib("name");
		if (!a)
			error(ctx, "<lina:for-each> must have NAME attribute");
		
		std::string node_name;
		const TreeNode *parent;
		if (ctx.invocation_stack.empty()) {
			if (!a->mValue.empty() && a->mValue[0] == '/')
				parent = ctx.mpDocument->mpRoot->ResolvePath(a->mValue.substr(1), node_name);
			else
				error(ctx, "path must be absolute if not in macro context");
		} else {
			std::list<const TreeNode *>::reverse_iterator it(ctx.invocation_stack.rbegin()), itEnd(ctx.invocation_stack.rend());
			
			for(; it!=itEnd; ++it) {
				parent = (*it)->ResolvePath(a->mValue, node_name);
				if(parent)
					break;
				if (!a->mValue.empty() && a->mValue[0] == '/')
					break;
			}
		}

		if (!parent)
			error(ctx, "cannot resolve path \"%s\"", a->mValue.c_str());

		std::list<TreeNode *>::const_iterator it2(parent->mChildren.begin()), it2End(parent->mChildren.end());

		ctx.invocation_stack.push_back(NULL);
		for(; it2!=it2End; ++it2) {
			if ((*it2)->mName == node_name) {
				ctx.invocation_stack.back() = *it2;
				output_tag_contents(ctx, out, tag);
			}
		}
		ctx.invocation_stack.pop_back();
	} else if (tag.mName == "lina:apply") {
		const TreeAttribute *a = tag.Attrib("name");
		if (!a)
			error(ctx, "<lina:apply> must have NAME attribute");

		std::map<std::string, TreeNode *>::const_iterator it(ctx.mpDocument->mMacros.find(a->mValue));

		if (it == ctx.mpDocument->mMacros.end())
			error(ctx, "macro \"%s\" undeclared", a->mValue.c_str());
		
		std::list<TreeNode *>::const_iterator it2(tag.mChildren.begin()), it2End(tag.mChildren.end());

		ctx.invocation_stack.push_back(NULL);
		for(; it2!=it2End; ++it2) {
			if (!(*it2)->mbIsText) {
				ctx.invocation_stack.back() = *it2;
				output_tag_contents(ctx, out, *(*it).second);
			}
		}
		ctx.invocation_stack.pop_back();
	} else if (tag.mName == "lina:if-present") {
		if (ctx.invocation_stack.empty())
			error(ctx, "<lina:if-present> can only be used during macro expansion");
		const TreeAttribute *a = tag.Attrib("name");
		if (!a)
			error(ctx, "<lina:if-present> must have NAME attribute");

		const TreeNode *t = ctx.find_tag(a->mValue);
		if (t)
			output_tag_contents(ctx, out, tag);
	} else if (tag.mName == "lina:if-not-present") {
		if (ctx.invocation_stack.empty())
			error(ctx, "<lina:if-not-present> can only be used during macro expansion");
		const TreeAttribute *a = tag.Attrib("name");
		if (!a)
			error(ctx, "<lina:if-not-present> must have NAME attribute");

		const TreeNode *t = ctx.find_tag(a->mValue);
		if (!t)
			output_tag_contents(ctx, out, tag);
	} else if (tag.mName == "lina:pre") {
		++ctx.pre_count;
		++ctx.cdata_count;
		if (!out)
			output_standard_tag(ctx, out, tag);
		else {
			output_tag_contents(ctx, out, tag);
		}
		--ctx.cdata_count;
		--ctx.pre_count;
	} else if (tag.mName == "lina:cdata") {
		++ctx.cdata_count;
		if (!out)
			output_standard_tag(ctx, out, tag);
		else
			output_tag_contents(ctx, out, tag);
		--ctx.cdata_count;
	} else if (tag.mName == "lina:delay") {
		std::list<TreeNode *>::const_iterator it(tag.mChildren.begin()), itEnd(tag.mChildren.end());
		for(; it!=itEnd; ++it) {
			output_standard_tag(ctx, out, **it);
		}
	} else if (tag.mName == "lina:dump-stack") {
		dump_stack(ctx);
	} else if (tag.mName == "lina:replace") {
		const TreeAttribute *a = tag.Attrib("from");
		if (!a || a->mbNoValue)
			error(ctx, "<lina:replace> must have FROM attribute");
		const TreeAttribute *a2 = tag.Attrib("to");
		if (!a2 || a2->mbNoValue)
			error(ctx, "<lina:replace> must have TO attribute");

		const std::string& x = a->mValue;
		const std::string& y = a2->mValue;

		std::string s, t;
		std::string::size_type i = 0;

		output_tag_contents(ctx, &s, tag);

		for(;;) {
			std::string::size_type j = s.find(x, i);
			if (j != i)
				t.append(s, i, j-i);
			if (j == std::string::npos)
				break;
			t.append(y);
			i = j + x.size();
		}

		TreeNode *new_tag = ctx.mpDocument->AllocNode();

		new_tag->mpLocation = tag.mpLocation;
		new_tag->mLineno = tag.mLineno;
		new_tag->mbIsText = true;
		new_tag->mbIsControl = false;
		new_tag->mName = t;

		output_tag(ctx, out, *new_tag);
	} else if (tag.mName == "lina:set-option") {
		const TreeAttribute *a_name = tag.Attrib("name");
		if (!a_name)
			error(ctx, "<lina:set-option> must have NAME attribute");

		if (a_name->mValue == "link-truncate") {
			const TreeAttribute *a_val = tag.Attrib("baseurl");
			if (!a_val || a_val->mbNoValue)
				error(ctx, "option \"link-truncate\" requires BASEURL attribute");

			bool bTruncate = !tag.Attrib("notruncate");

			g_truncateURLs.push_back(std::make_pair(a_val->mValue, bTruncate));
		} else if (a_name->mValue == "output-dir") {
			const TreeAttribute *a_val = tag.Attrib("target");
			if (!a_val || a_val->mbNoValue)
				error(ctx, "option \"output-dir\" requires TARGET attribute");

			g_outputDir = a_val->mValue;
		} else if (a_name->mValue == "tag-info") {
			const TreeAttribute *a_tagname = tag.Attrib("tag");
			if (!a_tagname || a_tagname->mbNoValue)
				error(ctx, "option \"tag-info\" requires TAG attribute");

			const TreeAttribute *a_cdata = tag.Attrib("cdata");

			if (!a_cdata || a_cdata->mbNoValue)
				error(ctx, "option \"tag-info\" requires CDATA attribute");

			TreeNode::SetSupportsCDATA(a_tagname->mValue, is_true(a_cdata->mValue));
		} else
			error(ctx, "option \"%s\" unknown\n", a_name->mValue.c_str());

	} else if (tag.mName == "lina:data") {
		// do nothing
	} else if (tag.mName == "lina:source") {
		if (out) {
			std::list<TreeNode *>::const_iterator itBegin(tag.mChildren.begin()), it(itBegin), itEnd(tag.mChildren.end());
			for(; it!=itEnd; ++it) {
				output_source_tags(ctx, out, **it);
			}
		}
	} else if (tag.mName == "lina:htmlhelp-toc") {
		const TreeAttribute *a_val = tag.Attrib("file");
		if (!a_val || a_val->mbNoValue)
			error(ctx, "<lina:htmlhelp-toc> requires FILE attribute");

		const std::string filename(create_output_filename(a_val->mValue));

		// build new tag with TOC contents
		ctx.construction_stack.push_back(ctx.mpDocument->AllocNode());
		TreeNode *new_tag = ctx.construction_stack.back();

		new_tag->mpLocation = tag.mpLocation;
		new_tag->mLineno = tag.mLineno;
		new_tag->mName = a_val->mValue;
		new_tag->mbIsText = false;
		new_tag->mbIsControl = false;

		output_tag_contents(ctx, NULL, tag);

		ctx.construction_stack.pop_back();
		output_tag(ctx, out, *new_tag);

		FILE *f = fopen(filename.c_str(), "wb");
		if (!f)
			error(ctx, "couldn't create htmlhelp toc \"%s\"", a_val->mValue.c_str());
		output_toc(f, *new_tag);
		fclose(f);

	} else if (tag.mName == "lina:htmlhelp-project") {
		const TreeAttribute *file_val = tag.Attrib("file");
		if (!file_val || file_val->mbNoValue)
			error(ctx, "<lina:htmlhelp-project> requires FILE attribute");

		const TreeAttribute *output_val = tag.Attrib("output");
		if (!output_val || output_val->mbNoValue)
			error(ctx, "<lina:htmlhelp-project> requires OUTPUT attribute");

		const TreeAttribute *toc_val = tag.Attrib("toc");
		if (!toc_val || toc_val->mbNoValue)
			error(ctx, "<lina:htmlhelp-project> requires TOC attribute");

		const TreeAttribute *title_val = tag.Attrib("title");
		if (!title_val || title_val->mbNoValue)
			error(ctx, "<lina:htmlhelp-project> requires TITLE attribute");

		const std::string filename(create_output_filename(file_val->mValue));

		FILE *f = fopen(filename.c_str(), "wb");
		if (!f)
			error(ctx, "couldn't create htmlhelp project \"%s\"", file_val->mValue.c_str());
		fprintf(f,
			"[OPTIONS]\n"
			"Auto Index=Yes\n"
			"Compatibility=1.1 or later\n"
			"Compiled file=%s\n"
			"Contents file=%s\n"
			"Default topic=index.html\n"
			"Display compile progress=no\n"
			"Full-text search=Yes\n"
			, output_val->mValue.c_str()
			, toc_val->mValue.c_str()
			);


		const TreeAttribute *fullstop_val = tag.Attrib("fullstop");
		if (fullstop_val && !fullstop_val->mbNoValue)
			fprintf(f, "Full text search stop list file=%s\n", fullstop_val->mValue.c_str());

		fprintf(f,
			"Language=0x0409 English (United States)\n"
			"Title=%s\n"
			"\n"
			"[FILES]\n"
			, title_val->mValue.c_str()
			);

		std::list<std::string>::const_iterator it(g_htmlHelpFiles.begin()), itEnd(g_htmlHelpFiles.end());
		for(; it!=itEnd; ++it) {
			fprintf(f, "%s\n", (*it).c_str());
		}

		fclose(f);		
	} else if (tag.mName == "lina:htmlhelp-addfile") {
		const TreeAttribute *file_val = tag.Attrib("file");
		if (!file_val || file_val->mbNoValue)
			error(ctx, "<lina:htmlhelp-addfile> requires FILE attribute");

		g_htmlHelpFiles.push_back(file_val->mValue);
	} else {
		std::string macroName(tag.mName, 5, std::string::npos);
		std::map<std::string, TreeNode *>::const_iterator it = ctx.mpDocument->mMacros.find(macroName);

		if (it == ctx.mpDocument->mMacros.end())
			error(ctx, "macro <lina:%s> not found", macroName.c_str());

//		dump_stack(ctx);
//		printf("executing macro: %s (%s:%d)\n", tag.mName.c_str(), tag.mLocation->name.c_str(), tag.mLineno);

		ctx.invocation_stack.push_back(&tag);
		output_tag_contents(ctx, out, *(*it).second);
		ctx.invocation_stack.pop_back();

//		printf("exiting macro: %s (%s:%d)\n", tag.mName.c_str(), tag.mLocation->name.c_str(), tag.mLineno);
	}
}
Beispiel #4
0
void Plot::setHighLow ()
{
  _plotSettings.high = 0;
  _plotSettings.low = 0;
  bool flag = false;

  QHashIterator<QString, Curve *> it(_plotSettings.curves);
  while (it.hasNext())
  {
    it.next();
    Curve *curve = it.value();
    double h, l;
    if (! curve->highLowRange(_plotSettings.startPos, _plotSettings.endPos, h, l))
      continue;

    if (! flag)
    {
      _plotSettings.high = h;
      _plotSettings.low = l;
      flag = true;
    }
    else
    {
      if (h > _plotSettings.high)
        _plotSettings.high = h;

      if (l < _plotSettings.low)
        _plotSettings.low = l;
    }
  }

  QHashIterator<QString, Marker *> it2(_plotSettings.markers);
  while (it2.hasNext())
  {
    it2.next();
    Marker *co = it2.value();
    
    double h, l;
    if (! co->highLow(_plotSettings.startPos, _plotSettings.endPos, h, l))
      continue;

    if (! flag)
    {
      _plotSettings.high = h;
      _plotSettings.low = l;
      flag = true;
    }
    else
    {
      if (h > _plotSettings.high)
        _plotSettings.high = h;

      if (l < _plotSettings.low)
        _plotSettings.low = l;
    }
  }
  if(high)
  {
    //Add 2% margin at top and bottom of plot
    float span = high-low;
    float margin = span / 50;
    setAxisScale(QwtPlot::yRight, low-margin, high+margin);
  }
  else
  {
    float span = _plotSettings.high-_plotSettings.low;
    float margin = span / 50;
    setAxisScale(QwtPlot::yRight, _plotSettings.low-margin, _plotSettings.high+margin);
 }
}
Beispiel #5
0
void tst_QFuture::iterators()
{
    {
        QFutureInterface<int> e;
        e.reportStarted();
        QFuture<int> f = e.future();

        int result;
        result = 1;
        e.reportResult(&result);
        result = 2;
        e.reportResult(&result);
        result = 3;
        e.reportResult(&result);
        e.reportFinished();

        QList<int> results;
        QFutureIterator<int> i(f);
        while (i.hasNext()) {
            results.append(i.next());
        }

        QCOMPARE(results, f.results());

        QFuture<int>::const_iterator i1 = f.begin(), i2 = i1 + 1;
        QFuture<int>::const_iterator c1 = i1, c2 = c1 + 1;

        QVERIFY(i1 == i1);
        QVERIFY(i1 == c1);
        QVERIFY(c1 == i1);
        QVERIFY(c1 == c1);
        QVERIFY(i2 == i2);
        QVERIFY(i2 == c2);
        QVERIFY(c2 == i2);
        QVERIFY(c2 == c2);

        QVERIFY(i1 != i2);
        QVERIFY(i1 != c2);
        QVERIFY(c1 != i2);
        QVERIFY(c1 != c2);
        QVERIFY(i2 != i1);
        QVERIFY(i2 != c1);
        QVERIFY(c2 != i1);
        QVERIFY(c2 != c1);

        int x1 = *i1;
        Q_UNUSED(x1);
        int x2 = *i2;
        Q_UNUSED(x2);
        int y1 = *c1;
        Q_UNUSED(y1);
        int y2 = *c2;
        Q_UNUSED(y2);
    }

    {
        QFutureInterface<QString> e;
        e.reportStarted();
        QFuture<QString> f =  e.future();

        e.reportResult(QString("one"));
        e.reportResult(QString("two"));
        e.reportResult(QString("three"));
        e.reportFinished();

        QList<QString> results;
        QFutureIterator<QString> i(f);
        while (i.hasNext()) {
            results.append(i.next());
        }

        QCOMPARE(results, f.results());

        QFuture<QString>::const_iterator i1 = f.begin(), i2 = i1 + 1;
        QFuture<QString>::const_iterator c1 = i1, c2 = c1 + 1;

        QVERIFY(i1 == i1);
        QVERIFY(i1 == c1);
        QVERIFY(c1 == i1);
        QVERIFY(c1 == c1);
        QVERIFY(i2 == i2);
        QVERIFY(i2 == c2);
        QVERIFY(c2 == i2);
        QVERIFY(c2 == c2);

        QVERIFY(i1 != i2);
        QVERIFY(i1 != c2);
        QVERIFY(c1 != i2);
        QVERIFY(c1 != c2);
        QVERIFY(i2 != i1);
        QVERIFY(i2 != c1);
        QVERIFY(c2 != i1);
        QVERIFY(c2 != c1);

        QString x1 = *i1;
        QString x2 = *i2;
        QString y1 = *c1;
        QString y2 = *c2;

        QCOMPARE(x1, y1);
        QCOMPARE(x2, y2);

        int i1Size = i1->size();
        int i2Size = i2->size();
        int c1Size = c1->size();
        int c2Size = c2->size();

        QCOMPARE(i1Size, c1Size);
        QCOMPARE(i2Size, c2Size);
    }

    {
        const int resultCount = 20;

        QFutureInterface<int> e;
        e.reportStarted();
        QFuture<int> f =  e.future();

        for (int i = 0; i < resultCount; ++i) {
            e.reportResult(i);
        }
    
        e.reportFinished();
    
        {
            QFutureIterator<int> it(f);
            QFutureIterator<int> it2(it);
        }

        {
            QFutureIterator<int> it(f);
    
            for (int i = 0; i < resultCount - 1; ++i) {
                QVERIFY(it.hasNext());
                QCOMPARE(it.peekNext(), i);
                QCOMPARE(it.next(), i);
            }

            QVERIFY(it.hasNext());
            QCOMPARE(it.peekNext(), resultCount - 1);
            QCOMPARE(it.next(), resultCount - 1);
            QVERIFY(it.hasNext() == false);
        }

        {
            QFutureIterator<int> it(f);
            QVERIFY(it.hasNext());
            it.toBack();
            QVERIFY(it.hasNext() == false);
            it.toFront();
            QVERIFY(it.hasNext());
        }
    }
}
void ConnectFriendWizard::updatePeersList(int index)
{

	ui->selectedPeersTW->clearContents();
	ui->selectedPeersTW->setRowCount(0);

	RsPgpId ownId = rsPeers->getGPGOwnId();

	int row = 0;

	_id_boxes.clear();

	// We have to use this trick because signers are given by their names instead of their ids. That's a cause
	// for some confusion when two peers have the same name.
	//
	std::list<RsPgpId> gpg_ids;
	rsPeers->getGPGAllList(gpg_ids);
	for (std::list<RsPgpId>::const_iterator it(gpg_ids.begin()); it != gpg_ids.end(); ++it) {
		if (*it == ownId) {
			// its me
			continue;
		}

#ifdef FRIEND_WIZARD_DEBUG
		std::cerr << "examining peer " << *it << " (name=" << rsPeers->getPeerName(*it);
#endif

		RsPeerDetails details ;
		if (!rsPeers->getGPGDetails(*it,details)) {
#ifdef FRIEND_WIZARD_DEBUG
			std::cerr << " no details." << std::endl ;
#endif
			continue;
		}

		// determine common friends

		std::list<RsPgpId> common_friends;

		for (std::list<RsPgpId>::const_iterator it2(details.gpgSigners.begin()); it2 != details.gpgSigners.end(); ++it2) {
			if(rsPeers->isGPGAccepted(*it2)) {
				common_friends.push_back(*it2);
			}
		}
		bool show = false;

		switch(index) {
		case 0: // "All unsigned friends of my friends"
			show = !details.ownsign;
#ifdef FRIEND_WIZARD_DEBUG
			std::cerr << "case 0: ownsign=" << details.ownsign << ", show=" << show << std::endl;
#endif
			break ;
		case 1: // "Unsigned peers who already signed my certificate"
			show = details.hasSignedMe && !(details.state & RS_PEER_STATE_FRIEND);
#ifdef FRIEND_WIZARD_DEBUG
			std::cerr << "case 1, ownsign=" << details.ownsign << ", is_authed_me=" << details.hasSignedMe << ", show=" << show << std::endl;
#endif
			break ;
		case 2: // "Peers shown as denied"
			show = details.ownsign && !(details.state & RS_PEER_STATE_FRIEND);
#ifdef FRIEND_WIZARD_DEBUG
			std::cerr << "case 2, ownsign=" << details.ownsign << ", state_friend=" << (details.state & RS_PEER_STATE_FRIEND) << ", show=" << show << std::endl;
#endif
			break ;
		}

		if (show) {
			ui->selectedPeersTW->insertRow(row);

			QCheckBox *cb = new QCheckBox;
			cb->setChecked(true);
			_id_boxes[cb] = details.id;
			_gpg_id_boxes[cb] = details.gpg_id;

			ui->selectedPeersTW->setCellWidget(row, 0, cb);
			ui->selectedPeersTW->setItem(row, 1, new QTableWidgetItem(QString::fromUtf8(details.name.c_str())));

			QComboBox *qcb = new QComboBox;

			if (common_friends.empty()) {
				qcb->addItem(tr("*** None ***"));
			} else {
				for (std::list<RsPgpId>::const_iterator it2(common_friends.begin()); it2 != common_friends.end(); ++it2) {
					qcb->addItem(QString::fromStdString( (*it2).toStdString()));
				}
			}

			ui->selectedPeersTW->setCellWidget(row, 2, qcb);
			ui->selectedPeersTW->setItem(row, 3, new QTableWidgetItem(QString::fromStdString(details.id.toStdString())));
			++row;
		}
	}
#ifdef FRIEND_WIZARD_DEBUG
	std::cerr << "FofPage::updatePeersList() finished iterating over peers" << std::endl;
#endif

	if (row>0) {
		ui->selectedPeersTW->resizeColumnsToContents();
		ui->makeFriendButton->setEnabled(true);
	} else {
		ui->makeFriendButton->setEnabled(false);
	}
}
Beispiel #7
0
/* Get antenna phase center variation.
 *
 * This method returns a Triple, in UEN system, with the
 * elevation and azimuth-dependent phase center variation.
 *
 * @param[in] freq      Frequency
 * @param[in] elevation Elevation (degrees)
 * @param[in] azimuth   Azimuth (degrees)
 *
 * @warning The phase center variation Triple is in UEN system.
 */
Triple Antenna::getAntennaPCVariation( frequencyType freq,
                                       double elevation,
                                       double azimuth ) const
throw(InvalidRequest)
{

    // The angle should be measured respect to zenith
    double angle( 90.0 - elevation );

    // Check that angle is within limits
    if( ( angle < zen1 ) ||
            ( angle > zen2 ) )
    {
        InvalidRequest e("Elevation is out of allowed range.");
        GPSTK_THROW(e);
    }

    // Reduce azimuth to 0 <= azimuth < 360 interval
    while( azimuth < 0.0 )
    {
        azimuth += 360.0;
    }
    while( azimuth >= 360.0 )
    {
        azimuth -= 360.0;
    }

    // Look for this frequency in pcMap
    // Define iterator
    PCDataMap::const_iterator it( pcMap.find(freq) );
    if( it != pcMap.end() )
    {

        // Get the right azimuth interval
        const double lowerAzimuth( std::floor(azimuth/dazi) * dazi );
        const double upperAzimuth( lowerAzimuth + dazi );

        // Look for data vectors
        AzimuthDataMap::const_iterator it2( (*it).second.find(lowerAzimuth) );
        AzimuthDataMap::const_iterator it3( (*it).second.find(upperAzimuth) );

        // Find the fraction from 'lowerAzimuth'
        const double fractionalAzimuth( ( azimuth - lowerAzimuth ) /
                                        ( upperAzimuth - lowerAzimuth ) );

        // Check if 'azimuth' exactly corresponds to a value in the map
        if( fractionalAzimuth == 0.0 )
        {
            // Check if there is data for 'lowerAzimuth'
            if( it2 != (*it).second.end() )
            {
                // Get the normalized angle
                const double normalizedAngle( (angle-zen1)/dzen );

                // Return result. Only the "Up" component is important.
                Triple result( linearInterpol( (*it2).second, normalizedAngle ),
                               0.0,
                               0.0 );

                return result;

            }
            else
            {
                InvalidRequest e("No data was found for this azimuth.");
                GPSTK_THROW(e);
            }
        }
        else
        {
            // We have to interpolate
            // Check if there is data for 'lowerAzimuth' and 'upperAzimuth'
            if( it2 != (*it).second.end() &&
                    it3 != (*it).second.end() )
            {
                // Get the normalized angle
                const double normalizedAngle( (angle-zen1)/dzen );

                // Find values corresponding to both azimuths
                double val1( linearInterpol( (*it2).second, normalizedAngle ) );
                double val2( linearInterpol( (*it3).second, normalizedAngle ) );

                // Return result. Only the "Up" component is important.
                Triple result( ( val1 + (val2-val1) * fractionalAzimuth ),
                               0.0,
                               0.0 );

                return result;

            }
            else
            {
                InvalidRequest e("Not enough data was found for this azimuth.");
                GPSTK_THROW(e);
            }
        }

    }
    else
    {

        InvalidRequest e("No data was found for this frequency.");
        GPSTK_THROW(e);

    }  // End of 'if( it != pcMap.end() )...'

}  // End of method 'Antenna::getAntennaPCVariation()'
std::vector<CHARRANGE> ProjectProperties::FindBugIDPositions(const CString& msg)
{
	size_t offset1 = 0;
	size_t offset2 = 0;
	std::vector<CHARRANGE> result;

	// first use the checkre string to find bug ID's in the message
	if (!sCheckRe.IsEmpty())
	{
		if (!sBugIDRe.IsEmpty())
		{

			// match with two regex strings (without grouping!)
			try
			{
				AutoUpdateRegex();
				const std::tr1::wsregex_iterator end;
				std::wstring s = msg;
				for (std::tr1::wsregex_iterator it(s.begin(), s.end(), regCheck); it != end; ++it)
				{
					// (*it)[0] is the matched string
					std::wstring matchedString = (*it)[0];
					ptrdiff_t matchpos = it->position(0);
					for (std::tr1::wsregex_iterator it2(matchedString.begin(), matchedString.end(), regBugID); it2 != end; ++it2)
					{
						ATLTRACE(_T("matched id : %s\n"), (*it2)[0].str().c_str());
						ptrdiff_t matchposID = it2->position(0);
						CHARRANGE range = {(LONG)(matchpos+matchposID), (LONG)(matchpos+matchposID+(*it2)[0].str().size())};
						result.push_back(range);
					}
				}
			}
			catch (std::exception) {}
		}
		else
		{
			try
			{
				AutoUpdateRegex();
				const std::tr1::wsregex_iterator end;
				std::wstring s = msg;
				for (std::tr1::wsregex_iterator it(s.begin(), s.end(), regCheck); it != end; ++it)
				{
					const std::tr1::wsmatch match = *it;
					// we define group 1 as the whole issue text and
					// group 2 as the bug ID
					if (match.size() >= 2)
					{
						ATLTRACE(_T("matched id : %s\n"), std::wstring(match[1]).c_str());
						CHARRANGE range = {(LONG)(match[1].first-s.begin()), (LONG)(match[1].second-s.begin())};
						result.push_back(range);
					}
				}
			}
			catch (std::exception) {}
		}
	}
	else if (result.empty() && (!sMessage.IsEmpty()))
	{
		CString sBugLine;
		CString sFirstPart;
		CString sLastPart;
		BOOL bTop = FALSE;
		if (nBugIdPos < 0)
			return result;

		sFirstPart = sMessage.Left(nBugIdPos);
		sLastPart = sMessage.Mid(nBugIdPos + 7);
		CString sMsg = msg;
		sMsg.TrimRight('\n');
		if (sMsg.ReverseFind('\n')>=0)
		{
			if (bAppend)
				sBugLine = sMsg.Mid(sMsg.ReverseFind('\n')+1);
			else
			{
				sBugLine = sMsg.Left(sMsg.Find('\n'));
				bTop = TRUE;
			}
		}
		else
			sBugLine = sMsg;
		if (sBugLine.Left(sFirstPart.GetLength()).Compare(sFirstPart)!=0)
			sBugLine.Empty();
		if (sBugLine.Right(sLastPart.GetLength()).Compare(sLastPart)!=0)
			sBugLine.Empty();
		if (sBugLine.IsEmpty())
		{
			if (sMsg.Find('\n')>=0)
				sBugLine = sMsg.Left(sMsg.Find('\n'));
			if (sBugLine.Left(sFirstPart.GetLength()).Compare(sFirstPart)!=0)
				sBugLine.Empty();
			if (sBugLine.Right(sLastPart.GetLength()).Compare(sLastPart)!=0)
				sBugLine.Empty();
			bTop = TRUE;
		}
		if (sBugLine.IsEmpty())
			return result;

		CString sBugIDPart = sBugLine.Mid(sFirstPart.GetLength(), sBugLine.GetLength() - sFirstPart.GetLength() - sLastPart.GetLength());
		if (sBugIDPart.IsEmpty())
			return result;

		//the bug id part can contain several bug id's, separated by commas
		if (!bTop)
			offset1 = sMsg.GetLength() - sBugLine.GetLength() + sFirstPart.GetLength();
		else
			offset1 = sFirstPart.GetLength();
		sBugIDPart.Trim(_T(","));
		while (sBugIDPart.Find(',')>=0)
		{
			offset2 = offset1 + sBugIDPart.Find(',');
			CHARRANGE range = {(LONG)offset1, (LONG)offset2};
			result.push_back(range);
			sBugIDPart = sBugIDPart.Mid(sBugIDPart.Find(',')+1);
			offset1 = offset2 + 1;
		}
		offset2 = offset1 + sBugIDPart.GetLength();
		CHARRANGE range = {(LONG)offset1, (LONG)offset2};
		result.push_back(range);
	}

	return result;
}
Beispiel #9
0
/*!
 * \brief IPProcessGrid::execute
 */
void IPProcessGrid::execute(bool forcedUpdate /* = false*/)
{
    // if no processes yet, then exit
    if(_scene->steps()->size() < 1)
    {
        return;
    }

    // if already running or nothing has changed, exit
    if(_isRunning || !_updateNeeded)
    {
        return;
    }
    // prevent user changes during execution
    _mainWindow->lockScene();
    _isRunning = true;
    _sequenceCount = 0;

    buildQueue();

    int totalDurationMs = 0;

    // execute the processes
    int counter = 0;
    int limit = 10000;

    QList<IPProcessStep*> afterProcessingList;

    QListIterator<IPProcessStep *> it(_processList);
    while (it.hasNext() && counter < limit)
    {
        if(_stopExecution)
            return;

        IPProcessStep* step = it.next();
        _currentStep = step;

        // make sure the progress bar gets filled
        updateProgress(1);

        // source processes don't have inputs
        if(step->process()->isSource())
        {
            // check if is sequence
            //IPLLoadImageSequence* sequenceProcess = dynamic_cast<IPLLoadImageSequence*>(step->process());

            // update if index has changed
            /*if(sequenceProcess && (_sequenceIndex != _lastSequenceIndex))
            {
                sequenceProcess->setSequenceIndex(_sequenceIndex);
                propagateNeedsUpdate(sequenceProcess);
            }*/

            // execute thread
            if(!step->process()->isResultReady() || forcedUpdate)
            {
                step->process()->resetMessages();
                step->process()->beforeProcessing();
                int durationMs = executeThread(step->process());
                //step->process()->afterProcessing();

                // afterProcessing will be called later
                afterProcessingList.append(step);

                totalDurationMs += durationMs;
                step->setDuration(durationMs);

                if(!step->process()->hasErrors())
                    step->updateThumbnail();

                // update error messages
                _mainWindow->updateProcessMessages();
            }

            /*if(sequenceProcess)
            {
                int currentSequenceCount = sequenceProcess->sequenceCount();
                _sequenceCount = std::max(_sequenceCount, currentSequenceCount);
                emit sequenceChanged(_sequenceIndex, _sequenceCount);
            }*/
        }
        else
        {
            if(!step->process()->isResultReady() || forcedUpdate)
            {
                // execute process once for every input
                for(int i=0; i < step->edgesIn()->size(); i++)
                {
                    IPProcessEdge* edge = step->edgesIn()->at(i);
                    int indexFrom = edge->indexFrom();
                    int indexTo = edge->indexTo();
                    IPProcessStep* stepFrom = edge->from();

                    IPLImage* result = static_cast<IPLImage*>(stepFrom->process()->getResultData(indexFrom));

                    // invalid result, stopp the execution
                    if(!result)
                    {
                        QString msg("Invalid operation at step: ");
                        msg.append(QString::fromStdString(stepFrom->process()->title()));
                        _mainWindow->showMessage(msg, MainWindow::MESSAGE_ERROR);
                        break;
                    }

                    // execute thread
                    step->process()->resetMessages();
                    step->process()->beforeProcessing();
                    int durationMs = executeThread(step->process(), result, indexTo, mainWindow()->useOpenCV());
                    //step->process()->afterProcessing();

                    // afterProcessing will be called later
                    afterProcessingList.append(step);

                    totalDurationMs += durationMs;
                    step->setDuration(durationMs);

                    step->updateThumbnail();

                    // update error messages
                    _mainWindow->updateProcessMessages();
                }
            }
        }

        // make sure the progress bar gets filled
        updateProgress(100);

        counter++;
    }

    if(_stopExecution)
        return;

    // update images
    _mainWindow->imageViewer()->updateImage();
    _mainWindow->imageViewer()->showProcessDuration(totalDurationMs);


    // update process graph
    _mainWindow->updateGraphicsView();
    _mainWindow->unlockScene();

    _isRunning = false;
    _currentStep = NULL;

    // if sequence, then run execute next step
    /*if(_sequenceCount > 0)
    {
        // notify GUI
        emit sequenceChanged(_sequenceIndex, _sequenceCount);

        if(_isSequenceRunning)
        {
            //setParamsHaveChanged();
            _mainWindow->execute(true);
        }
    }

    // find sequence processes
    //bool graphNeedsUpdate = false;
    for(auto it = _scene->steps()->begin(); it < _scene->steps()->end(); ++it)
    {
        IPProcessStep* step = (IPProcessStep*) *it;
        IPLProcess* process = step->process();

        if(process->isSequence())
        {
            process->requestUpdate();
            propertyChanged(process);
            requestUpdate();
        }
    }*/

    //if(_updateID > _currentUpdateID)
    //    _mainWindow->execute(false);

    // only for testing the camera
    //if(graphNeedsUpdate)
    //    _mainWindow->execute(false);

    _updateNeeded = false;

    // call afterProcessing of all steps which were executed this time
    // processes like the camera might request another execution
    QListIterator<IPProcessStep *> it2(_processList);
    while (it2.hasNext())
    {
        IPProcessStep* step = it2.next();
        step->process()->afterProcessing();
    }
}
Beispiel #10
0
void
AutoStart::loadAutoStartList()
{
   TQStringList files = TDEGlobal::dirs()->findAllResources("xdgconf-autostart", "*.desktop", false, true);
   TQStringList kdefiles = TDEGlobal::dirs()->findAllResources("autostart", "*.desktop", false, true);
   files += kdefiles;
   
   for(TQStringList::ConstIterator it = files.begin();
       it != files.end();
       ++it)
   {
       KDesktopFile config(*it, true);
       if (config.hasKey("X-TDE-autostart-condition")) {
           if (!startCondition(config.readEntry("X-TDE-autostart-condition")))
              continue;
       }
       else {
           if (!startCondition(config.readEntry("X-TDE-autostart-condition")))
              continue;
       }
       if (!config.tryExec())
          continue;
       if (config.readBoolEntry("Hidden", false))
          continue;

       // Check to see if the most important ( usually ~/.config/autostart or ~/.trinity/Autostart) XDG directory
       // has overridden the Hidden directive and honor it if set to True
       bool autostartOverriddenAndDisabled = false;
       for(TQStringList::ConstIterator localit = files.begin();
           localit != files.end();
           ++localit)
       {
           if (((*localit).startsWith(TDEGlobal::dirs()->localxdgconfdir()) == true) || ((*localit).startsWith(TDEGlobal::dirs()->localtdedir()) == true)) {
               // Same local file name?
               TQString localOuter;
               TQString localInner;
               int slashPos = (*it).findRev( '/', -1, TRUE );
               if (slashPos == -1) {
                   localOuter = (*it);
               }
               else {
                   localOuter = (*it).mid(slashPos+1);
               }
               slashPos = (*localit).findRev( '/', -1, TRUE );
               if (slashPos == -1) {
                   localInner = (*localit);
               }
               else {
                   localInner = (*localit).mid(slashPos+1);
               }
               if (localOuter == localInner) {
                   // Overridden!
                   // But is Hidden == True?
                   KDesktopFile innerConfig(*localit, true);
                   if (innerConfig.readBoolEntry("Hidden", false)) {
                       // Override confirmed; exit speedily without autostarting
                       autostartOverriddenAndDisabled = true;
                   }
               }
           }
       }

       if (autostartOverriddenAndDisabled == true)
           continue;

       if (config.hasKey("OnlyShowIn"))
       {
#ifdef WITH_OLD_XDG_STD
          if ((!config.readListEntry("OnlyShowIn", ';').contains("TDE")) && (!config.readListEntry("OnlyShowIn", ';').contains("KDE")))
              continue;
#else
          if (!config.readListEntry("OnlyShowIn", ';').contains("TDE"))
              continue;
#endif
       }
       if (config.hasKey("NotShowIn"))
       {
#ifdef WITH_OLD_XDG_STD
           if ((config.readListEntry("NotShowIn", ';').contains("TDE")) || (config.readListEntry("NotShowIn", ';').contains("KDE")))
               continue;
#else
           if (config.readListEntry("NotShowIn", ';').contains("TDE"))
               continue;
#endif
       }

       AutoStartItem *item = new AutoStartItem;
       item->name = extractName(*it);
       item->service = *it;
       if (config.hasKey("X-TDE-autostart-after"))
           item->startAfter = config.readEntry("X-TDE-autostart-after");
       else
           item->startAfter = config.readEntry("X-TDE-autostart-after");
       if( m_newStartup )
       {
          if (config.hasKey("X-TDE-autostart-phase"))
              item->phase = config.readNumEntry("X-TDE-autostart-phase", 2);
          else
              item->phase = config.readNumEntry("X-TDE-autostart-phase", 2);
          if (item->phase < 0)
             item->phase = 0;
       }
       else
       {
          if (config.hasKey("X-TDE-autostart-phase"))
              item->phase = config.readNumEntry("X-TDE-autostart-phase", 1);
          else
              item->phase = config.readNumEntry("X-TDE-autostart-phase", 1);
          if (item->phase < 1)
             item->phase = 1;
       }
       m_startList->append(item);
   }

   // Check for duplicate entries and remove if found
   TQPtrListIterator<AutoStartItem> it1(*m_startList);
   TQPtrListIterator<AutoStartItem> it2(*m_startList);
   AutoStartItem *item1;
   AutoStartItem *item2;
   while ((item1 = it1.current()) != 0) {
       bool dupfound1 = false;
       it2.toFirst();
       while ((item2 = it2.current()) != 0) {
           bool dupfound2 = false;
           if (item2 != item1) {
               if (item1->service == item2->service) {
                   m_startList->removeRef(item2);
                   dupfound1 = true;
                   dupfound2 = true;
               }
           }
           if (!dupfound2) {
               ++it2;
           }
       }
       if (!dupfound1) {
           ++it1;
       }
   }
}
Beispiel #11
0
std::pair<UCharImageType2D::Pointer,UShortImageType2D::Pointer> Focus::MakeProjection2()
{
	if(!imgIn)
		return std::pair<UCharImageType2D::Pointer,UShortImageType2D::Pointer>(NULL,NULL);

	int size1 = (int)imgIn->GetLargestPossibleRegion().GetSize()[0];
	int size2 = (int)imgIn->GetLargestPossibleRegion().GetSize()[1];
	int size3 = (int)imgIn->GetLargestPossibleRegion().GetSize()[2];

	UCharImageType2D::Pointer outImg = UCharImageType2D::New();
	UShortImageType2D::Pointer outDepth = UShortImageType2D::New();
	UCharImageType2D::PointType origin;
	origin[0] = 0;
	origin[1] = 0;
	outImg->SetOrigin( origin );
	outDepth->SetOrigin( origin );

	UCharImageType2D::IndexType start = {{ 0,0 }};
	UCharImageType2D::SizeType  size = {{ size1, size2 }};
	UCharImageType2D::RegionType region;
	region.SetSize( size );
	region.SetIndex( start );

	outImg->SetRegions( region ); 
	outDepth->SetRegions ( region );
	outImg->Allocate();
	outDepth->Allocate();

	typedef itk::ImageRegionIteratorWithIndex< UCharImageType2D > IteratorType;
	IteratorType it( outImg, outImg->GetLargestPossibleRegion() );
	typedef itk::ImageRegionIteratorWithIndex < UShortImageType2D> IteratorType2;
	IteratorType2 it2( outDepth, outDepth->GetLargestPossibleRegion() );
	for(it.GoToBegin(),it2.GoToBegin(); !it.IsAtEnd(); ++it,++it2)
	{
		UCharImageType2D::IndexType ind = it.GetIndex();
		int max = -1000;
		int mSlice = 0;
		for(int z=0; z<size3; ++z)
		{
			FloatImageType::IndexType ind3f;
			ind3f[0] = ind[0];
			ind3f[1] = ind[1];
			ind3f[2] = z;
			FloatImageType::PixelType pix = varImg->GetPixel(ind3f);
			if((int)pix > max)
			{
				max = (int)pix;
				mSlice = z;
			}
		}
		UCharImageType::IndexType ind3;
		ind3[0] = ind[0];
		ind3[1] = ind[1];
		ind3[2] = mSlice;
		it.Set( imgIn->GetPixel(ind3) );
		it2.Set ( mSlice );
	}

	std::pair< UCharImageType2D::Pointer, UShortImageType2D::Pointer> retpair;
	retpair.first = outImg;
	retpair.second = outDepth;
	return retpair;
}
Beispiel #12
0
void MainWindow::openFile(const QString & filename) {
    emit loadingNewMesh();
    auto package = std::make_shared<MeshPackage>();
    m_mesh.reset(readOBJtoSimplicialComplex<MeshType>(filename.toStdString()));
    std::cout << "Read a mesh with verts:faces: " << m_mesh->vertices().size()<< ":" << m_mesh->numSimplices() << std::endl;
    m_dec.reset(new decltype(m_dec)::element_type(*m_mesh));
    typedef typename MeshType::Vector Vector;

    package->vertices = m_mesh->vertices();//copy here so we can normalize coordinates
    package->indices = mtao_internal::template simplicesToRenderable<2>(*m_mesh);
    package->facevertices.resize(package->indices.size());
    package->faceindices.resize(package->indices.size());
    package->edgeindices = mtao_internal::simplicesToRenderable<1>(*m_mesh);
    package->edgevertices.resize(package->edgeindices.size());



    int i;


    auto& verts = package->vertices;
    auto& packed_indices = package->indices;
    auto& faceverts = package->facevertices;
    auto& faceindices = package->faceindices;
    auto& edgeindices = package->edgeindices;
    auto& edgeverts = package->edgevertices;

    //    mtao::normalizeInPlace(verts);//Normalize!!
    std::cout << "Normalizing vertices..." << std::endl;
    m_bbox = mtao::getBoundingBox(verts);
    mtao::normalizeToBBoxInPlace(verts,m_bbox);

    std::cout << "Writing primal verts" << std::endl;
    std::transform(packed_indices.cbegin(), packed_indices.cend(), faceverts.begin(),
                   [&verts](const unsigned int ind)->typename std::remove_reference<decltype(faceverts)>::type::value_type
    {
        return verts[ind];
    });

    i=0;
    std::cout << "Writing primal face indices" << std::endl;
    for(unsigned int & ind: faceindices)
    {
        ind = i++;
    }

    std::cout << "Writing primal edge vertices" << std::endl;
    std::transform(edgeindices.cbegin(), edgeindices.cend(), edgeverts.begin(),
                   [&verts](const unsigned int ind)->typename std::remove_reference<decltype(edgeverts)>::type::value_type
    {
        return verts[ind];
    });

    i=0;
    std::cout << "Writing primal edge indices" << std::endl;
    for(unsigned int & ind: edgeindices)
    {
        ind = i++;
    }





    std::cout << "Writing dual quantities" << std::endl;
    auto& dual_vertices = package->dual_vertices;
    auto& dual_indices = package->dual_indices;
    auto& dual_edgeindices = package->dual_edgeindices;
    auto& dual_edgeverts = package->dual_edgevertices;
    auto& dual_faceindices = package->dual_faceindices;
    auto& dual_faceverts = package->dual_facevertices;//blarg! can't autosize because this might turn out to be stupidly sophisticated

    dual_vertices.resize(
                m_mesh->template numSimplices<2>() +
                m_mesh->template numSimplices<1>() +
                m_mesh->template numSimplices<0>()
                );
    int offset2 = 0;//offset1 + m_mesh->template numSimplices<1>();
    int offset1 = m_mesh->template numSimplices<2>();
    int offset0 = offset1 + m_mesh->template numSimplices<1>();
    dual_edgeindices.resize(2*m_mesh->template numSimplices<1>());
    dual_edgeverts.resize(dual_edgeindices.size());


    typedef typename decltype(m_dec)::element_type::SparseMatrixColMajor SparseMatrix;
    const SparseMatrix & d0 = m_dec->template d<0>().expr;
    const SparseMatrix & d1 = m_dec->template d<1>().expr;





    package->num_dual_verts = m_mesh->template numSimplices<2>();

    std::cout << "Writing dual verts" << std::endl;
    for(auto&& s: m_mesh->template simplices<2>()) {
        dual_vertices[s.Index()+offset2] = s.Center();
    }

    for(auto&& s: m_mesh->template simplices<1>()) {
        dual_vertices[s.Index()+offset1] = s.Center();
    }

    for(auto&& s: m_mesh->template simplices<0>()) {
        dual_vertices[s.Index()+offset0] = s.Center();
    }

    std::cout << "Writing dual mesh indices" << std::endl;
    for(int i=0; i < m_mesh->template simplices<0>().size(); ++i) {
        auto&& s0 = m_mesh->template simplex<0>(i);

        for(SparseMatrix::InnerIterator it1(d0, s0.Index()); it1; ++it1) {
            auto&& s1 = m_mesh->template simplex<1>(it1.row());

            for(SparseMatrix::InnerIterator it2(d1, s1.Index()); it2; ++it2) {
                auto&& s2 = m_mesh->template simplex<2>(it2.row());
                dual_indices.push_back(s0.Index()+offset0);
                dual_indices.push_back(s1.Index()+offset1);
                dual_indices.push_back(s2.Index()+offset2);
            }
        }
    }



    std::cout << "Writing dual edge indices" << std::endl;
    for(int i=0; i < m_mesh->template simplices<1>().size(); ++i) {
        auto&& s = m_mesh->template simplex<1>(i);
        SparseMatrix::InnerIterator it(d1, s.Index());
        if(!it) continue;
        auto&& s1 = m_mesh->template simplex<2>(it.row());
        dual_edgeindices[2*i] = 2*i;
        dual_edgeverts[2*i] = s1.Center();
        ++it;
        if(!it) continue;
        auto&& s2 = m_mesh->template simplex<2>(it.row());
        dual_edgeindices[2*i+1] = 2*i+1;
        dual_edgeverts[2*i+1] = s2.Center();

    }






    std::cout << "Reserving" << std::endl;

    dual_faceverts.clear();
    dual_faceverts.reserve(3*m_mesh->template numSimplices<2>());
    dual_faceindices.clear();
    dual_faceindices.reserve(3*m_mesh->template numSimplices<2>());

    m_dual_vertex_form_indices.clear();
    m_dual_vertex_form_indices.reserve(m_mesh->template numSimplices<0>());

    int count=0;
    std::cout << "Writing dual face indices" << std::endl;
    for(int i=0; i < m_mesh->template simplices<0>().size(); ++i) {
        auto&& s0 = m_mesh->template simplex<0>(i);

        for(SparseMatrix::InnerIterator it1(d0, s0.Index()); it1; ++it1) {
            auto&& s1 = m_mesh->template simplex<1>(it1.row());

            SparseMatrix::InnerIterator it2(d1, s1.Index());
        if(!it2) continue;

            auto&& s2 = m_mesh->template simplex<2>(it2.row());
            dual_faceverts.push_back(s0.Center());
            if((s0[0] == s1[0]) ^ s1.isSameSign(s2)) {
            dual_faceverts.push_back(s2.Center());
            dual_faceverts.push_back(s1.Center());
            } else {
            dual_faceverts.push_back(s1.Center());
            dual_faceverts.push_back(s2.Center());
            }
            ++count;
            ++it2;
        if(!it2) continue;

            auto&& s2b = m_mesh->template simplex<2>(it2.row());
            dual_faceverts.push_back(s0.Center());
            if((s0[0] == s1[0]) ^ s1.isSameSign(s2)) {
            dual_faceverts.push_back(s1.Center());
            dual_faceverts.push_back(s2b.Center());
            } else {
            dual_faceverts.push_back(s2b.Center());
            dual_faceverts.push_back(s1.Center());
            }
            ++count;
        }
        m_dual_vertex_form_indices.push_back(count);
    }


    dual_faceindices.clear();
    dual_faceindices.resize(dual_faceverts.size());
    for(int i=0; i < dual_faceindices.size(); ++i) {
        dual_faceindices[i] = i;
    }




    std::cout << "Normalizing duals" << std::endl;

    mtao::normalizeToBBoxInPlace(dual_faceverts,m_bbox);
    mtao::normalizeToBBoxInPlace(dual_edgeverts,m_bbox);
    mtao::normalizeToBBoxInPlace(dual_vertices,m_bbox);







    //package->vertex_normals = m_mesh->getNormals();
    //package->vertex_normals = m_mesh->getNormals(NormalTriangleMesh::Area_Normal);
    package->vertex_normals = m_mesh->getNormals(NormalTriangleMesh::Angle_Normal);






















    std::cout << "Done loading mesh metadata" << std::endl;
    emit meshLoaded(package);
}
Beispiel #13
0
	void HACD::CreateGraph()
    {
		// vertex to triangle adjacency information
		std::vector< std::set<long> >  vertexToTriangles;		
		vertexToTriangles.resize(m_nPoints);
		for(size_t t = 0; t < m_nTriangles; ++t)
		{
			vertexToTriangles[m_triangles[t].X()].insert(static_cast<long>(t));
			vertexToTriangles[m_triangles[t].Y()].insert(static_cast<long>(t));
			vertexToTriangles[m_triangles[t].Z()].insert(static_cast<long>(t));
		}

		m_graph.Clear();
		m_graph.Allocate(m_nTriangles, 5 * m_nTriangles);
		unsigned long long tr1[3];
		unsigned long long tr2[3];
        long i1, j1, k1, i2, j2, k2;
        long t1, t2;
        for (size_t v = 0; v < m_nPoints; v++) 
		{
			std::set<long>::const_iterator it1(vertexToTriangles[v].begin()), itEnd(vertexToTriangles[v].end()); 
			for(; it1 != itEnd; ++it1)
			{
                t1 = *it1;
                i1 = m_triangles[t1].X();
                j1 = m_triangles[t1].Y();
                k1 = m_triangles[t1].Z();
				tr1[0] = GetEdgeIndex(i1, j1);
				tr1[1] = GetEdgeIndex(j1, k1);
				tr1[2] = GetEdgeIndex(k1, i1);
				std::set<long>::const_iterator it2(it1);
				for(++it2; it2 != itEnd; ++it2)
				{
                    t2 = *it2;
                    i2 = m_triangles[t2].X();
                    j2 = m_triangles[t2].Y();
                    k2 = m_triangles[t2].Z();
					tr2[0] = GetEdgeIndex(i2, j2);
					tr2[1] = GetEdgeIndex(j2, k2);
					tr2[2] = GetEdgeIndex(k2, i2);
					int shared = 0;
					for(int i = 0; i < 3; ++i)
					{
						for(int j = 0; j < 3; ++j)
						{
							if (tr1[i] == tr2[j])	
							{
								shared++;
							}
						}
					}
					if (shared == 1) // two triangles are connected if they share exactly one edge
					{
						m_graph.AddEdge(t1, t2);
					}
				}
			}
        }
        if (m_ccConnectDist >= 0.0)
        {
            m_graph.ExtractCCs();
            if (m_graph.m_nCCs > 1) 
            {
                std::vector< std::set<long> > cc2V;
                cc2V.resize(m_graph.m_nCCs);
                long cc;
                for(size_t t = 0; t < m_nTriangles; ++t)
                {
                    cc = m_graph.m_vertices[t].m_cc;
                    cc2V[cc].insert(m_triangles[t].X());
                    cc2V[cc].insert(m_triangles[t].Y());
                    cc2V[cc].insert(m_triangles[t].Z());
                }
                
                for(size_t cc1 = 0; cc1 < m_graph.m_nCCs; ++cc1)
                {
                    for(size_t cc2 = cc1+1; cc2 < m_graph.m_nCCs; ++cc2)
                    {
                        std::set<long>::const_iterator itV1(cc2V[cc1].begin()), itVEnd1(cc2V[cc1].end()); 
                        for(; itV1 != itVEnd1; ++itV1)
                        {
							double distC1C2 = std::numeric_limits<double>::max();
                            double dist;
                            t1 = -1;
                            t2 = -1;
                            std::set<long>::const_iterator itV2(cc2V[cc2].begin()), itVEnd2(cc2V[cc2].end()); 
                            for(; itV2 != itVEnd2; ++itV2)
                            {
                                dist = (m_points[*itV1] - m_points[*itV2]).GetNorm();
                                if (dist < distC1C2)
                                {
                                    distC1C2 = dist;
                                    t1 = *vertexToTriangles[*itV1].begin();
                                    
									std::set<long>::const_iterator it2(vertexToTriangles[*itV2].begin()), 
																   it2End(vertexToTriangles[*itV2].end()); 
									t2 = -1;
									for(; it2 != it2End; ++it2)
									{
										if (*it2 != t1)
										{
											t2 = *it2;
											break;
										}
									}
                                }
                            }
                            if (distC1C2 <= m_ccConnectDist && t1 > 0 && t2 > 0)
                            {
								
                                m_graph.AddEdge(t1, t2);                    
                            }
                        }
                    }
                }
            }
        }
    }
Beispiel #14
0
int main(int argc, char* argv[])
{

	GString strNetworkConnections(32767);
	GetNetworkConnections(strNetworkConnections,NET_FLAG_REDUCE_INFO|NET_FLAG_NO_UDP);

	GString strWanIP, strNoWanIPError; 
	ExternalIP(&strWanIP, &strNoWanIPError);

	CSmtp mail;
	GString strMailServer("smtp.gmail.com");


	// ------- GMail TLS --------
	// Note about GMail - login, then under "My Account" go to "Sign-In & Security" and set "Allow Less Secure Apps": to ON.  
	// This enables TLS and non-google apps(not insecure apps).  AOL, HotMail, and Yahoo enable the SMTP over TLS relay for
	// the paid email account services with no ads and higher mail/data limits.
	//
	mail.SetSMTPServer(strMailServer,587);
	mail.SetSecurityType(USE_TLS);

#include <"Do.not.compile">  // add your own Gmail account in the next two lines..... then delete this line   (and set the recipient)

	// Note about GMail - login, then under "My Account" go to "Sign-In & Security" and set "Allow Less Secure Apps": to ON.  
//	mail.SetLogin("*****@*****.**");
//	mail.SetPassword("MyOwnPassword");


	mail.SetSenderName("My Application");
	mail.SetSenderMail("*****@*****.**");
	mail.SetReplyTo("*****@*****.**");
	
	GString strSubject(g_strThisHostName);
	strSubject << " Stats";
	mail.SetSubject(strSubject);

	mail.AddRecipient("*****@*****.**");   //<---------------------------------------------------------- Who to send the email to
//	mail.AddRecipient("*****@*****.**");


  	mail.SetXPriority(XPRIORITY_NORMAL);
  	mail.SetXMailer("Professional (v7.77) Pro");
  	

	mail.AddMsgLine("----------------------------Wan IP----------------------------------------");
	mail.AddMsgLine(strWanIP);

	mail.AddMsgLine("----------------------Network Interfaces----------------------------------");
	GString strThisHost("Host:");
	strThisHost << g_strThisHostName;
	mail.AddMsgLine(strThisHost);
	GStringList lstBoundIPAddresses;
	InternalIPs(&lstBoundIPAddresses);
	GStringIterator it2(&lstBoundIPAddresses);
	while(it2())
	{
		mail.AddMsgLine(it2++);
	}

	mail.AddMsgLine("----------------------Network Connections----------------------------------");
	GStringList l("\n",strNetworkConnections); // each row divided by "\n"
	GStringIterator it(&l);
	while(it())
	{
		mail.AddMsgLine(it++);
	}


	mail.AddMsgLine("------------------------Processes-------------------------------------------");
	GString strRunningProcessData;
	GetProcessList( &strRunningProcessData );
	GStringList lstProcess("\n",strRunningProcessData); // each row divided by "\n"
	GStringIterator itP(&lstProcess);
	while(itP())
	{
		//mail.AddMsgLine(itP++);								// write it out -  raw
		GProcessListRow *pRow = new GProcessListRow(itP++);		// or use the already written code to parse process information

		GString strProcess;										// write onluy the data we want into this GString 
		strProcess << "pid:" << pRow->strPID << "   " << pRow->strName  << "     [" << pRow->strBinaryPath << "]";
		mail.AddMsgLine(strProcess);							// then write it out - formatted.
	}
	
  	//mail.AddAttachment("../test1.jpg");
  	//mail.AddAttachment("c:\\test2.exe");
	//mail.AddAttachment("c:\\test3.txt");
	mail.Send();



	return 0;
}
void tst_QJSValueIterator::iterateArray()
{
    QFETCH(QStringList, propertyNames);
    QFETCH(QStringList, propertyValues);

    QJSEngine engine;
    QJSValue array = engine.newArray();

    // Fill the array
    for (int i = 0; i < propertyNames.size(); ++i) {
        array.setProperty(propertyNames.at(i), propertyValues.at(i));
    }

    // Iterate thru array properties. Note that the QJSValueIterator doesn't guarantee
    // any order on the iteration!
    int length = array.property("length").toInt();
    QCOMPARE(length, propertyNames.size());

    bool iteratedThruLength = false;
    QHash<QString, QJSValue> arrayProperties;
    QJSValueIterator it(array);

    // Iterate forward
    while (it.hasNext()) {
        it.next();

        const QString name = it.name();
        if (name == QString::fromLatin1("length")) {
            QVERIFY(it.value().isNumber());
            QCOMPARE(it.value().toInt(), length);
            QVERIFY2(!iteratedThruLength, "'length' appeared more than once during iteration.");
            iteratedThruLength = true;
            continue;
        }

        // Storing the properties we iterate in a hash to compare with test data.
        QVERIFY2(!arrayProperties.contains(name), "property appeared more than once during iteration.");
        arrayProperties.insert(name, it.value());
        QVERIFY(it.value().strictlyEquals(array.property(name)));
    }

    // Verify properties
    QVERIFY(iteratedThruLength);
    QCOMPARE(arrayProperties.size(), propertyNames.size());
    for (int i = 0; i < propertyNames.size(); ++i) {
        QVERIFY(arrayProperties.contains(propertyNames.at(i)));
        QCOMPARE(arrayProperties.value(propertyNames.at(i)).toString(), propertyValues.at(i));
    }

#if 0

    // Iterate backwards
    arrayProperties.clear();
    iteratedThruLength = false;
    it.toBack();

    while (it.hasPrevious()) {
        it.previous();

        const QString name = it.name();
        if (name == QString::fromLatin1("length")) {
            QVERIFY(it.value().isNumber());
            QCOMPARE(it.value().toInt(), length);
            QCOMPARE(it.flags(), QScriptValue::SkipInEnumeration | QScriptValue::Undeletable);
            QVERIFY2(!iteratedThruLength, "'length' appeared more than once during iteration.");
            iteratedThruLength = true;
            continue;
        }

        // Storing the properties we iterate in a hash to compare with test data.
        QVERIFY2(!arrayProperties.contains(name), "property appeared more than once during iteration.");
        arrayProperties.insert(name, it.value());
        QCOMPARE(it.flags(), array.propertyFlags(name));
        QVERIFY(it.value().strictlyEquals(array.property(name)));
    }

    // Verify properties
    QVERIFY(iteratedThruLength);
    QCOMPARE(arrayProperties.size(), propertyNames.size());
    for (int i = 0; i < propertyNames.size(); ++i) {
        QVERIFY(arrayProperties.contains(propertyNames.at(i)));
        QCOMPARE(arrayProperties.value(propertyNames.at(i)).toString(), propertyValues.at(i));
    }

    // ### Do we still need this test?
    // Forward test again but as object
    arrayProperties.clear();
    iteratedThruLength = false;
    QJSValue arrayObject = engine.toObject(array);
    QJSValueIterator it2(arrayObject);

    while (it2.hasNext()) {
        it2.next();

        const QString name = it2.name();
        if (name == QString::fromLatin1("length")) {
            QVERIFY(it2.value().isNumber());
            QCOMPARE(it2.value().toInt(), length);
            QCOMPARE(it2.flags(), QScriptValue::SkipInEnumeration | QScriptValue::Undeletable);
            QVERIFY2(!iteratedThruLength, "'length' appeared more than once during iteration.");
            iteratedThruLength = true;
            continue;
        }

        // Storing the properties we iterate in a hash to compare with test data.
        QVERIFY2(!arrayProperties.contains(name), "property appeared more than once during iteration.");
        arrayProperties.insert(name, it2.value());
        QCOMPARE(it2.flags(), arrayObject.propertyFlags(name));
        QVERIFY(it2.value().strictlyEquals(arrayObject.property(name)));
    }

    // Verify properties
    QVERIFY(iteratedThruLength);
    QCOMPARE(arrayProperties.size(), propertyNames.size());
    for (int i = 0; i < propertyNames.size(); ++i) {
        QVERIFY(arrayProperties.contains(propertyNames.at(i)));
        QCOMPARE(arrayProperties.value(propertyNames.at(i)).toString(), propertyValues.at(i));
    }
#endif
}
Beispiel #16
0
int main(int argc, char** argv)
{
	//setting up default values
	width=DEFAULT_WIDTH;
	heigth=DEFAULT_HEIGTH;
	input_topic=DEFAULT_INPUT_TOPIC;
	output_topic=DEFAULT_OUTPUT_TOPIC;
	head_controller_topic=DEFAULT_HEAD_TOPIC;
	sampling_rate=RATE;
        //reading the configuration
	std::string path=ros::package::getPath("accompany_siena_images_republisher")+"/config/config.txt";
	//std::cout << path << "\n";
	
	std::ifstream infile(path.c_str());

	std::string param,value;
	while(infile >> param >> value)
	{
		//std::cout << "param: " << param << ", value: " << value <<"\n";
		if (param=="cob_version")
		{
			/*const char * c_val=value.c_str();
			if (strcmp(c_val,"cob3-6")==0||strcmp(c_val,"cob_3_6")==0||strcmp(c_val,"cob3_6")==0||strcmp(c_val,"cob-3-6")==0) cob_version==COB_3_6;
			if (strcmp(c_val,"cob3-2")==0||strcmp(c_val,"cob_3_2")==0||strcmp(c_val,"cob3_2")==0||strcmp(c_val,"cob-3-2")==0) cob_version==COB_3_2;
			printf("tmp cob version: %s\n",c_val);*/
			if (value=="cob3-6"||value=="cob_3_6"||value=="cob3-6"||value=="cob-3-6") cob_version=COB_3_6;
			if (value=="cob3-2"||value=="cob_3_2"||value=="cob3-2"||value=="cob-3-2") cob_version=COB_3_2;
		}
		if (param=="image_width")
		{
			sscanf(value.c_str(), "%d", &width);
		}
		if (param=="image_heigth")
		{	
			sscanf(value.c_str(), "%d", &heigth);
		}
		if (param=="input_topic")
		{
			input_topic=value;
		}
		if (param=="output_topic")
		{
			output_topic=value;
		}
		if (param=="head_downsampled_control_topic")
		{
			head_controller_topic=value;
		}
		if (param=="sampling_rate")
		{
			sscanf(value.c_str(), "%d", &sampling_rate);
		}
	}
	if (cob_version== COB_3_6)		
		std::cout <<"Cob version: cob 3-6\n";
	else
		std::cout <<"Cob version: cob 3-2\n";
	std::cout <<"Width:" <<width <<", Heigth:"<<heigth<<"\n";
	std::cout <<"Input topic: " <<input_topic<<"\n";
	std::cout <<"Output topic: " <<output_topic<<"\n";
	std::cout <<"Head Controller topic: " <<head_controller_topic<<"\n";
	std::cout <<"Sampling rate: "<<sampling_rate<<"\n";

	//computing (here -> only once!) pivot point coords:
	half_width=(int)width/2;
	half_heigth=(int)heigth/2;
	std::cout <<"HalfWidth:" <<half_width <<", HalfHeigth:"<<half_heigth<<"\n";
	
	ros::init(argc,argv,"Accompany_Republisher");
	ros::NodeHandle nh;
	
	image_transport::ImageTransport it2(nh);
	image_transport::Subscriber sub = it2.subscribe(input_topic, 1, image_callback);


	image_transport::ImageTransport it(nh);
	pub = it.advertise(output_topic,1);

	//Subscribing head position:
	ros::Subscriber head_sub=nh.subscribe(head_controller_topic,1,head_callback);
	
	std::cout <<"\n\n";
	std::cout << "Remapping topic \"" <<input_topic << "\" on \"" << output_topic <<"\"\n";
        std::cout << "Downsizing images to "<<width<<"x"<<heigth<<"\n";
	std::cout << "Cutting image frequency with "<<sampling_rate <<" ratio.\n";
	std::cout << "Images Republisher started...\n"	;

	//try to get robot version from environment
	try{
		std::cout << "Running robot: " << getenv("ROBOT") << "\n";
		std::string cob_run = getenv("ROBOT");
		if (cob_run=="cob3-2") cob_version=COB_3_2;
		if (cob_run=="cob3-6") cob_version=COB_3_6;
	}catch(const std::exception e)
	{
		std::cout << "Exception retriving running robot version: " << e.what() << "\n"; 
	}
	catch(...)
	{
		std::cout << "Generic exception retriving runninbg robot version: unknown.\n";
	}

	ros::spin();
	/*ros::Rate loop_rate(0.2);
	while (nh.ok())
	{
		if (last_img!= NULL) 
		{
			printf("**\n");
			sensor_msgs::ImagePtr msg = sensor_msgs::CvBridge::cvToImgMsg(last_img,"bgr8");
			pub.publish(msg);
			ros::spinOnce();
			loop_rate.sleep();
		}
	}*/
 	//cvReleaseImage(&last_img);
        
}
Beispiel #17
0
void CTankAIBase::CheckResponse( std::string response  ) 
{	
	// Debug 
	// Example response 
	// response = TANK_RESPONSE_PASS ; 
	// response = TANK_RESPONSE_FAIL ; 
	// response = std::string ( TANK_RESPONSE_PASS ) + std::string( " enemy(1233,-3,100), projectile(1234,-5,100), projectile(1235,-15,100), projectile(1236,-10,100) \n" ) ; 

	// Check the response
	if( response.size() <= 0 ) {
		// Nothing to do. 
		return ;
	}

	// This is a good response. 
	// Check for radar ping response and populate the m_objects with the information. 
	// Clear the object list as it is no longer valid. 
	m_objects.clear(); 

	unsigned int UUID ;
	CTankAIObject::TypeEnum type;
	char x; 
	char y;

    // regular expression
	// Example:  enemy(1233,-3,100), projectile(1234,-5,100), projectile(1235,-15,100), projectile(1236,-10,100) 
	const std::regex pattern("(projectile|tank)\\(([0-9]+),-?([0-9]+),-?([0-9]+)\\)");
	const std::regex patternNumber("-?([0-9]+)");

    const std::sregex_token_iterator end;
	for (std::sregex_token_iterator it(response.cbegin(), response.cend(), pattern);  it != end; ++it) {
		
		// Token to string. 
		std::string singleObject = (*it) ; 

		// Find the type 
		if( singleObject.find( TANK_OBJECT_TYPE_TANK ) != std::string::npos ) {
			type = CTankAIObject::tank ; 
		} else if( singleObject.find( TANK_OBJECT_TYPE_PROJECTILE ) != std::string::npos ) {
			type = CTankAIObject::projectile ; 
		} else {
			// Unknown type 
			continue; 
		}

		// Loop thought the prameters extracting the UUID, dx, dy. 
		int offset = 0 ; 
		const std::sregex_token_iterator end2;
		for (std::sregex_token_iterator it2( singleObject.cbegin(), singleObject.cend(), patternNumber);  it2 != end2; ++it2) {
		
			switch( offset ) {
				case 0:
					UUID = atoi( (*it2).str().c_str() ); 
					break; 
				case 1:
					x = (char ) atoi( (*it2).str().c_str() ); 
					break; 
				case 2:
					y = (char ) atoi( (*it2).str().c_str() ); 
					break; 
			}
			offset++; 
		}

		

		this->m_objects.push_back( CTankAIObject( UUID, type, x , y ) ); 
		// std::cout << singleObject << "\n" ; // Debug 
	}
}
Beispiel #18
0
bool KviPackageWriter::packInternal(const QString & szFileName, kvi_u32_t)
{

	KviFile f(szFileName);
	if(!f.open(QFile::WriteOnly | QFile::Truncate))
	{
		setLastError(__tr2qs("Can't open file for writing"));
		return false;
	}

	// write the PackageHeader
	// Magic
	char magic[4];
	magic[0] = 'K';
	magic[1] = 'V';
	magic[2] = 'P';
	magic[3] = 'F';
	if(f.write(magic, 4) != 4)
		return writeError();

	// Version
	kvi_u32_t uVersion = 0x1;
	if(!f.save(uVersion))
		return writeError();

	// Flags
	kvi_u32_t uFlags = 0x0;
	if(!f.save(uFlags))
		return writeError();

	// write PackageInfo
	// InfoFieldCount
	kvi_u32_t uCount = stringInfoFields()->count() + binaryInfoFields()->count();
	if(!f.save(uCount))
		return writeError();

	m_p->iCurrentProgress = 5;
	if(!updateProgress(m_p->iCurrentProgress, __tr2qs("Writing informational fields")))
		return false; // aborted

	// InfoFields (string)
	KviPointerHashTableIterator<QString, QString> it(*stringInfoFields());
	while(QString * s = it.current())
	{
		if(!f.save(it.currentKey()))
			return writeError();
		kvi_u32_t uType = KVI_PACKAGE_INFOFIELD_TYPE_STRING;
		if(!f.save(uType))
			return writeError();
		if(!f.save(*s))
			return writeError();
		++it;
	}

	// InfoFields (binary)
	KviPointerHashTableIterator<QString, QByteArray> it2(*binaryInfoFields());
	while(QByteArray * b = it2.current())
	{
		if(!f.save(it2.currentKey()))
			return writeError();
		kvi_u32_t uType = KVI_PACKAGE_INFOFIELD_TYPE_BINARYBUFFER;
		if(!f.save(uType))
			return writeError();
		if(!f.save(*b))
			return writeError();
		++it2;
	}

	m_p->iCurrentProgress = 10;
	if(!updateProgress(m_p->iCurrentProgress, __tr2qs("Writing package data")))
		return false; // aborted

	// write PackageData
	int iIdx = 0;
	for(KviPackageWriterDataField * pDataField = m_p->pDataFields->first(); pDataField; pDataField = m_p->pDataFields->next())
	{
		kvi_u32_t uKviPackageWriterDataFieldType = pDataField->m_uType;
		if(!f.save(uKviPackageWriterDataFieldType))
			return writeError();

		kvi_file_offset_t savedLenOffset = f.pos();
		// here we will store the length of the field once it's written
		if(!f.save(uKviPackageWriterDataFieldType))
			return writeError();

		m_p->iCurrentProgress = 10 + ((90 * iIdx) / m_p->pDataFields->count());

		switch(pDataField->m_uType)
		{
			case KVI_PACKAGE_DATAFIELD_TYPE_FILE:
				if(!packFile(&f, pDataField))
					return false;
				break;
			default:
				setLastError(__tr2qs("Internal error"));
				return false;
				break;
		}

		kvi_file_offset_t savedEndOffset = f.pos();
		f.seek(savedLenOffset);
		if(!f.save(pDataField->m_uWrittenFieldLength))
			return writeError();

		f.seek(savedEndOffset);
		iIdx++;
	}

	return true;
}
Beispiel #19
0
static AActor *SelectTeleDest (int tid, int tag, bool norandom)
{
	AActor *searcher;

	// If tid is non-zero, select a destination from a matching actor at random.
	// If tag is also non-zero, the selection is restricted to actors in sectors
	// with a matching tag. If tid is zero and tag is non-zero, then the old Doom
	// behavior is used instead (return the first teleport dest found in a tagged
	// sector).

	// Compatibility hack for some maps that fell victim to a bug in the teleport code in 2.0.9x
	if (ib_compatflags & BCOMPATF_BADTELEPORTERS) tag = 0;

	if (tid != 0)
	{
		NActorIterator iterator (NAME_TeleportDest, tid);
		int count = 0;
		while ( (searcher = iterator.Next ()) )
		{
			if (tag == 0 || tagManager.SectorHasTag(searcher->Sector, tag))
			{
				count++;
			}
		}

		// If teleport dests were not found, the sector tag is ignored for the
		// following compatibility searches.
		// Do this only when tag is 0 because this is the only case that was defined in Hexen.
		if (count == 0)
		{
			if (tag == 0)
			{
				// Try to find a matching map spot (fixes Hexen MAP10)
				NActorIterator it2 (NAME_MapSpot, tid);
				searcher = it2.Next ();
				if (searcher == NULL)
				{
					// Try to find a matching non-blocking spot of any type (fixes Caldera MAP13)
					FActorIterator it3 (tid);
					searcher = it3.Next ();
					while (searcher != NULL && (searcher->flags & MF_SOLID))
					{
						searcher = it3.Next ();
					}
					return searcher;
				}
			}
		}
		else
		{
			if (count != 1 && !norandom)
			{
				count = 1 + (pr_teleport() % count);
			}
			searcher = NULL;
			while (count > 0)
			{
				searcher = iterator.Next ();
				if (tag == 0 || tagManager.SectorHasTag(searcher->Sector, tag))
				{
					count--;
				}
			}
		}
		return searcher;
	}

	if (tag != 0)
	{
		int secnum;

		FSectorTagIterator itr(tag);
		while ((secnum = itr.Next()) >= 0)
		{
			// Scanning the snext links of things in the sector will not work, because
			// TeleportDests have MF_NOSECTOR set. So you have to search *everything*.
			// If there is more than one sector with a matching tag, then the destination
			// in the lowest-numbered sector is returned, rather than the earliest placed
			// teleport destination. This means if 50 sectors have a matching tag and
			// only the last one has a destination, *every* actor is scanned at least 49
			// times. Yuck.
			TThinkerIterator<AActor> it2(NAME_TeleportDest);
			while ((searcher = it2.Next()) != NULL)
			{
				if (searcher->Sector == &level.sectors[secnum])
				{
					return searcher;
				}
			}
		}
	}

	return NULL;
}
void
mitk::TeemDiffusionTensor3DReconstructionImageFilter<D,T>
::Update()
{
  itk::Statistics::MersenneTwisterRandomVariateGenerator::Pointer randgen = itk::Statistics::MersenneTwisterRandomVariateGenerator::New();
  randgen->SetSeed();

  // save input image to nrrd file in temp-folder
  char filename[512];
  int random_integer = randgen->GetIntegerVariate();
  sprintf( filename, "dwi_%d.nhdr",random_integer);

  try
  {
    mitk::IOUtil::Save(m_Input, filename);
  }
  catch (itk::ExceptionObject e)
  {
    std::cout << e << std::endl;
  }

  file_replace(filename,"vector","list");

  // build up correct command from input params
  char command[4096];
  sprintf( command, "tend estim -i %s -B kvp -o tensors_%d.nhdr -knownB0 true",
    filename, random_integer);

  //m_DiffusionImages;
  if(m_EstimateErrorImage)
  {
    sprintf( command, "%s -ee error_image_%d.nhdr", command, random_integer);
  }

  if(m_Sigma != -19191919)
  {
    sprintf( command, "%s -sigma %f", command, m_Sigma);
  }

  switch(m_EstimationMethod)
  {
  case TeemTensorEstimationMethodsLLS:
    sprintf( command, "%s -est lls", command);
    break;
  case TeemTensorEstimationMethodsMLE:
    sprintf( command, "%s -est mle", command);
    break;
  case TeemTensorEstimationMethodsNLS:
    sprintf( command, "%s -est nls", command);
    break;
  case TeemTensorEstimationMethodsWLS:
    sprintf( command, "%s -est wls", command);
    break;
  }

  sprintf( command, "%s -wlsi %d", command, m_NumIterations);

  if(m_ConfidenceThreshold != -19191919.0)
  {
    sprintf( command, "%s -t %f", command, m_ConfidenceThreshold);
  }

  sprintf( command, "%s -soft %f", command, m_ConfidenceFuzzyness);
  sprintf( command, "%s -mv %f", command, m_MinPlausibleValue);

  // call tend estim command
  std::cout << "Calling <" << command << ">" << std::endl;
  int success = system(command);
  if(!success)
  {
    MITK_ERROR << "system command could not be called!";
  }

  remove(filename);
  sprintf( filename, "dwi_%d.raw", random_integer);
  remove(filename);

  // change kind from tensor to vector
  sprintf( filename, "tensors_%d.nhdr", random_integer);
  file_replace(filename,"3D-masked-symmetric-matrix","vector");

  mitk::LocaleSwitch localeSwitch("C");
  // read result as mitk::Image and provide it in m_Output
  typedef itk::ImageFileReader<VectorImageType> FileReaderType;
  typename FileReaderType::Pointer reader = FileReaderType::New();
  reader->SetFileName(filename);
  reader->Update();
  typename VectorImageType::Pointer vecImage = reader->GetOutput();

  remove(filename);
  sprintf( filename, "tensors_%d.raw", random_integer);
  remove(filename);

  typename ItkTensorImageType::Pointer itkTensorImage = ItkTensorImageType::New();
  itkTensorImage->SetSpacing( vecImage->GetSpacing() );   // Set the image spacing
  itkTensorImage->SetOrigin( vecImage->GetOrigin() );     // Set the image origin
  itkTensorImage->SetDirection( vecImage->GetDirection() );  // Set the image direction
  itkTensorImage->SetLargestPossibleRegion( vecImage->GetLargestPossibleRegion() );
  itkTensorImage->SetBufferedRegion( vecImage->GetLargestPossibleRegion() );
  itkTensorImage->SetRequestedRegion( vecImage->GetLargestPossibleRegion() );
  itkTensorImage->Allocate();

  itk::ImageRegionIterator<VectorImageType> it(vecImage,
    vecImage->GetLargestPossibleRegion());

  itk::ImageRegionIterator<ItkTensorImageType> it2(itkTensorImage,
    itkTensorImage->GetLargestPossibleRegion());
  it2 = it2.Begin();

  //#pragma omp parallel private (it)
  {
    for(it=it.Begin();!it.IsAtEnd(); ++it, ++it2)
    {
      //#pragma omp single nowait
      {
        VectorType vec = it.Get();
        TensorType tensor;
        for(int i=1;i<7;i++)
          tensor[i-1] = vec[i] * vec[0];
        it2.Set( tensor );
      }
    } // end for
  } // end ompparallel

  m_OutputItk = mitk::TensorImage::New();
  m_OutputItk->InitializeByItk(itkTensorImage.GetPointer());
  m_OutputItk->SetVolume( itkTensorImage->GetBufferPointer() );

  // in case: read resulting error-image and provide it in m_ErrorImage
  if(m_EstimateErrorImage)
  {
    // open error image here
  }

}
Beispiel #21
0
void KviMainWindow::fillToolBarsPopup(QMenu * p)
{
	p->clear();

	disconnect(p, SIGNAL(triggered(QAction *)), this, SLOT(toolbarsPopupSelected(QAction *))); // just to be sure
	connect(p, SIGNAL(triggered(QAction *)), this, SLOT(toolbarsPopupSelected(QAction *)));

	QAction * pAction = nullptr;
	int cnt = 0;

	KviModuleExtensionDescriptorList * l = g_pModuleExtensionManager->getExtensionList("toolbar");
	if(l)
	{
		for(KviModuleExtensionDescriptor * d = l->first(); d; d = l->next())
		{
			QString label = __tr2qs("Show %1").arg(d->visibleName());
			if(d->icon())
				pAction = p->addAction(*(d->icon()), label);
			else
				pAction = p->addAction(label);
			pAction->setCheckable(true);
			pAction->setChecked(moduleExtensionToolBar(d->id()));
			pAction->setData(d->id());
			cnt++;
		}
	}

	// FIXME: Should this display "Hide %1" when the toolbar is already visible ?
	KviPointerHashTableIterator<QString, KviCustomToolBarDescriptor> it2(*(KviCustomToolBarManager::instance()->descriptors()));
	if(it2.current())
	{
		if(cnt > 0)
			p->addSeparator();

		while(KviCustomToolBarDescriptor * d = it2.current())
		{
			QString label = __tr2qs("Show %1").arg(d->label());
			QString ico = d->iconId();
			if(!ico.isEmpty())
			{
				QPixmap * pix = g_pIconManager->getImage(d->iconId());
				if(pix)
				{
					pAction = p->addAction(*pix, label);
				}
				else
				{
					pAction = p->addAction(label);
				}
			}
			else
			{
				pAction = p->addAction(label);
			}
			pAction->setData(d->internalId());
			pAction->setCheckable(true);
			pAction->setChecked(d->toolBar());
			++it2;
			cnt++;
		}
	}

	if(cnt > 0)
		p->addSeparator();

	p->addAction(
	    *(g_pIconManager->getSmallIcon(KviIconManager::ToolBarEditor)),
	    __tr2qs("Customize..."),
	    this,
	    SLOT(customizeToolBars()));
}
Beispiel #22
0
inline BOOL MFramework::Init()
{
    /* Get all the modules list and init  */
    std::string dir;

    //dir = Path::current();
    std::string pluginPath = GetPluginPath() + "/mplugins/";

    dir = pluginPath;

    try
    {
        DirectoryIterator it(dir);
        DirectoryIterator end;
        while (it != end)
        {
            /* loop for each dir */
            if (it->isDirectory() == true)
            {
                astring strName = it->path();
                try
                {
                    DirectoryIterator it2(it->path());
                    DirectoryIterator end2;

                    while (it2 != end2)
                    {
                        astring strName2 = it2->path();
                        if (it2->path().find("mplugin") != std::string::npos)
                        {
                            /* Find a plugin and call mmodule to add */
                            astring strPluginName = it2->path();
                            MiningModule * pModule =
                                new MiningModule(strPluginName, m_pFactory);
                            if (pModule && pModule->Valid() == TRUE)
                            {
                                pModule->Init();
                                m_MModules[strPluginName] = pModule;
                            }

                        }
                        ++it2;
                    }
                }
                catch (Poco::Exception& exc)
                {
                    continue;
                }
            }

            ++it;
        }
    }
    catch (Poco::Exception& exc)
    {
        std::cerr << exc.displayText() << std::endl;
        VDC_DEBUG( "Plugin init error \n");

        return FALSE;
    }

    return TRUE;
}
Beispiel #23
0
std::array<unsigned long,vcp<4,1,1>::element_count()> const vcp<4,1,1>::generate_vector( const_vertex_iterator v1, const_vertex_iterator v2 ) {
	std::array<unsigned long,element_count()> counts = {{0}};
	
	std::size_t v1v2( V1V2 * OUT * g.out_edge_exists( v1, v2 ) + V1V2 * IN * g.in_edge_exists( v1, v2 ) );
	
	unsigned long connections( 0 );
	unsigned long amutuals( 0 );
	unsigned long gaps( 0 );
	
	// compose ordered list of v3 candidates
	const_edge_iterator v1_out_neighbors_it( g.out_neighbors_begin( v1 ) );
	const_edge_iterator v1_out_neighbors_end( g.out_neighbors_end( v1 ) );
	const_edge_iterator v1_in_neighbors_it( g.in_neighbors_begin( v1 ) );
	const_edge_iterator v1_in_neighbors_end( g.in_neighbors_end( v1 ) );
	const_edge_iterator v2_out_neighbors_it( g.out_neighbors_begin( v2 ) );
	const_edge_iterator v2_out_neighbors_end( g.out_neighbors_end( v2 ) );
	const_edge_iterator v2_in_neighbors_it( g.in_neighbors_begin( v2 ) );
	const_edge_iterator v2_in_neighbors_end( g.in_neighbors_end( v2 ) );
	assert( MAX_NEIGHBORS > (v1_out_neighbors_end-v1_out_neighbors_it)+(v1_in_neighbors_end-v1_in_neighbors_it)+(v2_out_neighbors_end-v2_out_neighbors_it)+(v2_in_neighbors_end-v2_in_neighbors_it) );
	std::pair<const_vertex_iterator,unsigned short>* v3Vertices_begin( &v3Vertices[0] );
	std::pair<const_vertex_iterator,unsigned short>* v3Vertices_end( &v3Vertices[0] );
	std::pair<const_edge_iterator,directedness_value> min1( next_union_element( v1_out_neighbors_it, v1_out_neighbors_end, v1_in_neighbors_it, v1_in_neighbors_end ) );
	std::pair<const_edge_iterator,directedness_value> min2( next_union_element( v2_out_neighbors_it, v2_out_neighbors_end, v2_in_neighbors_it, v2_in_neighbors_end ) );
	while( min1.first != v1_in_neighbors_end && min2.first != v2_in_neighbors_end ) {
		if( g.target_of( min1.first ) < g.target_of( min2.first ) ) {
			if( g.target_of( min1.first ) != v2 ) {
				++connections;
				++gaps;
				if( min1.second < 3 ) {
					++amutuals;
				}
				v3Vertices_end->first = g.target_of( min1.first );
				v3Vertices_end->second = v1v2 + V1V3 * min1.second;
				++v3Vertices_end;
			}
			min1 = next_union_element( v1_out_neighbors_it, v1_out_neighbors_end, v1_in_neighbors_it, v1_in_neighbors_end );
		} else if( g.target_of( min1.first ) > g.target_of( min2.first ) ) {
			if( g.target_of( min2.first ) != v1 ) {
				++connections;
				++gaps;
				if( min2.second < 3 ) {
					++amutuals;
				}
				v3Vertices_end->first = g.target_of( min2.first );
				v3Vertices_end->second = v1v2 + V2V3 * min2.second;
				++v3Vertices_end;
			}
			min2 = next_union_element( v2_out_neighbors_it, v2_out_neighbors_end, v2_in_neighbors_it, v2_in_neighbors_end );
		} else { // the next neighbor is shared by both v1 and v2, so it cannot be either and we do not need to check to exclude it
			connections += 2;
			if( min1.second < 3 ) {
				++amutuals;
			}
			if( min2.second < 3 ) {
				++amutuals;
			}
		 	v3Vertices_end->first = g.target_of( min1.first );
		 	v3Vertices_end->second = v1v2 + V1V3 * min1.second + V2V3 * min2.second;
			++v3Vertices_end;
			min1 = next_union_element( v1_out_neighbors_it, v1_out_neighbors_end, v1_in_neighbors_it, v1_in_neighbors_end );
			min2 = next_union_element( v2_out_neighbors_it, v2_out_neighbors_end, v2_in_neighbors_it, v2_in_neighbors_end );
		}
	}
	while( min1.first != v1_in_neighbors_end ) {
		if( g.target_of( min1.first ) != v2 ) {
			++connections;
			++gaps;
			if( min1.second < 3 ) {
				++amutuals;
			}
			v3Vertices_end->first = g.target_of( min1.first );
			v3Vertices_end->second = v1v2 + V1V3 * min1.second;
			++v3Vertices_end;
		}
		min1 = next_union_element( v1_out_neighbors_it, v1_out_neighbors_end, v1_in_neighbors_it, v1_in_neighbors_end );
	}
	while( min2.first != v2_in_neighbors_end ) {
		if( g.target_of( min2.first ) != v1 ) {
			++connections;
			++gaps;
			if( min2.second < 3 ) {
				++amutuals;
			}
			v3Vertices_end->first = g.target_of( min2.first );
			v3Vertices_end->second = v1v2 + V2V3 * min2.second;
			++v3Vertices_end;
		}
		min2 = next_union_element( v2_out_neighbors_it, v2_out_neighbors_end, v2_in_neighbors_it, v2_in_neighbors_end );
	}

	unsigned long v3_count( v3Vertices_end-v3Vertices_begin );
	unsigned long v4_count( 0 );
	for( std::pair<const_vertex_iterator,unsigned short>* it1( v3Vertices_begin ); it1 != v3Vertices_end; ++it1 ) { // for each v3 vertex computed above
		const_edge_iterator v3_out_neighbors_it( g.out_neighbors_begin( it1->first ) );
		const_edge_iterator v3_out_neighbors_end( g.out_neighbors_end( it1->first ) );
		const_edge_iterator v3_in_neighbors_it( g.in_neighbors_begin( it1->first ) );
		const_edge_iterator v3_in_neighbors_end( g.in_neighbors_end( it1->first ) );
		unsigned long v4_local_count( 0 ); // keep track of how many v4 vertices are only the result of the neighbors of this v3
		std::pair<const_edge_iterator,directedness_value> min( next_union_element( v3_out_neighbors_it, v3_out_neighbors_end, v3_in_neighbors_it, v3_in_neighbors_end ) );
		for( std::pair<const_vertex_iterator,unsigned short>* it2( v3Vertices_begin ); it2 != v3Vertices_end; ++it2 ) {	
			while( min.first != v3_in_neighbors_end && g.target_of( min.first ) < it2->first ) {
				if( g.target_of( min.first ) != v1 && g.target_of( min.first ) != v2 ) {
					++v4_local_count;
					if( min.second < 3 ) {
						++amutuals;
					}
					++counts[ element_address( it1->second + V3V4 * min.second ) ];
				}
				min = next_union_element( v3_out_neighbors_it, v3_out_neighbors_end, v3_in_neighbors_it, v3_in_neighbors_end );
			}
			if( min.first == v3_in_neighbors_end || g.target_of( min.first ) > it2->first ) {
				if( it1->first < it2->first ) {
					unsigned short temp( it2->second - v1v2 );
					std::size_t contrib( 0 );
					contrib += V1V4 * (temp % V2V3);
					contrib += V2V4 * (temp / V2V3);
					++gaps;
					++counts[ element_address( it1->second + contrib ) ];
				}
			} else {
				if( it1->first < it2->first ) {
					unsigned short temp( it2->second - v1v2 );
					std::size_t contrib( 0 );
					contrib += V1V4 * (temp % V2V3);
					contrib += V2V4 * (temp / V2V3);
					++connections;
					if( min.second < 3 ) {
						++amutuals;
					}
					++counts[ element_address( it1->second + contrib + V3V4 * min.second  ) ];
				}
				min = next_union_element( v3_out_neighbors_it, v3_out_neighbors_end, v3_in_neighbors_it, v3_in_neighbors_end );
			}
		}
		while( min.first != v3_in_neighbors_end ) {
			if( g.target_of( min.first ) != v1 && g.target_of( min.first ) != v2 ) {
				++v4_local_count;
				if( min.second < 3 ) {
					++amutuals;
				}
				++counts[ element_address( it1->second + V3V4 * min.second ) ];
			}
			min = next_union_element( v3_out_neighbors_it, v3_out_neighbors_end, v3_in_neighbors_it, v3_in_neighbors_end );
		}
		v4_count += v4_local_count;
		connections += v4_local_count;
		gaps += 2*v4_local_count;
		counts[ element_address( it1->second ) ] += g.vertex_count() - 2 - v3_count - v4_local_count;
	}
		
	// account for the least connected substructures
	counts[ element_address( v1v2+OUT*V3V4) ] = this->amutualPairs - (amutuals + static_cast<bool>(v1v2)); // out and in versions are isomorphically equivalent and do not need to be counted separately
	counts[ element_address( v1v2+BOTH*V3V4 ) ] = this->mutualPairs - (connections - amutuals);
	counts[ element_address( v1v2 ) ] = unconnected_pairs - (gaps + !static_cast<bool>(v1v2)) - (2 + v3_count) * (g.vertex_count() - 2 - v3_count) + 3 * v4_count;
	
	return counts;
}
    void SymmetricForcesDemonsRegistration::GenerateData2( const itk::Image<TPixel, VImageDimension>* itkImage1)
  {
    typedef typename itk::Image< TPixel, VImageDimension >  FixedImageType;
    typedef typename itk::Image< TPixel, VImageDimension >  MovingImageType;

    typedef float InternalPixelType;
    typedef typename itk::Image< InternalPixelType, VImageDimension > InternalImageType;
    typedef typename itk::CastImageFilter< FixedImageType,
                                  InternalImageType > FixedImageCasterType;
    typedef typename itk::CastImageFilter< MovingImageType,
                                  InternalImageType > MovingImageCasterType;
    typedef typename itk::Vector< float, VImageDimension >    VectorPixelType;
    typedef typename itk::Image<  VectorPixelType, VImageDimension > DeformationFieldType;
    typedef typename itk::SymmetricForcesDemonsRegistrationFilter<
                                  InternalImageType,
                                  InternalImageType,
                                  DeformationFieldType>   RegistrationFilterType;
    typedef typename itk::WarpImageFilter<
                            MovingImageType,
                            MovingImageType,
                            DeformationFieldType  >     WarperType;
    typedef typename itk::LinearInterpolateImageFunction<
                                    MovingImageType,
                                    double          >  InterpolatorType;

    typedef  TPixel  OutputPixelType;
    typedef typename itk::Image< OutputPixelType, VImageDimension > OutputImageType;
    typedef typename itk::CastImageFilter<
                          MovingImageType,
                          OutputImageType > CastFilterType;
    typedef typename itk::ImageFileWriter< OutputImageType >  WriterType;
    typedef typename itk::ImageFileWriter< DeformationFieldType >  FieldWriterType;

    typename FixedImageType::Pointer fixedImage = FixedImageType::New();
    mitk::CastToItkImage(m_ReferenceImage, fixedImage);
    typename MovingImageType::ConstPointer movingImage = itkImage1;

    if (fixedImage.IsNotNull() && movingImage.IsNotNull())
    {
      typename RegistrationFilterType::Pointer filter = RegistrationFilterType::New();

      this->AddStepsToDo(4);
      itk::ReceptorMemberCommand<SymmetricForcesDemonsRegistration>::Pointer command = itk::ReceptorMemberCommand<SymmetricForcesDemonsRegistration>::New();
      command->SetCallbackFunction(this, &SymmetricForcesDemonsRegistration::SetProgress);
      filter->AddObserver( itk::IterationEvent(), command );

      typename FixedImageCasterType::Pointer fixedImageCaster = FixedImageCasterType::New();
      fixedImageCaster->SetInput(fixedImage);
      filter->SetFixedImage( fixedImageCaster->GetOutput() );
      typename MovingImageCasterType::Pointer movingImageCaster = MovingImageCasterType::New();
      movingImageCaster->SetInput(movingImage);
      filter->SetMovingImage(movingImageCaster->GetOutput());
      filter->SetNumberOfIterations( m_Iterations );
      filter->SetStandardDeviations( m_StandardDeviation );
      filter->Update();

      typename WarperType::Pointer warper = WarperType::New();
      typename InterpolatorType::Pointer interpolator = InterpolatorType::New();

      warper->SetInput( movingImage );
      warper->SetInterpolator( interpolator );
      warper->SetOutputSpacing( fixedImage->GetSpacing() );
      warper->SetOutputOrigin( fixedImage->GetOrigin() );
      warper->SetDisplacementField( filter->GetOutput() );
      warper->Update();
      typename WriterType::Pointer      writer =  WriterType::New();
      typename CastFilterType::Pointer  caster =  CastFilterType::New();

      writer->SetFileName( m_ResultName );

      caster->SetInput( warper->GetOutput() );
      writer->SetInput( caster->GetOutput()   );
      if(m_SaveResult)
      {
        writer->Update();
      }
      Image::Pointer outputImage = this->GetOutput();
      mitk::CastToMitkImage( warper->GetOutput(), outputImage );

      if (VImageDimension == 2)
      {
        typedef DeformationFieldType  VectorImage2DType;
        typedef typename DeformationFieldType::PixelType Vector2DType;

        typename VectorImage2DType::ConstPointer vectorImage2D = filter->GetOutput();

        typename VectorImage2DType::RegionType  region2D = vectorImage2D->GetBufferedRegion();
        typename VectorImage2DType::IndexType   index2D  = region2D.GetIndex();
        typename VectorImage2DType::SizeType    size2D   = region2D.GetSize();


        typedef typename itk::Vector< float,       3 >  Vector3DType;
        typedef typename itk::Image< Vector3DType, 3 >  VectorImage3DType;

        typedef typename itk::ImageFileWriter< VectorImage3DType > WriterType;

        WriterType::Pointer writer3D = WriterType::New();

        VectorImage3DType::Pointer vectorImage3D = VectorImage3DType::New();

        VectorImage3DType::RegionType  region3D;
        VectorImage3DType::IndexType   index3D;
        VectorImage3DType::SizeType    size3D;

        index3D[0] = index2D[0];
        index3D[1] = index2D[1];
        index3D[2] = 0;

        size3D[0]  = size2D[0];
        size3D[1]  = size2D[1];
        size3D[2]  = 1;

        region3D.SetSize( size3D );
        region3D.SetIndex( index3D );

        typename VectorImage2DType::SpacingType spacing2D   = vectorImage2D->GetSpacing();
        VectorImage3DType::SpacingType spacing3D;

        spacing3D[0] = spacing2D[0];
        spacing3D[1] = spacing2D[1];
        spacing3D[2] = 1.0;

        vectorImage3D->SetSpacing( spacing3D );

        vectorImage3D->SetRegions( region3D );
        vectorImage3D->Allocate();

        typedef typename itk::ImageRegionConstIterator< VectorImage2DType > Iterator2DType;

        typedef typename itk::ImageRegionIterator< VectorImage3DType > Iterator3DType;

        Iterator2DType  it2( vectorImage2D, region2D );
        Iterator3DType  it3( vectorImage3D, region3D );

        it2.GoToBegin();
        it3.GoToBegin();

        Vector2DType vector2D;
        Vector3DType vector3D;

        vector3D[2] = 0; // set Z component to zero.

        while( !it2.IsAtEnd() )
        {
          vector2D = it2.Get();
          vector3D[0] = vector2D[0];
          vector3D[1] = vector2D[1];
          it3.Set( vector3D );
          ++it2;
          ++it3;
        }

        writer3D->SetInput( vectorImage3D );
        m_DeformationField = vectorImage3D;

        writer3D->SetFileName( m_FieldName );

        try
        {
          if(m_SaveField)
          {
            writer3D->Update();
          }
        }
        catch( itk::ExceptionObject & excp )
        {
          MITK_ERROR << excp << std::endl;
        }
      }
      else
      {
        typename FieldWriterType::Pointer      fieldwriter =  FieldWriterType::New();
        fieldwriter->SetFileName( m_FieldName );
        fieldwriter->SetInput( filter->GetOutput() );
        //m_DeformationField = filter->GetOutput();
        m_DeformationField = (itk::Image<itk::Vector<float, 3>,3> *)(filter->GetOutput()); //see BUG #3732
        if(m_SaveField)
        {
          fieldwriter->Update();
        }

      }
      this->SetRemainingProgress(4);
    }
  }
void rw_new_tests() {

  // valid hashdigest values
  hash_t k1;
  hash_t k2;
  to_key(1, k1);
  to_key(2, k2);

  hashdb_element_t element;

  // create working changes object
  hashdb_changes_t changes;

  // open new hashdb manager
  hashdb_manager_t manager(temp_dir, RW_NEW);

  // ************************************************************
  // initial state
  // ************************************************************
  // check initial size
  BOOST_TEST_EQ(manager.map_size(), 0);

  // check initial iterator
  BOOST_TEST_EQ((manager.begin() == manager.end()), true);

  // ************************************************************
  // insert, remove, and hashdb_changes variables
  // note: some of these tests additionally test failure ordering
  // ************************************************************
  // insert valid
  element = hashdb_element_t(k1, 4096, "rep1", "file1", 0);
  manager.insert(element, changes);
  BOOST_TEST_EQ(changes.hashes_inserted, 1);
  BOOST_TEST_EQ(manager.map_size(), 1);

  // insert, mismatched hash block size
  element = hashdb_element_t(k1, 5, "rep1", "file1", 0);
  manager.insert(element, changes);
  BOOST_TEST_EQ(changes.hashes_not_inserted_mismatched_hash_block_size, 1);
  BOOST_TEST_EQ(manager.map_size(), 1);

  // insert, file offset not aligned
  element = hashdb_element_t(k1, 4096, "rep1", "file1", 5);
  manager.insert(element, changes);
  BOOST_TEST_EQ(changes.hashes_not_inserted_invalid_byte_alignment, 1);
  BOOST_TEST_EQ(manager.map_size(), 1);

  // insert, no exact duplicates
  element = hashdb_element_t(k2, 4096, "rep1", "file1", 4096);
  manager.insert(element, changes);
  BOOST_TEST_EQ(changes.hashes_inserted, 2);
  BOOST_TEST_EQ(manager.map_size(), 2);
  manager.insert(element, changes);
  BOOST_TEST_EQ(changes.hashes_not_inserted_duplicate_element, 1);
  BOOST_TEST_EQ(manager.map_size(), 2);

  // max 4 elements of same hash
  element = hashdb_element_t(k2, 4096, "rep1", "file1", 0);
  manager.insert(element, changes);
  element = hashdb_element_t(k2, 4096, "rep1", "file2", 4096);
  manager.insert(element, changes);
  element = hashdb_element_t(k2, 4096, "rep2", "file1", 4096);
  manager.insert(element, changes);
  element = hashdb_element_t(k2, 4096, "rep3", "file1", 4096); // too many
  manager.insert(element, changes);
  BOOST_TEST_EQ(changes.hashes_not_inserted_exceeds_max_duplicates, 1);
  BOOST_TEST_EQ(manager.map_size(), 5);

  // delete elements of same hash
  element = hashdb_element_t(k2, 4096, "rep3", "file1", 4096); // not present
  manager.remove(element, changes);
  BOOST_TEST_EQ(changes.hashes_removed, 0);
  BOOST_TEST_EQ(changes.hashes_not_removed_no_element, 1);
  BOOST_TEST_EQ(manager.map_size(), 5);
  element = hashdb_element_t(k2, 4096, "rep1", "file1", 4096);
  manager.remove(element, changes);
  element = hashdb_element_t(k2, 4096, "rep1", "file1", 0);
  manager.remove(element, changes);
  element = hashdb_element_t(k2, 4096, "rep1", "file2", 4096);
  manager.remove(element, changes);
  element = hashdb_element_t(k2, 4096, "rep2", "file1", 4096);
  manager.remove(element, changes);
  BOOST_TEST_EQ(changes.hashes_removed, 4);
  BOOST_TEST_EQ(changes.hashes_not_removed_no_element, 1);
  BOOST_TEST_EQ(manager.map_size(), 1);

  // remove, entry of single element
  element = hashdb_element_t(k1, 4096, "rep1", "file1", 0);
  manager.remove(element, changes);
  BOOST_TEST_EQ(changes.hashes_removed, 5);
  BOOST_TEST_EQ(changes.hashes_not_removed_no_element, 1);
  BOOST_TEST_EQ(manager.map_size(), 0);

  // remove, no element
  element = hashdb_element_t(k1, 4096, "rep1", "file1", 0);
  manager.remove(element, changes);
  BOOST_TEST_EQ(changes.hashes_not_removed_no_element, 2);
  BOOST_TEST_EQ(manager.map_size(), 0);

  // insert, valid, previously deleted
  element = hashdb_element_t(k1, 4096, "rep1", "file1", 0);
  manager.insert(element, changes);
  BOOST_TEST_EQ(changes.hashes_inserted, 6);

  // remove_key successfully
  manager.remove_key(k1, changes);
  BOOST_TEST_EQ(changes.hashes_removed, 6);

  // add two of same key then remove_key successfully
  element = hashdb_element_t(k2, 4096, "rep1", "file1", 0);
  manager.insert(element, changes);
  element = hashdb_element_t(k2, 4096, "rep1", "file2", 4096);
  manager.insert(element, changes);
  manager.remove_key(k2, changes);
  BOOST_TEST_EQ(changes.hashes_removed, 8);

  // remove_key no hash
  manager.remove_key(k1, changes);
  BOOST_TEST_EQ(changes.hashes_not_removed_no_hash, 1);

  // remove, mismatched hash block size
  element = hashdb_element_t(k1, 5, "rep1", "file1", 0);
  manager.remove(element, changes);
  BOOST_TEST_EQ(changes.hashes_not_removed_mismatched_hash_block_size, 1);

  // remove, file offset not aligned
  element = hashdb_element_t(k1, 4096, "rep1", "file1", 5);
  manager.remove(element, changes);
  BOOST_TEST_EQ(changes.hashes_not_removed_invalid_byte_alignment, 1);

  // remove, no element
  element = hashdb_element_t(k2, 4096, "rep1", "file1", 0);
  manager.remove(element, changes);
  BOOST_TEST_EQ(changes.hashes_not_removed_no_element, 3);

  // ************************************************************
  // find, find_count, size, iterator
  // ************************************************************
  BOOST_TEST_EQ(manager.find_count(k1), 0);
  BOOST_TEST_EQ(manager.find_count(k1), 0);

  // setup with one element to make iterator simple
  element = hashdb_element_t(k1, 4096, "rep1", "file1", 0);
  manager.insert(element, changes);
  BOOST_TEST_EQ(manager.map_size(), 1);
  hashdb_iterator_t it(manager.begin());
  BOOST_TEST_EQ(it->key, k1);
  BOOST_TEST_EQ(it->hash_block_size, 4096);
  BOOST_TEST_EQ(it->repository_name, "rep1");
  BOOST_TEST_EQ(it->filename, "file1");
  BOOST_TEST_EQ(it->file_offset, 0);
  BOOST_TEST_EQ((*it).file_offset, 0);
  ++it;
  BOOST_TEST_EQ((it == manager.end()), true);

  // setup with two elements under one key and one element under another key
  element = hashdb_element_t(k1, 4096, "second_rep1", "file1", 0);
  manager.insert(element, changes);
  element = hashdb_element_t(k2, 4096, "rep1", "file1", 0);
  manager.insert(element, changes);

  BOOST_TEST_EQ(manager.find_count(k1), 2);
  BOOST_TEST_EQ(manager.map_size(), 3);

  hashdb_iterator_t it2(manager.begin());
  ++it2;
  it2++;
  ++it2;

  BOOST_TEST_EQ((it2 == manager.end()), true);

  // check iterator pair from find
  std::pair<hashdb_iterator_t, hashdb_iterator_t> it_pair;
  it_pair = manager.find(k1);
  ++it_pair.first;
  ++it_pair.first;
  BOOST_TEST_EQ((it_pair.first == it_pair.second), true);
  it_pair = manager.find(k1);
  ++it_pair.first;
  ++it_pair.first;
  BOOST_TEST_EQ((it_pair.first == it_pair.second), true);

  // ************************************************************
  // install lots of data
  // ************************************************************
  // populate with 1,000,000 entries
  hash_t key;
  BOOST_TEST_EQ(manager.map_size(), 3);
  for (uint64_t n=0; n< 1000000; ++n) {
    to_key(n+1000000, key);
    element = hashdb_element_t(key, 4096, "rep1", "file1", 0);
    manager.insert(element, changes);
  }
  BOOST_TEST_EQ(manager.map_size(), 1000003);
}
Beispiel #26
0
EditDinamycItemDlg::EditDinamycItemDlg(QWidget *parent) :
    QDialog(parent)
{
    if(!isSet)
    {
        QSqlQuery x(QSqlDatabase::database("grupo"));
        if(x.exec("Select valor_stock FROM articulos"))
            while (x.next()) {
                qDebug() << "valor_stock" << x.record().value("valor_stock");
            }
        else
            qDebug() << x.lastError();
        _zonas << "General" << "Empresa";

        //TODO cambiar dentro de Maya

        QStringList groupTables;
        QSqlQuery q(Configuracion_global->groupDB);
        q.exec("show tables");
        while(q.next())
            groupTables << q.record().value(0).toString();

        _tablas.insert("General",groupTables);

        QStringListIterator it(groupTables);
        while(it.hasNext())
        {
            QString tabla = it.next();
            QStringList campos;
            QString s = QString("show columns from %1").arg(tabla);
            q.exec(s);
            while(q.next())
                campos << q.record().value(0).toString();
            _campos.insert(tabla,campos);            
        }

        QStringList empTables;
        QSqlQuery q2(Configuracion_global->empresaDB);
        q2.exec("show tables");
        while(q2.next())
            empTables << q2.record().value(0).toString();

        _tablas.insert("Empresa",empTables);

        QStringListIterator it2(empTables);
        while(it2.hasNext())
        {
            QString tabla = it2.next();
            QStringList campos;
            QString s = QString("show columns from %1").arg(tabla);
            q2.exec(s);
            while(q2.next())
                campos << q2.record().value(0).toString();


            _campos.insert(tabla,campos);
        }

        isSet = true;
    }
}
Beispiel #27
0
void RegionLoad::UpdateView()
{
	/*
	Tests the intersection of all regions with the view (if moved) 
	Call CreateActors of the areas that began to intercept and    
	DestroyActors of the areas that are not more intercepting.
	*/
	
	//The coordinates changes solve the bug in activation-problem_view_parent.ged
	//(don't load left region)

	//Make sure view don't will shake
	KrImage *pImageView = GameControl::Get()->GetViewActor()->getImage();
	Axis *pAxis = GameControl::Get()->GetAxis();

	if(pImageView->IsInvalid(true)) 
	{
		//Solve the alpha14.ged bug
		pImageView->CalcCompositeTransform();
		engine->Tree()->Walk(pImageView, true, true);
	}
	else
	{
		pImageView->CalcTransform();
	}

	//Get view bounds
	KrRect rectView = pImageView->Bounds(), viewPos;

	//Get view in screen and axis coordinates
	KrVector2T< GlFixed > screen, axis;
	pImageView->ObjectToScreen(0, 0, &screen);
	pAxis->getImage()->ScreenToObject( screen.x.ToInt(), screen.y.ToInt(), &axis );

	//Make sure rect is (0, 0, ...)
	rectView.Translate(-rectView.xmin, -rectView.ymin);

	//Translate to correct position
	rectView.Translate(axis.x.ToInt(), axis.y.ToInt());


	//Solve the bug: "PocketPC don't load checkers.ged"
	viewPos.Set(rectView.xmin, rectView.ymin, 
				//zeroViewPos.x.ToInt(), zeroViewPos.y.ToInt(),
				0, 0);

	

	if(viewPos != viewPosAnt)
	{		
		MapRegions createdRegions, destroyedRegions;

/*#ifdef DEBUG
		GLOUTPUT( " View pos: (%ld, %ld)\n",  rectView.xmin, rectView.ymin);
#endif*/

		MapRegionsIterator it(regions);
		RegionLoad *pRegion;
		for( it.Begin(); !it.Done(); it.Next() )
		{
			pRegion = *it.Key();

			pRegion->getImage()->CalcTransform();
			KrRect rectRegion = pRegion->getImage()->Bounds();
			rectRegion.Translate(-rectRegion.xmin, -rectRegion.ymin);

			//To axis coordinate
			pRegion->getImage()->ObjectToScreen(0, 0, &screen);
			pAxis->getImage()->ScreenToObject( screen.x.ToInt(), screen.y.ToInt(), &axis );
			rectRegion.Translate(axis.x.ToInt(), axis.y.ToInt());

			//View and region in axis coordinates
			if(rectView.Intersect(rectRegion))
			{
				if(!pRegion->bRegionInView)
				{
					createdRegions.Add(pRegion, 1);
				}				
			}
			else
			{
				if(pRegion->bRegionInView)
				{
					destroyedRegions.Add(pRegion, 1);				
				}
			}
		}

		//Destroy actors from regions outside the view
		//Solve the Move to Region.ged when add the 'sad' actor to two default regions 
		//(some times)

		MapRegionsIterator it1(destroyedRegions);
		
		for(it1.Begin(); !it1.Done(); it1.Next())
		{
			pRegion = *it1.Key();
			
			pRegion->DestroyActors();
			if(defaultRegion == pRegion)
				InvalidateDefaultRegion();
		}

		//Call OnCreate after destroy old actors
		//Solve the Move to Region 2.ged actor move to a wrong position
		MapRegionsIterator it2(createdRegions);
		
		for(it2.Begin(); !it2.Done(); it2.Next())
		{
			pRegion = *it2.Key();			
			RegionLoad *pOldDefaultRegion = defaultRegion;
			SetDefaultRegion(pRegion);
			
			pRegion->CreateActors();
					
			RemoveCommonActorsFromOldDefaultRegion(pOldDefaultRegion);
		}
		
		viewPosAnt = viewPos;
	}






}
/**
 * Regenerate the QTreeWidget participant list of a Chat Lobby
 *
 * Show yellow icon for muted Participants
 */
void ChatLobbyDialog::updateParticipantsList()
{
    ChatLobbyInfo linfo;

    if(rsMsgs->getChatLobbyInfo(lobbyId,linfo))
    {
        ChatLobbyInfo cliInfo=linfo;
        QList<QTreeWidgetItem*>  qlOldParticipants=ui.participantsList->findItems("*",Qt::MatchWildcard,COLUMN_ID);

        foreach(QTreeWidgetItem *qtwiCur,qlOldParticipants)
            if(cliInfo.gxs_ids.find(RsGxsId((*qtwiCur).text(COLUMN_ID).toStdString())) == cliInfo.gxs_ids.end())
            {
                //Old Participant go out, remove it
                int index = ui.participantsList->indexOfTopLevelItem(qtwiCur);
                delete ui.participantsList->takeTopLevelItem(index);
            }

        for (std::map<RsGxsId,time_t>::const_iterator it2(linfo.gxs_ids.begin()); it2 != linfo.gxs_ids.end(); ++it2)
        {
            QString participant = QString::fromUtf8( (it2->first).toStdString().c_str() );

            QList<QTreeWidgetItem*>  qlFoundParticipants=ui.participantsList->findItems(participant,Qt::MatchExactly,COLUMN_ID);
            GxsIdRSTreeWidgetItem *widgetitem;

            if (qlFoundParticipants.count()==0)
            {
                // TE: Add Wigdet to participantsList with Checkbox, to mute Participant

                widgetitem = new GxsIdRSTreeWidgetItem(mParticipantCompareRole,GxsIdDetails::ICON_TYPE_AVATAR);
                widgetitem->setId(it2->first,COLUMN_NAME, true) ;
                //widgetitem->setText(COLUMN_NAME, participant);
                // set activity time to the oast so that the peer is marked as inactive
                widgetitem->setText(COLUMN_ACTIVITY,QString::number(time(NULL) - timeToInactivity));
                widgetitem->setText(COLUMN_ID,QString::fromStdString(it2->first.toStdString()));

                ui.participantsList->addTopLevelItem(widgetitem);
            }
            else
                widgetitem = dynamic_cast<GxsIdRSTreeWidgetItem*>(qlFoundParticipants.at(0));

            if (isParticipantMuted(it2->first)) {
                widgetitem->setTextColor(COLUMN_NAME,QColor(255,0,0));
            } else {
                widgetitem->setTextColor(COLUMN_NAME,ui.participantsList->palette().color(QPalette::Active, QPalette::Text));
            }

            time_t tLastAct=widgetitem->text(COLUMN_ACTIVITY).toInt();
            time_t now = time(NULL);

            if(isParticipantMuted(it2->first))
                widgetitem->setIcon(COLUMN_ICON, QIcon(":/icons/bullet_red_128.png"));
            else if (tLastAct + timeToInactivity < now)
                widgetitem->setIcon(COLUMN_ICON, QIcon(":/icons/bullet_grey_128.png"));
            else
                widgetitem->setIcon(COLUMN_ICON, QIcon(":/icons/bullet_green_128.png"));

            RsGxsId gxs_id;
            rsMsgs->getIdentityForChatLobby(lobbyId, gxs_id);

            if (RsGxsId(participant.toStdString()) == gxs_id) widgetitem->setIcon(COLUMN_ICON, QIcon(":/icons/bullet_yellow_128.png"));

            QTime qtLastAct=QTime(0,0,0).addSecs(now-tLastAct);
            widgetitem->setToolTip(COLUMN_ICON,tr("Right click to mute/unmute participants<br/>Double click to address this person<br/>")
                                   +tr("This participant is not active since:")
                                   +qtLastAct.toString()
                                   +tr(" seconds")
                                  );
        }
    }
static void testluproblem(const ap::real_2d_array& a,
     int m,
     int n,
     double& diffpu,
     double& luerr)
{
    ap::real_2d_array t1;
    ap::real_2d_array t2;
    ap::real_2d_array t3;
    ap::integer_1d_array it1;
    ap::integer_1d_array it2;
    int i;
    int j;
    int k;
    double v;
    double mx;
    ap::real_2d_array a0;
    ap::integer_1d_array p0;

    mx = 0;
    for(i = 1; i <= m; i++)
    {
        for(j = 1; j <= n; j++)
        {
            if( ap::fp_greater(fabs(a(i,j)),mx) )
            {
                mx = fabs(a(i,j));
            }
        }
    }
    if( ap::fp_eq(mx,0) )
    {
        mx = 1;
    }
    
    //
    // Compare LU and unpacked LU
    //
    t1.setbounds(1, m, 1, n);
    for(i = 1; i <= m; i++)
    {
        ap::vmove(&t1(i, 1), &a(i, 1), ap::vlen(1,n));
    }
    ludecomposition(t1, m, n, it1);
    ludecompositionunpacked(a, m, n, t2, t3, it2);
    for(i = 1; i <= m; i++)
    {
        for(j = 1; j <= ap::minint(m, n); j++)
        {
            if( i>j )
            {
                diffpu = ap::maxreal(diffpu, fabs(t1(i,j)-t2(i,j))/mx);
            }
            if( i==j )
            {
                diffpu = ap::maxreal(diffpu, fabs(1-t2(i,j))/mx);
            }
            if( i<j )
            {
                diffpu = ap::maxreal(diffpu, fabs(0-t2(i,j))/mx);
            }
        }
    }
    for(i = 1; i <= ap::minint(m, n); i++)
    {
        for(j = 1; j <= n; j++)
        {
            if( i>j )
            {
                diffpu = ap::maxreal(diffpu, fabs(0-t3(i,j))/mx);
            }
            if( i<=j )
            {
                diffpu = ap::maxreal(diffpu, fabs(t1(i,j)-t3(i,j))/mx);
            }
        }
    }
    for(i = 1; i <= ap::minint(m, n); i++)
    {
        diffpu = ap::maxreal(diffpu, fabs(double(it1(i)-it2(i))));
    }
    
    //
    // Test unpacked LU
    //
    ludecompositionunpacked(a, m, n, t1, t2, it1);
    t3.setbounds(1, m, 1, n);
    k = ap::minint(m, n);
    for(i = 1; i <= m; i++)
    {
        for(j = 1; j <= n; j++)
        {
            v = ap::vdotproduct(t1.getrow(i, 1, k), t2.getcolumn(j, 1, k));
            t3(i,j) = v;
        }
    }
    for(i = ap::minint(m, n); i >= 1; i--)
    {
        if( i!=it1(i) )
        {
            for(j = 1; j <= n; j++)
            {
                v = t3(i,j);
                t3(i,j) = t3(it1(i),j);
                t3(it1(i),j) = v;
            }
        }
    }
    for(i = 1; i <= m; i++)
    {
        for(j = 1; j <= n; j++)
        {
            luerr = ap::maxreal(luerr, fabs(a(i,j)-t3(i,j))/mx);
        }
    }
    
    //
    // Test 0-based LU
    //
    t1.setbounds(1, m, 1, n);
    for(i = 1; i <= m; i++)
    {
        ap::vmove(&t1(i, 1), &a(i, 1), ap::vlen(1,n));
    }
    ludecomposition(t1, m, n, it1);
    a0.setbounds(0, m-1, 0, n-1);
    for(i = 0; i <= m-1; i++)
    {
        for(j = 0; j <= n-1; j++)
        {
            a0(i,j) = a(i+1,j+1);
        }
    }
    rmatrixlu(a0, m, n, p0);
    for(i = 0; i <= m-1; i++)
    {
        for(j = 0; j <= n-1; j++)
        {
            diffpu = ap::maxreal(diffpu, fabs(a0(i,j)-t1(i+1,j+1)));
        }
    }
    for(i = 0; i <= ap::minint(m-1, n-1); i++)
    {
        diffpu = ap::maxreal(diffpu, fabs(double(p0(i)+1-it1(i+1))));
    }
}
Beispiel #30
0
/////////////////////////////////////////////////////////////////////////////
//#include <pmessage.hpp>
SIGNED MyMainFrame::Message(const PegMessage &msg)
{
    bool ok;
	switch(msg.wType)
    {
        //case PM_ADD:   
        //	addWindow( (PegWindow*)msg.pSource );
        //	break;

		case PM_DRAW:
			Invalidate();
			Draw();
			break;

        case HM_SYS_KEYBOARD:
            toggleKeypad();
            break;

		//case HM_SYS_RESUME:
		//	break;

		case HM_SYS_ZOOM:
			if(m_allowResizeKey) setFullScreenApp(!m_fullScreen);
			break;

        case HM_SYS_CLEAR:
			if(m_activeWin && m_activeWin->onClearKeyPressed()) 
				removeWindow(m_activeWin);
            break;

		case PM_FIRST_START:
			if(m_activeWin) Presentation()->MoveFocusTree(m_activeWin);
			break;

 		case SIGNAL(DEF_MENU_QUIT, PSF_CLICKED):
			programQuit();
			break;

		case MYMF_SEND_SIGNAL:
			((MyWindow*)msg.pSource)->onSignal(msg.iData);
			break;
		
       default:
			ok = false;
			if(m_activeWin)	m_otherWin.Insert(m_activeWin);
			ent ptr2;
			CPListIterator it2(&m_otherWin);	
			for(ptr2 = it2.Head(); ptr2!=NULL; ptr2 = it2.Next())
			{
				ent ptr;
				CPListIterator it( ((MyWindow*)ptr2)->handledSignalsList() );
				for(ptr = it.Head(); ptr!=NULL; ptr = it.Next())
				{
					if( msg.wType == *((WORD*)ptr) )
					{
						prepareSignal((MyWindow*)ptr2, msg.wType);
						ok=true;
						break;
					}
				}
			}
		
			m_otherWin.Remove(m_activeWin);

			if(!ok) return PegWindow::Message(msg);
    }
    return 0;
}