Beispiel #1
0
bool Search::Find(bool firstLoop)
{
	if (firstLoop)
	{
		SetDefaults();
		if (!_caseSensitive)
		{
			for (unsigned int i=0;i<_criteria.size();i++)
			{
				Uncapitalize(_criteria[i]._query);
			}
		}
		if (!SI.Init(_beginPath)){
			SearchException se(L"Could not find path: ");
			se.AppendBasicLog(SI.GetPath());
		};
	}else
	{_cycleTimer=clock();}
	SearchLoop();
	return 0;
}
Beispiel #2
0
int main(int argc, char *argv[])
{
    try {

        CheckearthqParameters p;
        getProgramOptions(argc, argv, &p);

        Random::RandomGen r(p.config_file);
        Ephemeris::SwissEphemeris se(p.ephemeris_path);
        Ephemeris::ephemeris = &se;

        list<Earthquake> earthquakes{ getEarthquakes(p.input_file, p.excl_unknown, p.skip_bad, p.dbf) };

        list<DateTime> earthquake_date_times;

        for(auto e : earthquakes) {

            if(e.deaths >= p.min_deaths
                    && e.when.date().year() >= p.year_from
                    && e.when.date().year() <= p.year_to)
            {
                earthquake_date_times.push_back(e.when);
            }
        }

        Test::performMainTest(earthquake_date_times, p, &r);

        return 0;
    }
    catch(const exception& e)
    {
        cerr << e.what() << "\n";
    }
    catch(...) {

        cerr << "unknown error\n";
    }

    return  1;
}
Beispiel #3
0
void set_pivot_from_preferences(gfx::Transformation& t)
{
  gfx::Transformation::Corners corners;
  t.transformBox(corners);
  gfx::PointT<double> nw(corners[gfx::Transformation::Corners::LEFT_TOP]);
  gfx::PointT<double> ne(corners[gfx::Transformation::Corners::RIGHT_TOP]);
  gfx::PointT<double> sw(corners[gfx::Transformation::Corners::LEFT_BOTTOM]);
  gfx::PointT<double> se(corners[gfx::Transformation::Corners::RIGHT_BOTTOM]);
  gfx::PointT<double> pivotPos((nw + se) / 2);

  app::gen::PivotPosition pivot = Preferences::instance().selection.pivotPosition();
  switch (pivot) {
    case app::gen::PivotPosition::NORTHWEST:
      pivotPos = nw;
      break;
    case app::gen::PivotPosition::NORTH:
      pivotPos = (nw + ne) / 2.0;
      break;
    case app::gen::PivotPosition::NORTHEAST:
      pivotPos = ne;
      break;
    case app::gen::PivotPosition::WEST:
      pivotPos = (nw + sw) / 2.0;
      break;
    case app::gen::PivotPosition::EAST:
      pivotPos = (ne + se) / 2.0;
      break;
    case app::gen::PivotPosition::SOUTHWEST:
      pivotPos = sw;
      break;
    case app::gen::PivotPosition::SOUTH:
      pivotPos = (sw + se) / 2.0;
      break;
    case app::gen::PivotPosition::SOUTHEAST:
      pivotPos = se;
      break;
  }

  t.displacePivotTo(gfx::PointF(pivotPos));
}
Beispiel #4
0
bool OverridingShortcut::eventFilter(QObject* /*watched*/, QEvent* event)
{
	if (event->type() == QEvent::ShortcutOverride && key().count() == 1)
	{
		QKeyEvent* key_event = static_cast<QKeyEvent*>(event);
		if ((key_event->key() | int(key_event->modifiers())) == key()[0])
		{
			if (timer.elapsed() < 50) // milliseconds
			{
				event->accept();
				return true;
			}
			
			QShortcutEvent se(key(), id());
			event->setAccepted(QShortcut::event(&se));
			timer.restart();
			return event->isAccepted();
		}
	}
	
	return false;
}
Beispiel #5
0
TEST(VoidElement, CopyElement)
{
    tawara::StringElement se(0x80, "12345");

    std::streamsize se_size(se.size());
    tawara::VoidElement ve1(se);
    EXPECT_EQ(se_size, ve1.size());
    EXPECT_FALSE(ve1.fill());

    tawara::VoidElement ve2(se, true);
    EXPECT_EQ(se_size, ve2.size());
    EXPECT_TRUE(ve2.fill());

    // Test elements with a size right on the border of two encoded sizes for
    // the body size
    for (int ii(0); ii < 10; ++ii)
    {
        tawara::BinaryElement be(0x81, std::vector<char>(0x3FFB + ii, 0xC0));
        tawara::VoidElement ve3(be);
        EXPECT_EQ(be.size(), ve3.size());
    }
}
Beispiel #6
0
void LiveEventControl::openLoopRangeDialog(int row)
{
	QDialog d;
	QVBoxLayout l(&d);
	QLabel ls(tr("Loop start"),&d);
	QSpinBox ss(&d);
	QLabel le(tr("Loop end"),&d);
	QSpinBox se(&d);
	QPushButton okButton(tr("Ok"), &d);
	QPushButton cancelButton(tr("Cancel"), &d);
	connect(&okButton,SIGNAL(released()),&d,SLOT(accept()));
	connect(&cancelButton,SIGNAL(released()),&d,SLOT(reject()));
	l.addWidget(&ls);
	l.addWidget(&ss);
	l.addWidget(&le);
	l.addWidget(&se);
	l.addWidget(&okButton);
	l.addWidget(&cancelButton);
	QTableWidgetItem *item = getItem(row,6);
	QStringList bounds(item->text().split("-"));
	if (bounds.size() > 1) {
		if (bounds[0].toInt() >= 0) {
			ss.setValue(bounds[0].toInt());
		}
		if (bounds[1].toInt() >= 0) {
			se.setValue(bounds[1].toInt());
		}
	}
	int ret = d.exec();
	if (ret == QDialog::Accepted) {
		QString range = QString::number(ss.value()) + "-" + QString::number(se.value());
		qDebug() << "LiveEventControl::openLoopRangeDialog " << row << range;
		QTableWidgetItem *item = m_ui->panelTableWidget->item(row,6);
		item->setText(range);
		emit setPanelLoopRangeSignal(row, ss.value() - 1,se.value() - 1);
	}
}
Beispiel #7
0
std::istream& GetLine(std::istream& is, std::string& t)
{
    t.clear();
    std::istream::sentry se(is, true);
    std::streambuf* sb = is.rdbuf();

    for (;;) {
        int c = sb->sbumpc();
        switch (c) {
            case '\n':
              return is;
            case '\r':
              if (sb->sgetc() == '\n')
                sb->sbumpc();
              return is;
            case  EOF:
              if (t.empty())
                is.setstate(std::ios::eofbit);
              return is;
            default:
              t += (char)c;
        }
    }
}
Beispiel #8
0
int main(int argc, char* argv[])
{
  std::cout << "\n  Testing ActionsAndRules class\n "
            << std::string(30,'=') << std::endl;

  try
  {
    std::queue<std::string> resultsQ;
    PreprocToQ ppq(resultsQ);
    PreprocStatement pps;
    pps.addAction(&ppq);

    FunctionDefinition fnd;
    PrettyPrintToQ pprtQ(resultsQ);
    fnd.addAction(&pprtQ);

    Toker toker("../ActionsAndRules.h");
    SemiExp se(&toker);
    Parser parser(&se);
    parser.addRule(&pps);
    parser.addRule(&fnd);
    while(se.get())
      parser.parse();
    size_t len = resultsQ.size();
    for(size_t i=0; i<len; ++i)
    {
      std::cout << "\n  " << resultsQ.front().c_str();
      resultsQ.pop();
    }
    std::cout << "\n\n";
  }
  catch(std::exception& ex)
  {
    std::cout << "\n\n  " << ex.what() << "\n\n";
  }
}
    void Read(CObjectIStream* obj_in_stream,
              TCallback callback,
              const string& top_level_asn_object = kEmptyStr)
    {
        while ( !obj_in_stream->EndOfData() ) {
            // determine the ASN.1 object type
            string obj = obj_in_stream->ReadFileHeader();
            if ( obj.empty() ) {
                // auto-detection is not possible in ASN.1 binary mode
                // hopefully top_level_asn_object was specified by the user
                if ( top_level_asn_object.empty() ) {
                    NCBI_THROW(CException, eUnknown,
                        "ReadFileHeader() returned empty.  "
                        "Binary ASN.1 file?  "
                        "Please supply the top_level_asn_object.");
                }
                else {
                    obj = top_level_asn_object;
                }
            }
            else {
                if (!top_level_asn_object.empty()  &&  obj != top_level_asn_object) {
                    // object differs from the specified, skip it
                    continue;
                }
            }

            CTypesIterator i;
            CType<CSeq_align>::AddTo(i);

            if (obj == "Seq-entry") {
                CRef<CSeq_entry> se(new CSeq_entry);
                obj_in_stream->Read(Begin(*se), CObjectIStream::eNoFileHeader);
                if ( m_Scope ) {
                    m_Scope->AddTopLevelSeqEntry(*se);
                }
                for (i = Begin(*se); i; ++i) {
                    if ( CType<CSeq_align>::Match(i) ) {
                        callback(CType<CSeq_align>::Get(i));
                    }
                }
            }
            else if (obj == "Seq-submit") {
                CRef<CSeq_submit> ss(new CSeq_submit);
                obj_in_stream->Read(Begin(*ss), CObjectIStream::eNoFileHeader);
                CType<CSeq_entry>::AddTo(i);
                int tse_cnt = 0;
                for (i = Begin(*ss); i; ++i) {
                    if ( CType<CSeq_align>::Match(i) ) {
                        callback(CType<CSeq_align>::Get(i));
                    }
                    else if ( CType<CSeq_entry>::Match(i) ) {
                        if ( !(tse_cnt++) ) {
                            //m_Scope.AddTopLevelSeqEntry
                            (*(CType<CSeq_entry>::Get(i)));
                        }
                    }
                }
            }
            else if (obj == "Seq-align") {
                CRef<CSeq_align> sa(new CSeq_align);
                obj_in_stream->Read(Begin(*sa), CObjectIStream::eNoFileHeader);
                for (i = Begin(*sa); i; ++i) {
                    if ( CType<CSeq_align>::Match(i) ) {
                        callback(CType<CSeq_align>::Get(i));
                    }
                }
            }
            else if (obj == "Seq-align-set") {
                CRef<CSeq_align_set> sas(new CSeq_align_set);
                obj_in_stream->Read(Begin(*sas), CObjectIStream::eNoFileHeader);
                for (i = Begin(*sas); i; ++i) {
                    if ( CType<CSeq_align>::Match(i) ) {
                        callback(CType<CSeq_align>::Get(i));
                    }
                }
            }
            else if (obj == "Seq-annot") {
                CRef<CSeq_annot> san(new CSeq_annot);
                obj_in_stream->Read(Begin(*san), CObjectIStream::eNoFileHeader);
                for (i = Begin(*san); i; ++i) {
                    if ( CType<CSeq_align>::Match(i) ) {
                        callback(CType<CSeq_align>::Get(i));
                    }
                }
            }
            else if (obj == "Dense-seg") {
                CRef<CDense_seg> ds(new CDense_seg);
                obj_in_stream->Read(Begin(*ds), CObjectIStream::eNoFileHeader);
                CRef<CSeq_align> sa(new CSeq_align);
                sa->SetType(CSeq_align::eType_not_set);
                sa->SetSegs().SetDenseg(*ds);
                sa->SetDim(ds->GetDim());
                callback(sa);
            }
            else {
                if ( obj.empty() ) {
                    NCBI_THROW(CException, eUnknown,
                        "ReadFileHeader() returned empty.  "
                        "Binary ASN.1 file?  "
                        "Please supply the top_level_asn_object.");
                }
                else {
                    cerr << "Don't know how to extract alignments from: " << obj << endl;
                    cerr << "Do you know?  Please contact us at [email protected]." << endl;
                }
                return;
            }

            if (m_Verbose) {
                cerr << "Finished reading " << obj << "." << endl;
            }

        }            
    }
int main(int argc, char* argv[])
{
  std::cout << "\n  Testing SemiExp class\n "
            << std::string(23,'=') << std::endl;

  try {
  std::cout << "\n  testing SemiExp::get(...)";
  std::cout << "\n -----------------------------";
  Toker toker1(argv[1]);
  toker1.returnComments(false);
  SemiExp test1(&toker1);
  test1.get();
  std::cout << "\n  " << test1.show();
  test1.get(false);
  std::cout << "\n  " << test1.show();
  test1.get();
  std::cout << "\n  " << test1.show();
  test1.get(false);
  std::cout << "\n  " << test1.show() << std::endl;

  std::cout << "\n  testing SemiExp::merge(...)";
  std::cout << "\n -----------------------------";
  SemiExp test2(0);
  test2.push_back("one");
  test2.push_back("two");
  test2.push_back("three");
  test2.push_back("four");
  test2.push_back("five");
  std::cout << "\n  " << test2.show();
  test2.merge("two","five");
  std::cout << "\n  " << test2.show() << std::endl;
  
  std::cout << "\n  testing SemiExp::find()";
  std::cout << "\n -------------------------";
  SemiExp semi(0);
  semi.push_back("one");
  semi.push_back("two");
  semi.push_back("three");
  semi.push_back("four");
  std::cout << "\n" << semi.show();
  size_t pos = semi.find("two");
  std::cout << "\n  position of \"two\" is " << pos;
  pos = semi.find("foobar");
  std::cout << "\n  position of \"foobar\" is " << pos;
  std::cout << "\n\n";

  std::cout << "\n  Note that comments and quotes are returned as single tokens\n";
  }
  catch(std::exception& ex)
  {
    std::cout << "\n\n  " << ex.what() << "\n\n";
    return 1;
  }
  if(argc < 2)
  {
    std::cout 
      << "\n  please enter name of file to process on command line\n\n";
    return 1;
  }

  for(int i=1; i<argc; ++i)
  {
    std::cout << "\n  Processing file " << argv[i];
    std::cout << "\n  " << std::string(16 + strlen(argv[i]),'-') << "\n\n";
    try
    {
  	  Toker toker(argv[i]);
      toker.returnComments();
      SemiExp se(&toker);
      se.makeCommentSemiExp();
      //se.verbose();                 // uncomment to show token details
      while(se.get())
      {
        std::cout << se.show(true).c_str() << std::endl;
        for(size_t i=0; i<se.length(); ++i)
          if(se[i] == "")
            std::cout << "\n\n----blank token----\n";
      }
      std::cout << "\n";
    }
    catch(std::exception ex)
    {
      std::cout << "\n  " << ex.what() << "\n\n";
    }
  }

  for(int i=1; i<argc; ++i)
  {
    std::cout << "\n  Processing file " << argv[i];
    std::cout << "\n  " << std::string(16 + strlen(argv[i]),'-') << "\n\n";
    try
    {
  	  Toker toker(argv[i]);
      toker.returnComments();
      SemiExp se(&toker);
      se.makeCommentSemiExp();
      se.returnNewLines(false);
      //se.verbose();                 // uncomment to show token details
      while(se.get())
      {
        for(size_t i=0; i<se.length(); ++i)
          if(se[i] == "")
            std::cout << "\n\n----blank token----\n";
        std::cout << se.show(true).c_str() << std::endl;
      }
      std::cout << "\n";
    }
    catch(std::exception ex)
    {
      std::cout << "\n  " << ex.what() << "\n\n";
    }
  }
}
Beispiel #11
0
int
main (int argc, char *argv[])
{
  int optch;
  char *dir = KBDDIR;
  struct kd_keymap map;
  FILE *file;
  char line[MAXLINE + 2];
  char *start;
  int p[4], i, j;
  char ch;

  if ((optch = getopt (argc, argv, "d:")) != EOF)
    if (optch == 'd')
      dir = optarg;
    else
      usage ();

  if (argc < 4)
    usage ();

  if (chdir (dir) < 0)
    {
      fprintf (stderr, "setkbd: cannot change to directory %s: %s\n", dir, strerror (errno));
      return 1;
    }

  if ((map.kbd_flags = atoi (argv[optind + 2])) < 0)
    {
      fprintf (stderr, "setkbd: diacr_mask error\n");
      return 1;
    }

  for (i = 0; i < 97; i++)
    map.key_map[i] = map.shift_map[i] = map.alt_map[i] = 0;
  for (i = 0; i < NUM_ACC; i++)
    {
      map.accent_table[i][0] = 32;
      for (j = 1; j < 63; j++)
	map.accent_table[i][j] = j + 64;
    }
  for (i = 0; i < 13; i++)
    map.lock_state[i] = 0;
  for (i = 0; i <= NUM_ACC; i++)
    map.diacr_table[i] = 0;

  if ((file = fopen (argv[optind], "r")) == NULL)
    {
      fprintf (stderr, "setkbd: cannot open %s: %s\n", argv[optind], strerror (errno));
      return 1;
    }
  while (fgets (line, MAXLINE, file))
    {
      start = line;
      while (*start == ' ' || *start == '\t')
	start++;
      if (*start && *start != '\n' && *start != '#')
	{
	  for (i = 0; i < 4; i++)
	    p[i] = -1;
	  ch = 0;
	  for (i = 0; i < 4; i++)
	    {
	      while (*start == ' ' || *start == '\t')
		start++;
	      if (*start == '\'')
		{
		  p[i] = *(++start);
		  start++;
		  start++;
		}
	      else if ((p[i] = strtol (start, &start, 0)) < 0 || p[i] > 255)
		se ();
	    }
	  while (*start == ' ' || *start == '\t')
	    start++;
	  if ((ch = *start) != 'C' && ch != 'O')
	    se ();
	}
      map.key_map[p[0]] = p[1];
      map.shift_map[p[0]] = p[2];
      map.alt_map[p[0]] = p[3];
      map.lock_state[p[0] / 8] |= (ch == 'C') ? 1 << (p[0] % 8) : 0;
    }
  i = -1;
  if ((file = fopen (argv[optind + 1], "r")) == NULL)
    {
      fprintf (stderr, "setkbd: cannot open %s: %s\n", argv[optind + 1], strerror (errno));
      return 1;
    }
  while (fgets (line, MAXLINE, file))
    {
      start = line;
      if (*start && *start != '\n' && *start != '#')
	{
	  while (*start == ' ' || *start == '\t')
	    start++;
	  switch (*start)
	    {
	    case 'd':
	      if ((p[2] = strtol (start + 4, &start, 0)) < 0
		  || p[2] > 255)
		se ();
	      i++;
	      if (i == NUM_ACC)
		{
		  fprintf (stderr, "setkbd: too many dead keys\n");
		  exit (1);
		}
	      map.diacr_table[i] = p[2];
	      goto aaa;
	      break;
	    case '#':
	    case '\n':
	      break;
	    default:
	      if (i < 0)
		se ();
	      for (j = 0; j < 2; j++)
		p[j] = -1;
	      for (j = 0; j < 2; j++)
		{
		  while (*start == ' ' || *start == '\t')
		    start++;
		  if (*start == '\'')
		    {
		      p[j] = *(++start);
		      start++;
		      start++;
		    }
		  else if ((p[j] = strtol (start, &start, 0)) < 0 || p[j] > 255)
		    se ();
		}
	      map.accent_table[i][p[0] - 64] = p[1];
	      break;
	    }
	}
    aaa:
    }
  if (ioctl (2, KDSETKBD, &map) < 0)
    {
      fprintf (stderr, "setkbd: ioctl failed: %s\n", strerror (errno));
      return 1;
    }

  return 0;
}
Beispiel #12
0
int main(int argc, char *argv[])
{
    if(2 != argc) {
        printf("./meta_kdtree metapath\n");
        return -1;
    }

    skdtree_t se(6);
    mylist *mlist = meta_read(argv[1]);
    printf("partiton size = %d\n", mlist->size);

    // insert every file's metadata to simple kdtree
    for(int i = 0; i < mlist->size; i++) {
        file_meta *m = (file_meta *)mlist->item[i].data;
        meta_info_t *mi = new meta_info_t(m->uid, m->gid, m->size, m->atime, m->ctime, m->mtime);
        se.insert(mi);
    }
    
    // dump test
    {
        // dump in normal tree
        std::vector<meta_info_t *> result;
        struct timeval start, end;
        gettimeofday(&start, NULL);
        se.dump(result);
        gettimeofday(&end, NULL);
        printf("height: %d\n", se.height());
        print_interval(start, end);
        printf("%d\n", result.size());

        printf("\n");

        // dump in balance tree
        se.balance();
        result.clear();
        gettimeofday(&start, NULL);
        se.dump(result);
        gettimeofday(&end, NULL);
        printf("height: %d\n", se.height());
        print_interval(start, end);
        printf("%d\n", result.size()); 

        printf("\n");

        // dump in list
        std::vector<file_meta *> mresult;
        gettimeofday(&start, NULL);
        for(int i = 0; i < mlist->size; i++) {
            mresult.push_back((file_meta *)mlist->item[i].data);
        }
        gettimeofday(&end, NULL);
        print_interval(start, end);
        printf("%d\n", result.size()); 
        printf("\n");
    }

    
    {
        
        struct timeval start, end;
        meta_info_t low(0, 0, 1024*1024, 0, 0, 0);
        meta_info_t high(0, 0, 2024*1024, 0xffffffff, 0xffffffff, 0xffffffff);
        region_t r(low, high);

        // range find in kdtree

        std::cout << "range find in simple kdtree" << std::endl;
        std::vector<meta_info_t *> v;
        gettimeofday(&start, NULL);
        se.find_within_range(r, v);
        gettimeofday(&end, NULL);
        print_interval(start, end);
        printf("results: %u\n", v.size());
        printf("\n");


        v.clear();
        se.balance();
        printf("height after optimise: %d\n", se.height());

        std::cout << "range find in simple balance kdtree" << std::endl;
        gettimeofday(&start, NULL);
        se.find_within_range(r, v);
        gettimeofday(&end, NULL);
        print_interval(start, end);
        printf("results: %u\n", v.size());
        printf("\n");

    }
}
Beispiel #13
0
// apply a displacement that does not create elements that are
// distorted over a value "thres"
double highOrderTools::apply_incremental_displacement(double max_incr,
                                                      std::vector<MElement*> & v,
                                                      bool mixed,
                                                      double thres,
                                                      char *meshName,
                                                      std::vector<MElement*> & disto)
{
#ifdef HAVE_PETSC
  // assume that the mesh is OK, yet already curved
  //linearSystemCSRTaucs<double> *lsys = new linearSystemCSRTaucs<double>;
  linearSystemPETSc<double> *lsys = new  linearSystemPETSc<double>;
  lsys->setParameter("petscOptions","-pc_type ilu");
  lsys->setParameter("petscOptions","-ksp_monitor");

  dofManager<double> myAssembler(lsys);
  elasticityMixedTerm El_mixed (0, 1.0, .333, _tag);
  elasticityTerm El (0, 1.0, .333, _tag);

  std::set<MVertex*> _vertices;

  //+++++++++ Boundary Conditions & Numbering +++++++++++++++++++++++++++++++
  // fix all dof that correspond to vertices on the boundary
  // the value is equal
  for (unsigned int i = 0; i < v.size(); i++){
    for (int j = 0; j < v[i]->getNumVertices(); j++){
      MVertex *vert = v[i]->getVertex(j);
      _vertices.insert(vert);
    }
  }

  //+++++++++ Fix d tr(eps) = 0 +++++++++++++++++++++++++++++++
  if (mixed){
    for (unsigned int i = 0; i < disto.size(); i++){
      for (int j = 0; j < disto[i]->getNumVertices(); j++){
        MVertex *vert = disto[i]->getVertex(j);
        myAssembler.fixVertex(vert, 4, _tag, 0.0);
      }
    }
  }

  for (std::set<MVertex*>::iterator it = _vertices.begin(); it != _vertices.end(); ++it){
    MVertex *vert = *it;
    std::map<MVertex*,SVector3>::iterator itt = _targetLocation.find(vert);
    // impose displacement @ boundary
    if (itt != _targetLocation.end() && vert->onWhat()->dim() < _dim){
      myAssembler.fixVertex(vert, 0, _tag, itt->second.x()-vert->x());
      myAssembler.fixVertex(vert, 1, _tag, itt->second.y()-vert->y());
      myAssembler.fixVertex(vert, 2, _tag, itt->second.z()-vert->z());
    }
    // ensure we do not touch any vertex that is on the boundary
    else if (vert->onWhat()->dim() < _dim){
      myAssembler.fixVertex(vert, 0, _tag, 0);
      myAssembler.fixVertex(vert, 1, _tag, 0);
      myAssembler.fixVertex(vert, 2, _tag, 0);
    }
    //    }
    if (_dim == 2)myAssembler.fixVertex(vert, 2, _tag, 0);
    // number vertices
    myAssembler.numberVertex(vert, 0, _tag);
    myAssembler.numberVertex(vert, 1, _tag);
    myAssembler.numberVertex(vert, 2, _tag);
    if (mixed){
      myAssembler.numberVertex(vert, 3, _tag);
      myAssembler.numberVertex(vert, 4, _tag);
    }
  }

  if (myAssembler.sizeOfR()){
    // assembly of the elasticity term on the
    for (unsigned int i = 0; i < v.size(); i++){
      SElement se(v[i]);
      if (mixed) El_mixed.addToMatrix(myAssembler, &se);
      else El.addToMatrix(myAssembler, &se);
    }
    // solve the system
    lsys->systemSolve();
  }

  // Move vertices @ maximum
  FILE *fd = Fopen ("d.msh","w");
  fprintf(fd,"$MeshFormat\n2 0 8\n$EndMeshFormat\n$NodeData\n1\n"
          "\"tr(sigma)\"\n1\n0.0\n3\n1\n3\n%d\n", (int) _vertices.size());
  for (std::set<MVertex*>::iterator it = _vertices.begin(); it != _vertices.end(); ++it){
    double ax, ay, az;
    myAssembler.getDofValue(*it, 0, _tag, ax);
    myAssembler.getDofValue(*it, 1, _tag, ay);
    myAssembler.getDofValue(*it, 2, _tag, az);
    (*it)->x() += max_incr*ax;
    (*it)->y() += max_incr*ay;
    (*it)->z() += max_incr*az;
    fprintf(fd,"%d %g %g %g\n",(*it)->getIndex(), ax,ay,az);
  }
  fprintf(fd,"$EndNodeData\n");
  fclose(fd);

  // Check now if elements are ok

  (*_vertices.begin())->onWhat()->model()->writeMSH(meshName);

  double percentage = max_incr * 100.;
  while(1){
    std::vector<MElement*> disto;
    double minD;
    getDistordedElements(v, 0.5, disto, minD);
    if (minD < thres){
      percentage -= 10.;
      for (std::set<MVertex*>::iterator it = _vertices.begin(); it != _vertices.end(); ++it){
        double ax, ay, az;
        myAssembler.getDofValue(*it, 0, _tag, ax);
        myAssembler.getDofValue(*it, 1, _tag, ay);
        myAssembler.getDofValue(*it, 2, _tag, az);
        (*it)->x() -= .1*ax;
        (*it)->y() -= .1*ay;
        (*it)->z() -= .1*az;
      }
    }
    else break;
  }

  delete lsys;
  return percentage;
#endif
  return 0.0;
}
Beispiel #14
0
PView *GMSH_DistancePlugin::execute(PView *v)
{
  int id_pt   = (int) DistanceOptions_Number[0].def;
  int id_line = (int) DistanceOptions_Number[1].def;
  int id_face = (int) DistanceOptions_Number[2].def;
  double type = (double) DistanceOptions_Number[3].def;
  int ortho   = (int) DistanceOptions_Number[6].def;

  PView *view = new PView();
  _data = getDataList(view);
#if defined(HAVE_SOLVER)
#if defined(HAVE_TAUCS)
  linearSystemCSRTaucs<double> *lsys = new linearSystemCSRTaucs<double>;
#else
  linearSystemCSRGmm<double> *lsys = new linearSystemCSRGmm<double>;
  lsys->setNoisy(1);
  lsys->setGmres(1);
  lsys->setPrec(5.e-8);
#endif
  dofManager<double> * dofView = new dofManager<double>(lsys);
#endif

  std::vector<GEntity*> _entities;
  GModel::current()->getEntities(_entities);
  if (!_entities.size() || !_entities[_entities.size()-1]->getMeshElement(0)) {
    Msg::Error("This plugin needs a mesh !");
    return view;
  }

  GEntity* ge = _entities[_entities.size()-1];
  int integrationPointTetra[2] = {0,0};

  int numnodes = 0;
  for (unsigned int i = 0; i < _entities.size()-1; i++)
    numnodes += _entities[i]->mesh_vertices.size();
  int totNodes = numnodes + _entities[_entities.size()-1]->mesh_vertices.size();
  int order = ge->getMeshElement(0)->getPolynomialOrder();
  int totNumNodes = totNodes + ge->getNumMeshElements()*integrationPointTetra[order-1];

  std::vector<SPoint3> pts;
  std::vector<double> distances;
  std::vector<MVertex* > pt2Vertex;
  pts.clear();
  distances.clear();
  pt2Vertex.clear();
  pts.reserve(totNumNodes);
  distances.reserve(totNumNodes);
  pt2Vertex.reserve(totNumNodes);

  std::map<MVertex*,double> _distanceE_map;
  std::map<MVertex*,int> _isInYarn_map;
  std::vector<int> index;
  std::vector<double> distancesE;
  std::vector<double> distances2;
  std::vector<double> distancesE2;
  std::vector<int> isInYarn;
  std::vector<int> isInYarn2;
  std::vector<SPoint3> closePts;
  std::vector<SPoint3> closePts2;

  for (int i=0; i<totNumNodes; i++) {
    distances.push_back(1.e22);
  }

  int k = 0;
  for (unsigned int i=0; i<_entities.size(); i++){
    GEntity* ge = _entities[i];
    _maxDim = std::max(_maxDim, ge->dim());
    for (unsigned int j=0; j<ge->mesh_vertices.size(); j++) {
      MVertex *v = ge->mesh_vertices[j];
      pts.push_back(SPoint3(v->x(), v->y(), v->z()));
      _distance_map.insert(std::make_pair(v, 0.0));
/* TO DO (by AM)
      SPoint3 p_empty();
      _closePts_map.insert(std::make_pair(v, p_empty));
*/
      pt2Vertex[k] = v;
      k++;
    }
  }

  // Compute geometrical distance to mesh boundaries
  //------------------------------------------------------
  if (type < 0.0 ) {

    bool existEntity = false;

    for (unsigned int i=0; i<_entities.size(); i++) {
      GEntity* g2 = _entities[i];
      int gDim = g2->dim();
      std::vector<int> phys = g2->getPhysicalEntities();
      bool computeForEntity = false;
      for(unsigned int k = 0; k<phys.size(); k++) {
        int tagp = phys[k];
        if (id_pt == 0 && id_line == 0 && id_face == 0 && gDim == _maxDim - 1)
          computeForEntity = true;
        else if ((tagp == id_pt && gDim == 0) || (tagp == id_line && gDim == 1) ||
                 (tagp == id_face && gDim == 2))
          computeForEntity = true;
      }
      if (computeForEntity) {
        existEntity = true;
        for (unsigned int k = 0; k < g2->getNumMeshElements(); k++) {
          std::vector<double> iDistances;
          std::vector<SPoint3> iClosePts;
          std::vector<double> iDistancesE;
          std::vector<int> iIsInYarn;
          MElement *e = g2->getMeshElement(k);
          MVertex *v1 = e->getVertex(0);
          MVertex *v2 = e->getVertex(1);
          SPoint3 p1(v1->x(), v1->y(), v1->z());
          SPoint3 p2(v2->x(), v2->y(), v2->z());
          if ((e->getNumVertices() == 2 && order == 1) ||
              (e->getNumVertices() == 3 && order == 2)) {
            signedDistancesPointsLine(iDistances, iClosePts, pts, p1, p2);
          }
          else if ((e->getNumVertices() == 3 && order == 1) ||
                   (e->getNumVertices() == 6 && order == 2)) {
            MVertex *v3 = e->getVertex(2);
            SPoint3 p3 (v3->x(),v3->y(),v3->z());
            signedDistancesPointsTriangle(iDistances, iClosePts, pts, p1, p2, p3);
          }
          for (unsigned int kk=0; kk<pts.size(); kk++) {
            if (std::abs(iDistances[kk]) < distances[kk]) {
              distances[kk] = std::abs(iDistances[kk]);
              MVertex *v = pt2Vertex[kk];
              _distance_map[v] = distances[kk];
              /* TO DO (by AM)
              _closePts_map[v] = iClosePts[kk];
              */
            }
          }
        }
      }
    }
    if (!existEntity){
      if (id_pt != 0)   Msg::Error("The Physical Point does not exist !");
      if (id_line != 0) Msg::Error("The Physical Line does not exist !");
      if (id_face != 0) Msg::Error("The Physical Surface does not exist !");
      return view;
    }

    printView(_entities, _distance_map);

    /* TO DO (by AM)
    printView(_entities, _closePts_map);
    */
  }

  // Compute PDE for distance function
  //-----------------------------------
  else if (type > 0.0) {

#if defined(HAVE_SOLVER)

    bool existEntity = false;
    SBoundingBox3d bbox;
    for(unsigned int i = 0; i < _entities.size(); i++){
      GEntity* ge = _entities[i];
      int gDim = ge->dim();
      bool fixForEntity = false;
      std::vector<int> phys = ge->getPhysicalEntities();
      for(unsigned int k = 0; k < phys.size(); k++) {
        int tagp = phys[k];
        if (id_pt == 0 && id_line == 0 && id_face == 0 && gDim == _maxDim - 1)
          fixForEntity = true;
        else if ((tagp == id_pt && gDim == 0) || (tagp == id_line && gDim == 1) ||
                 (tagp == id_face && gDim == 2) )
          fixForEntity = true;
      }
      if (fixForEntity) {
        existEntity = true;
        for (unsigned int i = 0; i < ge->getNumMeshElements(); ++i) {
          MElement *t = ge->getMeshElement(i);
          for (int k=0; k<t->getNumVertices(); k++) {
            MVertex *v = t->getVertex(k);
            dofView->fixVertex(v, 0, 1, 0.);
            bbox += SPoint3(v->x(), v->y(), v->z());
          }
        }
      }
    }

    if (!existEntity){
      if (id_pt != 0)   Msg::Error("The Physical Point does not exist !");
      if (id_line != 0) Msg::Error("The Physical Line does not exist !");
      if (id_face != 0) Msg::Error("The Physical Surface does not exist !");
      return view;
    }

    std::vector<MElement *> allElems;
    for(unsigned int ii = 0; ii < _entities.size(); ii++){
      if(_entities[ii]->dim() == _maxDim) {
        GEntity *ge = _entities[ii];
        for(unsigned int i = 0; i < ge->getNumMeshElements(); ++i) {
          MElement *t = ge->getMeshElement(i);
          allElems.push_back(t);
          for (int k = 0; k < t->getNumVertices(); k++)
            dofView->numberVertex(t->getVertex(k), 0, 1);
        }
      }
    }

    double L = norm(SVector3(bbox.max(), bbox.min()));
    double mu = type*L;

    simpleFunction<double> DIFF(mu*mu), ONE(1.0);
    distanceTerm distance(GModel::current(), 1, &DIFF, &ONE);

    for (std::vector<MElement* >::iterator it = allElems.begin();
         it != allElems.end(); it++){
      SElement se((*it));
      distance.addToMatrix(*dofView, &se);
    }
    groupOfElements gr(allElems);
    distance.addToRightHandSide(*dofView, gr);

    Msg::Info("Distance Computation: Assembly done");
    lsys->systemSolve();
    Msg::Info("Distance Computation: System solved");

    for (std::map<MVertex*,double >::iterator itv = _distance_map.begin();
         itv != _distance_map.end() ; ++itv) {
      MVertex *v = itv->first;
      double value;
      dofView->getDofValue(v, 0, 1, value);
      value = std::min(0.9999, value);
      double dist = -mu * log(1. - value);
      itv->second = dist;
    }

    printView(_entities, _distance_map);

#endif
  }

  _data->setName("distance");
  _data->Time.push_back(0);
  _data->setFileName(_fileName.c_str());
  _data->finalize();

  // compute also orthogonal vector to distance field
  // A Uortho = -C DIST
  //------------------------------------------------
  if (ortho > 0) {
#if defined(HAVE_SOLVER)

#ifdef HAVE_TAUCS
    linearSystemCSRTaucs<double> *lsys2 = new linearSystemCSRTaucs<double>;
#else
    linearSystemCSRGmm<double> *lsys2 = new linearSystemCSRGmm<double>;
    lsys->setNoisy(1);
    lsys->setGmres(1);
    lsys->setPrec(5.e-8);
#endif
    dofManager<double> myAssembler(lsys2);
    simpleFunction<double> ONE(1.0);

    double dMax = 1.0; //EMI TO CHANGE

    std::vector<MElement *> allElems;
    for(unsigned int ii = 0; ii < _entities.size(); ii++){
      if (_entities[ii]->dim() == _maxDim) {
        GEntity *ge = _entities[ii];
        for (unsigned int i=0; i<ge->getNumMeshElements(); ++i) {
          MElement *t = ge->getMeshElement(i);
          double vMean = 0.0;
          for (int k = 0; k < t->getNumVertices(); k++) {
            std::map<MVertex*, double>::iterator it = _distance_map.find(t->getVertex(k));
            vMean += it->second;
          }
          vMean /= t->getNumVertices();
          if (vMean < dMax)
            allElems.push_back(ge->getMeshElement(i));
        }
      }
    }

    int mid = (int)floor(allElems.size() / 2.);
    MElement *e = allElems[mid];
    MVertex *vFIX = e->getVertex(0);
    myAssembler.fixVertex(vFIX, 0, 1, 0.0);

    for (std::vector<MElement* >::iterator it = allElems.begin();
         it != allElems.end(); it++){
      MElement *t = *it;
      for(int k = 0; k < t->getNumVertices(); k++)
        myAssembler.numberVertex(t->getVertex(k), 0, 1);
    }

    orthogonalTerm *ortho;
    ortho  = new orthogonalTerm(GModel::current(), 1, &ONE, &_distance_map);
    // if (type  < 0)
    //   ortho  = new orthogonalTerm(GModel::current(), 1, &ONE, view);
    // else
    //   ortho  = new orthogonalTerm(GModel::current(), 1, &ONE, dofView);

    for (std::vector<MElement* >::iterator it = allElems.begin();
         it != allElems.end(); it++){
      SElement se((*it));
      ortho->addToMatrix(myAssembler, &se);
    }
    groupOfElements gr(allElems);
    ortho->addToRightHandSide(myAssembler, gr);

    Msg::Info("Orthogonal Computation: Assembly done");
    lsys2->systemSolve();
    Msg::Info("Orthogonal Computation: System solved");

    PView *view2 = new PView();
    PViewDataList *data2 = getDataList(view2);
    data2->setName("ortogonal field");

    Msg::Info("Writing  orthogonal.pos");
    FILE * f5 = Fopen("orthogonal.pos","w");
    fprintf(f5,"View \"orthogonal\"{\n");
    for (std::vector<MElement* >::iterator it = allElems.begin();
         it != allElems.end(); it++){
      MElement *e = *it;

    int numNodes = e->getNumVertices();
    if (e->getType() == TYPE_POLYG)
      numNodes = e->getNumChildren() * e->getChild(0)->getNumVertices();
    std::vector<double> x(numNodes), y(numNodes), z(numNodes);
    std::vector<double> *out2 = data2->incrementList(1, e->getType(), numNodes);
    std::vector<MVertex*> nods;
    std::vector<double> orth;

    if(!e->getNumChildren())
      for(int i=0; i<numNodes; i++)
        nods.push_back(e->getVertex(i));
    else
      for(int i = 0; i < e->getNumChildren(); i++)
        for(int j = 0; j < e->getChild(i)->getNumVertices(); j++)
          nods.push_back(e->getChild(i)->getVertex(j));

    for(int nod = 0; nod < numNodes; nod++) out2->push_back((nods[nod])->x());
    for(int nod = 0; nod < numNodes; nod++) out2->push_back((nods[nod])->y());
    for(int nod = 0; nod < numNodes; nod++) out2->push_back((nods[nod])->z());

    if (_maxDim == 2)
      switch (numNodes) {
        case 2: fprintf(f5,"SL("); break;
        case 3: fprintf(f5,"ST("); break;
        case 4: fprintf(f5,"SQ("); break;
        default: Msg::Fatal("Error in Plugin 'Distance' (numNodes=%g).",numNodes); break;
      }
    else if (_maxDim == 3)
      switch (numNodes) {
        case 4: fprintf(f5,"SS("); break;
        case 8: fprintf(f5,"SH("); break;
        case 6: fprintf(f5,"SI("); break;
        case 5: fprintf(f5,"SY("); break;
        default: Msg::Fatal("Error in Plugin 'Distance' (numNodes=%g).",numNodes); break;
      }

    for (int j=0; j<numNodes; j++) {
      MVertex *v =  nods[j];
      if (j)
        fprintf(f5, ",%g,%g,%g", v->x(), v->y(), v->z());
      else
        fprintf(f5, "%g,%g,%g", v->x(), v->y(), v->z());
      double value;
      myAssembler.getDofValue(v, 0, 1, value);
      orth.push_back(value);
    }
    fprintf(f5,"){");
    for (unsigned int i=0; i<orth.size(); i++) {
      out2->push_back(orth[i]);
      if (i)
        fprintf(f5,",%g", orth[i]);
      else
        fprintf(f5,"%g", orth[i]);
    }
    fprintf(f5,"};\n");

  }
  fprintf(f5,"};\n");
  fclose(f5);

  lsys->clear();
  lsys2->clear();

  data2->Time.push_back(0);
  data2->setFileName("orthogonal.pos");
  data2->finalize();

#endif
  }

  return view;
}
Beispiel #15
0
static void vaapi_encode_h264_write_slice_header2(PutBitContext *pbc,
                                                  VAAPIEncodeContext *ctx,
                                                  VAAPIEncodePicture *pic,
                                                  VAAPIEncodeSlice *slice)
{
    VAEncSequenceParameterBufferH264  *vseq = ctx->codec_sequence_params;
    VAEncPictureParameterBufferH264   *vpic = pic->codec_picture_params;
    VAEncSliceParameterBufferH264   *vslice = slice->codec_slice_params;
    VAAPIEncodeH264Context            *priv = ctx->priv_data;
    VAAPIEncodeH264MiscSequenceParams *mseq = &priv->misc_sequence_params;
    VAAPIEncodeH264Slice            *pslice = slice->priv_data;
    VAAPIEncodeH264MiscSliceParams  *mslice = &pslice->misc_slice_params;

    vaapi_encode_h264_write_nal_header(pbc, mslice->nal_unit_type,
                                       mslice->nal_ref_idc);

    ue(vslice->macroblock_address, first_mb_in_slice);
    ue(vslice_var(slice_type));
    ue(vpic_var(pic_parameter_set_id));

    if (mseq->separate_colour_plane_flag) {
        u(2, mslice_var(colour_plane_id));
    }

    u(4 + vseq->seq_fields.bits.log2_max_frame_num_minus4,
      (vpic->frame_num &
       ((1 << (4 + vseq->seq_fields.bits.log2_max_frame_num_minus4)) - 1)),
      frame_num);

    if (!vseq->seq_fields.bits.frame_mbs_only_flag) {
        u(1, mslice_var(field_pic_flag));
        if (mslice->field_pic_flag)
            u(1, mslice_var(bottom_field_flag));
    }

    if (vpic->pic_fields.bits.idr_pic_flag) {
        ue(vslice_var(idr_pic_id));
    }

    if (vseq->seq_fields.bits.pic_order_cnt_type == 0) {
        u(4 + vseq->seq_fields.bits.log2_max_pic_order_cnt_lsb_minus4,
          vslice_var(pic_order_cnt_lsb));
        if (mseq->bottom_field_pic_order_in_frame_present_flag &&
            !mslice->field_pic_flag) {
            se(vslice_var(delta_pic_order_cnt_bottom));
        }
    }

    if (vseq->seq_fields.bits.pic_order_cnt_type == 1 &&
        !vseq->seq_fields.bits.delta_pic_order_always_zero_flag) {
        se(vslice_var(delta_pic_order_cnt[0]));
        if (mseq->bottom_field_pic_order_in_frame_present_flag &&
            !mslice->field_pic_flag) {
            se(vslice_var(delta_pic_order_cnt[1]));
        }
    }

    if (vpic->pic_fields.bits.redundant_pic_cnt_present_flag) {
        ue(mslice_var(redundant_pic_cnt));
    }

    if (vslice->slice_type == SLICE_TYPE_B) {
        u(1, vslice_var(direct_spatial_mv_pred_flag));
    }

    if (vslice->slice_type == SLICE_TYPE_P ||
        vslice->slice_type == SLICE_TYPE_SP ||
        vslice->slice_type == SLICE_TYPE_B) {
        u(1, vslice_var(num_ref_idx_active_override_flag));
        if (vslice->num_ref_idx_active_override_flag) {
            ue(vslice_var(num_ref_idx_l0_active_minus1));
            if (vslice->slice_type == SLICE_TYPE_B)
                ue(vslice_var(num_ref_idx_l1_active_minus1));
        }
    }

    if (mslice->nal_unit_type == 20 || mslice->nal_unit_type == 21) {
        av_assert0(0 && "no MVC support");
    } else {
        if (vslice->slice_type % 5 != 2 && vslice->slice_type % 5 != 4) {
            u(1, mslice_var(ref_pic_list_modification_flag_l0));
            if (mslice->ref_pic_list_modification_flag_l0) {
                av_assert0(0 && "ref pic list modification");
            }
        }
        if (vslice->slice_type % 5 == 1) {
            u(1, mslice_var(ref_pic_list_modification_flag_l1));
            if (mslice->ref_pic_list_modification_flag_l1) {
                av_assert0(0 && "ref pic list modification");
            }
        }
    }

    if ((vpic->pic_fields.bits.weighted_pred_flag &&
         (vslice->slice_type == SLICE_TYPE_P ||
          vslice->slice_type == SLICE_TYPE_SP)) ||
        (vpic->pic_fields.bits.weighted_bipred_idc == 1 &&
         vslice->slice_type == SLICE_TYPE_B)) {
        av_assert0(0 && "prediction weights not supported");
    }

    av_assert0(mslice->nal_ref_idc > 0 ==
               vpic->pic_fields.bits.reference_pic_flag);
    if (mslice->nal_ref_idc != 0) {
        if (vpic->pic_fields.bits.idr_pic_flag) {
            u(1, mslice_var(no_output_of_prior_pics_flag));
            u(1, mslice_var(long_term_reference_flag));
        } else {
            u(1, mslice_var(adaptive_ref_pic_marking_mode_flag));
            if (mslice->adaptive_ref_pic_marking_mode_flag) {
                av_assert0(0 && "MMCOs not supported");
            }
        }
    }

    if (vpic->pic_fields.bits.entropy_coding_mode_flag &&
        vslice->slice_type != SLICE_TYPE_I &&
        vslice->slice_type != SLICE_TYPE_SI) {
        ue(vslice_var(cabac_init_idc));
    }

    se(vslice_var(slice_qp_delta));
    if (vslice->slice_type == SLICE_TYPE_SP ||
        vslice->slice_type == SLICE_TYPE_SI) {
        if (vslice->slice_type == SLICE_TYPE_SP)
            u(1, mslice_var(sp_for_switch_flag));
        se(mslice_var(slice_qs_delta));
    }

    if (vpic->pic_fields.bits.deblocking_filter_control_present_flag) {
        ue(vslice_var(disable_deblocking_filter_idc));
        if (vslice->disable_deblocking_filter_idc != 1) {
            se(vslice_var(slice_alpha_c0_offset_div2));
            se(vslice_var(slice_beta_offset_div2));
        }
    }

    if (mseq->num_slice_groups_minus1 > 0 &&
        mseq->slice_group_map_type >= 3 && mseq->slice_group_map_type <= 5) {
        av_assert0(0 && "slice groups not supported");
    }

    // No alignment - this need not be a byte boundary.
}
void DocumentExporter::exportCurrentScene(Scene *sce)
{
	PointerRNA sceneptr, unit_settings;
	PropertyRNA *system; /* unused , *scale; */

	clear_global_id_map();
	
	COLLADABU::NativeString native_filename =
	    COLLADABU::NativeString(std::string(this->export_settings->filepath), COLLADABU::NativeString::ENCODING_UTF8);
	COLLADASW::StreamWriter sw(native_filename);

	fprintf(stdout, "Collada export: %s\n", this->export_settings->filepath);

	// open <collada>
	sw.startDocument();

	// <asset>
	COLLADASW::Asset asset(&sw);

	RNA_id_pointer_create(&(sce->id), &sceneptr);
	unit_settings = RNA_pointer_get(&sceneptr, "unit_settings");
	system = RNA_struct_find_property(&unit_settings, "system");
	//scale = RNA_struct_find_property(&unit_settings, "scale_length");

	std::string unitname = "meter";
	float linearmeasure = RNA_float_get(&unit_settings, "scale_length");

	switch (RNA_property_enum_get(&unit_settings, system)) {
		case USER_UNIT_NONE:
		case USER_UNIT_METRIC:
			if (linearmeasure == 0.001f) {
				unitname = "millimeter";
			}
			else if (linearmeasure == 0.01f) {
				unitname = "centimeter";
			}
			else if (linearmeasure == 0.1f) {
				unitname = "decimeter";
			}
			else if (linearmeasure == 1.0f) {
				unitname = "meter";
			}
			else if (linearmeasure == 1000.0f) {
				unitname = "kilometer";
			}
			break;
		case USER_UNIT_IMPERIAL:
			if (linearmeasure == 0.0254f) {
				unitname = "inch";
			}
			else if (linearmeasure == 0.3048f) {
				unitname = "foot";
			}
			else if (linearmeasure == 0.9144f) {
				unitname = "yard";
			}
			break;
		default:
			break;
	}

	asset.setUnit(unitname, linearmeasure);
	asset.setUpAxisType(COLLADASW::Asset::Z_UP);
	if (U.author[0] != '\0') {
		asset.getContributor().mAuthor = U.author;
	}
	else {
		asset.getContributor().mAuthor = "Blender User";
	}
	char version_buf[128];
#ifdef WITH_BUILDINFO
	sprintf(version_buf, "Blender %d.%02d.%d r%s", BLENDER_VERSION / 100, BLENDER_VERSION % 100, BLENDER_SUBVERSION, build_rev);
#else
	sprintf(version_buf, "Blender %d.%02d.%d", BLENDER_VERSION / 100, BLENDER_VERSION % 100, BLENDER_SUBVERSION);
#endif
	asset.getContributor().mAuthoringTool = version_buf;
	asset.add();
	
	LinkNode *export_set = this->export_settings->export_set;
	// <library_cameras>
	if (bc_has_object_type(export_set, OB_CAMERA)) {
		CamerasExporter ce(&sw, this->export_settings);
		ce.exportCameras(sce);
	}
	
	// <library_lights>
	if (bc_has_object_type(export_set, OB_LAMP)) {
		LightsExporter le(&sw, this->export_settings);
		le.exportLights(sce);
	}

	// <library_images>
	ImagesExporter ie(&sw, this->export_settings);
	ie.exportImages(sce);
	
	// <library_effects>
	EffectsExporter ee(&sw, this->export_settings);
	ee.exportEffects(sce);
	
	// <library_materials>
	MaterialsExporter me(&sw, this->export_settings);
	me.exportMaterials(sce);

	// <library_geometries>
	if (bc_has_object_type(export_set, OB_MESH)) {
		GeometryExporter ge(&sw, this->export_settings);
		ge.exportGeom(sce);
	}

	// <library_animations>
	AnimationExporter ae(&sw, this->export_settings);
	ae.exportAnimations(sce);

	// <library_controllers>
	ArmatureExporter arm_exporter(&sw, this->export_settings);
	if (bc_has_object_type(export_set, OB_ARMATURE)) {
		arm_exporter.export_controllers(sce);
	}

	// <library_visual_scenes>
	SceneExporter se(&sw, &arm_exporter, this->export_settings);
	se.exportScene(sce);
	
	// <scene>
	std::string scene_name(translate_id(id_name(sce)));
	COLLADASW::Scene scene(&sw, COLLADASW::URI(COLLADABU::Utils::EMPTY_STRING,
	                                           scene_name));
	scene.add();
	
	// close <Collada>
	sw.endDocument();

}
Beispiel #17
0
bool
AVCCommand::fire()
{
    memset( &m_fcpFrame,  0x0,  sizeof( m_fcpFrame ) );

    Util::Cmd::BufferSerialize se( m_fcpFrame, sizeof( m_fcpFrame ) );
    if ( !serialize( se ) ) {
        debugFatal(  "fire: Could not serialize\n" );
        return false;
    }

    unsigned short fcpFrameSize = se.getNrOfProducesBytes();

    if (getDebugLevel() >= DEBUG_LEVEL_VERY_VERBOSE) {
        debugOutputShort( DEBUG_LEVEL_VERY_VERBOSE, "%s:\n", getCmdName() );
        debugOutputShort( DEBUG_LEVEL_VERY_VERBOSE,  "  Request:\n");
        showFcpFrame( m_fcpFrame, fcpFrameSize );

        Util::Cmd::StringSerializer se_dbg;
        serialize( se_dbg );
        
        // output the debug message in smaller chunks to avoid problems
        // with a max message size
        unsigned int chars_to_write=se_dbg.getString().size();
        unsigned int chars_written=0;
        while (chars_written<chars_to_write) {
            debugOutputShort(DEBUG_LEVEL_VERY_VERBOSE, "%s\n",
                         se_dbg.getString().substr(chars_written, DEBUG_MAX_MESSAGE_LENGTH).c_str());
            chars_written += DEBUG_MAX_MESSAGE_LENGTH-1;
        }
    }

    bool result = false;
    unsigned int resp_len;
    quadlet_t* resp = m_p1394Service->transactionBlock( m_nodeId,
                                                        (quadlet_t*)m_fcpFrame,
                                                        ( fcpFrameSize+3 ) / 4,
                                                        &resp_len );
    if ( resp ) {
        resp_len *= 4;
        unsigned char* buf = ( unsigned char* ) resp;

        m_eResponse = ( EResponse )( *buf );
        switch ( m_eResponse )
        {
            case eR_Accepted:
            case eR_Implemented:
            case eR_Rejected:
            case eR_NotImplemented:
            {
                Util::Cmd::BufferDeserialize de( buf, resp_len );
                result = deserialize( de );
    
                debugOutputShort( DEBUG_LEVEL_VERY_VERBOSE,"  Response:\n");
                showFcpFrame( buf, de.getNrOfConsumedBytes() );
    
                Util::Cmd::StringSerializer se_dbg;
                serialize( se_dbg );
    
                // output the debug message in smaller chunks to avoid problems
                // with a max message size
                unsigned int chars_to_write=se_dbg.getString().size();
                unsigned int chars_written=0;
                while (chars_written<chars_to_write) {
                    debugOutputShort(DEBUG_LEVEL_VERY_VERBOSE, "%s\n",
                                se_dbg.getString().substr(chars_written, DEBUG_MAX_MESSAGE_LENGTH).c_str());
                    chars_written += DEBUG_MAX_MESSAGE_LENGTH-1;
                }
            }
            break;
            default:
                debugWarning( "unexpected response received (0x%x)\n", m_eResponse );
                debugOutputShort( DEBUG_LEVEL_VERY_VERBOSE,"  Response:\n");
    
                Util::Cmd::BufferDeserialize de( buf, resp_len );
                deserialize( de );
    
                showFcpFrame( buf, de.getNrOfConsumedBytes() );
                result = false;

        }
        debugOutputShort( DEBUG_LEVEL_VERY_VERBOSE, "\n" );
        m_p1394Service->transactionBlockClose();
    } else {
        debugOutput( DEBUG_LEVEL_VERBOSE, "no response\n" );
        result = false;
        m_p1394Service->transactionBlockClose();
    }

    return result;
}
PNM* MorphologicalOperator::transform()
{  
	int size  = getParameter("size").toInt();
	SE  shape = (MorphologicalOperator::SE) getParameter("shape").toInt();

	PNM* newImage = new PNM(image->width(), image->height(), QImage::Format_RGB32);
	
	math::matrix<bool> se(size,size);
	
	se = getSE(size,shape);
	
	int radius = size/2;

	if (image->format() == QImage::Format_Mono) {
	}
	else if (image->format() == QImage::Format_Indexed8) {
		// Iterate over image space
		for (int x=0; x<image->width(); x++) {
			for (int y=0; y<image->height(); y++) {
				math::matrix<double> window(size,size);
				int a=0;
				for (int i=(x-radius);i<(x+radius+1);i++) {
					int b=0;
					for (int j=(y-radius);j<(y+radius+1);j++) {
						QRgb pixel = getPixel (i,j, RepeatEdge);
						window(a,b) = qGray(pixel);
						b++;
					}
					a++;
				}
				int v = morph(window, se);
				
				newImage->setPixel(x,y, v);
			}
		}
	}
	else { //if (image->format() == QImage::Format_RGB32)
		// Iterate over image space
		for (int x=0; x<image->width(); x++) {
			for (int y=0; y<image->height(); y++){
				math::matrix<double> windowR(size,size);
				math::matrix<double> windowG(size,size);
				math::matrix<double> windowB(size,size);
				int a=0;
				for (int i=(x-radius);i<(x+radius+1);i++) {
					int b=0;
					for (int j=(y-radius);j<(y+radius+1);j++) {
						QRgb pixel = getPixel (i,j, RepeatEdge);
						windowR(a,b) = qRed(pixel);
						windowG(a,b) = qGreen(pixel);
						windowB(a,b) = qBlue(pixel);
						b++;
					}
					a++;
				}
				int r = morph(windowR, se);
				int g = morph(windowG, se);
				int b = morph(windowB, se);
				
				QColor newPixel = QColor(r,g,b);
				newImage->setPixel(x,y, newPixel.rgb());
			}
		}
	}

    return newImage;
}
int main(int argc, char* argv[])
{
  std::cout << "\n  Demonstrating Scope Analysis\n "
            << std::string(30,'=') << std::endl;
  if(argc < 2)
  {
    std::cout 
      << "\n  please enter name of file to process on command line\n\n";
    return 1;
  }

  for(int i=1; i<argc; ++i)
  {
    std::cout << "\n  Processing file " << argv[i];
    std::cout << "\n  " << std::string(16 + strlen(argv[i]),'-');
    try
    {
  	  Toker toker(argv[i]);
      SemiExp se(&toker);
      ScopeStack<element> stack;
      while(se.get())
      {
        if(se.length() < 1)
          continue;
        //std::cout << se.show().c_str() << std::endl;
        if(se[se.length() - 1] == "}")
        {
          stack.pop();
          showStack<element>(stack);
        }
        if(se.length() < 3)
          continue;
        if(se[se.length() - 1] == "{")
        {
          element item;
          size_t pos = se.find("(");
          if(pos < se.length())
          {
            if(isSpecialKeyWord(se[pos-1]))
              item.type = "control";
            else
              item.type = "function";
            item.name = se[pos-1];
            stack.push(item);
            showStack<element>(stack);
          }
          else
          {
            item.type = se[se.length()-3];
            item.name = se[se.length()-2];
            stack.push(item);
            showStack<element>(stack);
          }
        }
      }
      std::cout << "\n\n";
    }
    catch(std::exception ex)
    {
      std::cout << "\n  " << ex.what() << "\n\n";
    }
  }
}
void test_transformations_spherical()
{
    T const input_long = 15.0;
    T const input_lat = 5.0;

    T const expected_long = 0.26179938779914943653855361527329;
    T const expected_lat = 0.08726646259971647884618453842443;

    // Can be checked using http://www.calc3d.com/ejavascriptcoordcalc.html
    // (for phi use long, in radians, for theta use lat, in radians, they are listed there as "theta, phi")
    T const expected_polar_x = 0.084186;
    T const expected_polar_y = 0.0225576;
    T const expected_polar_z = 0.996195;

    // Can be checked with same URL using 90-theta for lat.
    // So for theta use 85 degrees, in radians: 0.08726646259971647884618453842443
    T const expected_equatorial_x = 0.962250;
    T const expected_equatorial_y = 0.257834;
    T const expected_equatorial_z = 0.0871557;

    // 1: Spherical-polar (lat=5, so it is near the pole - on a unit sphere)
    bg::model::point<T, 2, bg::cs::spherical<bg::degree> > sp(input_long, input_lat);

    // 1a: to radian
    bg::model::point<T, 2, bg::cs::spherical<bg::radian> > spr;
    bg::transform(sp, spr);
    BOOST_CHECK_CLOSE(bg::get<0>(spr), expected_long, 0.001);
    BOOST_CHECK_CLOSE(bg::get<1>(spr), expected_lat, 0.001);

    // 1b: to cartesian-3d
    bg::model::point<T, 3, bg::cs::cartesian> pc3;
    bg::transform(sp, pc3);
    BOOST_CHECK_CLOSE(bg::get<0>(pc3), expected_polar_x, 0.001);
    BOOST_CHECK_CLOSE(bg::get<1>(pc3), expected_polar_y, 0.001);
    BOOST_CHECK_CLOSE(bg::get<2>(pc3), expected_polar_z, 0.001);
    BOOST_CHECK_CLOSE(check_distance<T>(pc3), 1.0, 0.001);

    // 1c: back
    bg::transform(pc3, spr);
    BOOST_CHECK_CLOSE(bg::get<0>(spr), expected_long, 0.001);
    BOOST_CHECK_CLOSE(bg::get<1>(spr), expected_lat, 0.001);

    // 2: Spherical-equatorial (lat=5, so it is near the equator)
    bg::model::point<T, 2, bg::cs::spherical_equatorial<bg::degree> > se(input_long, input_lat);

    // 2a: to radian 
    bg::model::point<T, 2, bg::cs::spherical_equatorial<bg::radian> > ser;
    bg::transform(se, ser);
    BOOST_CHECK_CLOSE(bg::get<0>(ser), expected_long, 0.001);
    BOOST_CHECK_CLOSE(bg::get<1>(ser), expected_lat, 0.001);

    bg::transform(se, pc3);
    BOOST_CHECK_CLOSE(bg::get<0>(pc3), expected_equatorial_x, 0.001);
    BOOST_CHECK_CLOSE(bg::get<1>(pc3), expected_equatorial_y, 0.001);
    BOOST_CHECK_CLOSE(bg::get<2>(pc3), expected_equatorial_z, 0.001);
    BOOST_CHECK_CLOSE(check_distance<T>(pc3), 1.0, 0.001);

    // 2c: back
    bg::transform(pc3, ser);
    BOOST_CHECK_CLOSE(bg::get<0>(spr), expected_long, 0.001);  // expected_long
    BOOST_CHECK_CLOSE(bg::get<1>(spr), expected_lat, 0.001); // expected_lat


    // 3: Spherical-polar including radius
    bg::model::point<T, 3, bg::cs::spherical<bg::degree> > sp3(input_long, input_lat, 0.5);

    // 3a: to radian
    bg::model::point<T, 3, bg::cs::spherical<bg::radian> > spr3;
    bg::transform(sp3, spr3);
    BOOST_CHECK_CLOSE(bg::get<0>(spr3), expected_long, 0.001);
    BOOST_CHECK_CLOSE(bg::get<1>(spr3), expected_lat, 0.001);
    BOOST_CHECK_CLOSE(bg::get<2>(spr3), 0.5, 0.001);

    // 3b: to cartesian-3d
    bg::transform(sp3, pc3);
    BOOST_CHECK_CLOSE(bg::get<0>(pc3), expected_polar_x / 2.0, 0.001);
    BOOST_CHECK_CLOSE(bg::get<1>(pc3), expected_polar_y / 2.0, 0.001);
    BOOST_CHECK_CLOSE(bg::get<2>(pc3), expected_polar_z / 2.0, 0.001);
    BOOST_CHECK_CLOSE(check_distance<T>(pc3), 0.5, 0.001);

    // 3c: back
    bg::transform(pc3, spr3);
    BOOST_CHECK_CLOSE(bg::get<0>(spr3), expected_long, 0.001);
    BOOST_CHECK_CLOSE(bg::get<1>(spr3), expected_lat, 0.001);
    BOOST_CHECK_CLOSE(bg::get<2>(spr3), 0.5, 0.001);


    // 4: Spherical-equatorial including radius
    bg::model::point<T, 3, bg::cs::spherical_equatorial<bg::degree> > se3(input_long, input_lat, 0.5);

    // 4a: to radian
    bg::model::point<T, 3, bg::cs::spherical_equatorial<bg::radian> > ser3;
    bg::transform(se3, ser3);
    BOOST_CHECK_CLOSE(bg::get<0>(ser3), expected_long, 0.001);
    BOOST_CHECK_CLOSE(bg::get<1>(ser3), expected_lat, 0.001);
    BOOST_CHECK_CLOSE(bg::get<2>(ser3), 0.5, 0.001);

    // 4b: to cartesian-3d
    bg::transform(se3, pc3);
    BOOST_CHECK_CLOSE(bg::get<0>(pc3), expected_equatorial_x / 2.0, 0.001);
    BOOST_CHECK_CLOSE(bg::get<1>(pc3), expected_equatorial_y / 2.0, 0.001);
    BOOST_CHECK_CLOSE(bg::get<2>(pc3), expected_equatorial_z / 2.0, 0.001);
    BOOST_CHECK_CLOSE(check_distance<T>(pc3), 0.5, 0.001);

    // 4c: back
    bg::transform(pc3, ser3);
    BOOST_CHECK_CLOSE(bg::get<0>(ser3), expected_long, 0.001);
    BOOST_CHECK_CLOSE(bg::get<1>(ser3), expected_lat, 0.001);
    BOOST_CHECK_CLOSE(bg::get<2>(ser3), 0.5, 0.001);
}
Beispiel #21
0
 void onUpCancel(void *e) {
     this->hide();
     BaseEvent se(this, VsEvent::SELECTED);
     se.payload = (void *) false;
     disEvent(&se);
 }
Beispiel #22
0
/**
Symmetrize and invert the hessian
*/
void function_minimizer::hess_inv(void)
{
  initial_params::set_inactive_only_random_effects();
  int nvar=initial_params::nvarcalc(); // get the number of active parameters
  independent_variables x(1,nvar);

  initial_params::xinit(x);        // get the initial values into the x vector
  //double f;
  dmatrix hess(1,nvar,1,nvar);
  uistream ifs("admodel.hes");
  int file_nvar = 0;
  ifs >> file_nvar;
  if (nvar != file_nvar)
  {
    cerr << "Number of active variables in file mod_hess.rpt is wrong"
         << endl;
  }

  for (int i = 1;i <= nvar; i++)
  {
    ifs >> hess(i);
    if (!ifs)
    {
      cerr << "Error reading line " << i  << " of the hessian"
           << " in routine hess_inv()" << endl;
      exit(1);
    }
  }
  int hybflag = 0;
  ifs >> hybflag;
  dvector sscale(1,nvar);
  ifs >> sscale;
  if (!ifs)
  {
    cerr << "Error reading sscale"
         << " in routine hess_inv()" << endl;
  }

  double maxerr=0.0;
  for (int i = 1;i <= nvar; i++)
  {
    for (int j=1;j<i;j++)
    {
      double tmp=(hess(i,j)+hess(j,i))/2.;
      double tmp1=fabs(hess(i,j)-hess(j,i));
      tmp1/=(1.e-4+fabs(hess(i,j))+fabs(hess(j,i)));
      if (tmp1>maxerr) maxerr=tmp1;
      hess(i,j)=tmp;
      hess(j,i)=tmp;
    }
  }
  /*
  if (maxerr>1.e-2)
  {
    cerr << "warning -- hessian aprroximation is poor" << endl;
  }
 */

  for (int i = 1;i <= nvar; i++)
  {
    int zero_switch=0;
    for (int j=1;j<=nvar;j++)
    {
      if (hess(i,j)!=0.0)
      {
        zero_switch=1;
      }
    }
    if (!zero_switch)
    {
      cerr << " Hessian is 0 in row " << i << endl;
      cerr << " This means that the derivative if probably identically 0 "
              " for this parameter" << endl;
    }
  }

  int ssggnn;
  ln_det(hess,ssggnn);
  int on1=0;
  {
    ofstream ofs3((char*)(ad_comm::adprogram_name + adstring(".eva")));
    {
      dvector se=eigenvalues(hess);
      ofs3 << setshowpoint() << setw(14) << setprecision(10)
           << "unsorted:\t" << se << endl;
     se=sort(se);
     ofs3 << setshowpoint() << setw(14) << setprecision(10)
     << "sorted:\t" << se << endl;
     if (se(se.indexmin())<=0.0)
      {
        negative_eigenvalue_flag=1;
        cout << "Warning -- Hessian does not appear to be"
         " positive definite" << endl;
      }
    }
    ivector negflags(0,hess.indexmax());
    int num_negflags=0;
    {
      int on = option_match(ad_comm::argc,ad_comm::argv,"-eigvec");
      on1=option_match(ad_comm::argc,ad_comm::argv,"-spmin");
      if (on > -1 || on1 >-1 )
      {
        ofs3 << setshowpoint() << setw(14) << setprecision(10)
          << eigenvalues(hess) << endl;
        dmatrix ev=trans(eigenvectors(hess));
        ofs3 << setshowpoint() << setw(14) << setprecision(10)
          << ev << endl;
        for (int i=1;i<=ev.indexmax();i++)
        {
          double lam=ev(i)*hess*ev(i);
          ofs3 << setshowpoint() << setw(14) << setprecision(10)
            << lam << "  "  << ev(i)*ev(i) << endl;
          if (lam<0.0)
          {
            num_negflags++;
            negflags(num_negflags)=i;
          }
        }
        if ( (on1>-1) && (num_negflags>0))   // we will try to get away from
        {                                     // saddle point
          negative_eigenvalue_flag=0;
          spminflag=1;
          if(negdirections)
          {
            delete negdirections;
          }
          negdirections = new dmatrix(1,num_negflags);
          for (int i=1;i<=num_negflags;i++)
          {
            (*negdirections)(i)=ev(negflags(i));
          }
        }
        int on2 = option_match(ad_comm::argc,ad_comm::argv,"-cross");
        if (on2>-1)
        {                                     // saddle point
          dmatrix cross(1,ev.indexmax(),1,ev.indexmax());
          for (int i = 1;i <= ev.indexmax(); i++)
          {
            for (int j=1;j<=ev.indexmax();j++)
            {
              cross(i,j)=ev(i)*ev(j);
            }
          }
          ofs3 <<  endl << "  e(i)*e(j) ";
          ofs3 << endl << cross << endl;
        }
      }
    }

    if (spminflag==0)
    {
      if (num_negflags==0)
      {
        hess=inv(hess);
        int on=0;
        if ( (on=option_match(ad_comm::argc,ad_comm::argv,"-eigvec"))>-1)
        {
          int i;
          ofs3 << "choleski decomp of correlation" << endl;
          dmatrix ch=choleski_decomp(hess);
          for (i=1;i<=ch.indexmax();i++)
            ofs3 << ch(i)/norm(ch(i)) << endl;
          ofs3 << "parameterization of choleski decomnp of correlation" << endl;
          for (i=1;i<=ch.indexmax();i++)
          {
            dvector tmp=ch(i)/norm(ch(i));
            ofs3 << tmp(1,i)/tmp(i) << endl;
          }
        }
      }
    }
  }
  if (spminflag==0)
  {
    if (on1<0)
    {
      for (int i = 1;i <= nvar; i++)
      {
        if (hess(i,i) <= 0.0)
        {
          hess_errorreport();
          ad_exit(1);
        }
      }
    }
    {
      adstring tmpstring="admodel.cov";
      if (ad_comm::wd_flag)
        tmpstring = ad_comm::adprogram_name + ".cov";
      uostream ofs((char*)tmpstring);
      ofs << nvar << hess;
      ofs << gradient_structure::Hybrid_bounded_flag;
      ofs << sscale;
    }
  }
}
Beispiel #23
0
static void vaapi_encode_h264_write_sps(PutBitContext *pbc,
                                        VAAPIEncodeContext *ctx)
{
    VAEncSequenceParameterBufferH264  *vseq = ctx->codec_sequence_params;
    VAAPIEncodeH264Context            *priv = ctx->priv_data;
    VAAPIEncodeH264MiscSequenceParams *mseq = &priv->misc_sequence_params;
    int i;

    vaapi_encode_h264_write_nal_header(pbc, NAL_SPS, 3);

    u(8, mseq_var(profile_idc));
    u(1, mseq_var(constraint_set0_flag));
    u(1, mseq_var(constraint_set1_flag));
    u(1, mseq_var(constraint_set2_flag));
    u(1, mseq_var(constraint_set3_flag));
    u(1, mseq_var(constraint_set4_flag));
    u(1, mseq_var(constraint_set5_flag));
    u(2, 0, reserved_zero_2bits);

    u(8, vseq_var(level_idc));

    ue(vseq_var(seq_parameter_set_id));

    if (mseq->profile_idc == 100 || mseq->profile_idc == 110 ||
        mseq->profile_idc == 122 || mseq->profile_idc == 244 ||
        mseq->profile_idc ==  44 || mseq->profile_idc ==  83 ||
        mseq->profile_idc ==  86 || mseq->profile_idc == 118 ||
        mseq->profile_idc == 128 || mseq->profile_idc == 138) {
        ue(vseq_field(chroma_format_idc));

        if (vseq->seq_fields.bits.chroma_format_idc == 3)
            u(1, mseq_var(separate_colour_plane_flag));

        ue(vseq_var(bit_depth_luma_minus8));
        ue(vseq_var(bit_depth_chroma_minus8));

        u(1, mseq_var(qpprime_y_zero_transform_bypass_flag));

        u(1, vseq_field(seq_scaling_matrix_present_flag));
        if (vseq->seq_fields.bits.seq_scaling_matrix_present_flag) {
            av_assert0(0 && "scaling matrices not supported");
        }
    }

    ue(vseq_field(log2_max_frame_num_minus4));
    ue(vseq_field(pic_order_cnt_type));

    if (vseq->seq_fields.bits.pic_order_cnt_type == 0) {
        ue(vseq_field(log2_max_pic_order_cnt_lsb_minus4));
    } else if (vseq->seq_fields.bits.pic_order_cnt_type == 1) {
        u(1, mseq_var(delta_pic_order_always_zero_flag));
        se(vseq_var(offset_for_non_ref_pic));
        se(vseq_var(offset_for_top_to_bottom_field));
        ue(vseq_var(num_ref_frames_in_pic_order_cnt_cycle));

        for (i = 0; i < vseq->num_ref_frames_in_pic_order_cnt_cycle; i++)
            se(vseq_var(offset_for_ref_frame[i]));
    }

    ue(vseq_var(max_num_ref_frames));
    u(1, mseq_var(gaps_in_frame_num_allowed_flag));

    ue(vseq->picture_width_in_mbs  - 1, pic_width_in_mbs_minus1);
    ue(vseq->picture_height_in_mbs - 1, pic_height_in_mbs_minus1);

    u(1, vseq_field(frame_mbs_only_flag));
    if (!vseq->seq_fields.bits.frame_mbs_only_flag)
        u(1, vseq_field(mb_adaptive_frame_field_flag));

    u(1, vseq_field(direct_8x8_inference_flag));

    u(1, vseq_var(frame_cropping_flag));
    if (vseq->frame_cropping_flag) {
        ue(vseq_var(frame_crop_left_offset));
        ue(vseq_var(frame_crop_right_offset));
        ue(vseq_var(frame_crop_top_offset));
        ue(vseq_var(frame_crop_bottom_offset));
    }

    u(1, vseq_var(vui_parameters_present_flag));
    if (vseq->vui_parameters_present_flag)
        vaapi_encode_h264_write_vui(pbc, ctx);

    vaapi_encode_h264_write_trailing_rbsp(pbc);
}
Beispiel #24
0
bool TTabDelimExampleGenerator::readExample(TFileExampleIteratorData &fei, TExample &exam)
{
  vector<string> atoms;
  // read lines until eof or a non-empty line
  while(!feof(fei.file) && ((readTabAtom(fei, atoms, true, csv)>0) || atomsEmpty(atoms))) {
    vector<string>::iterator ii(atoms.begin()), ie(atoms.end());
    while ((ii!=ie) && !(*ii).length())
      ii++;
    if (ii==ie)
      atoms.clear();
    else
      break;
  }
  
  if (!atoms.size())
    return false;

  // Add an appropriate number of empty atoms, if needed
  while (atoms.size()<attributeTypes->size())
    atoms.push_back(string(""));
  _ASSERT(exam.domain==domain);

  exam.removeMetas();

  TExample::iterator ei(exam.begin());
  TVarList::iterator vi(domain->attributes->begin());
  vector<string>::iterator ai(atoms.begin());
  TIntList::iterator si(attributeTypes->begin()), se(attributeTypes->end());
  TIntList::iterator cb, cp, ce;
  if (classPoses) {
      cb = cp = classPoses->begin();
      ce = classPoses->end();
  }
  int pos=0;
  for (; (si!=se); pos++, si++, ai++) {
    if (*si) { // if attribute is not to be skipped and is not a basket
      string valstr;

      // Check for don't care
      valstr = *ai;
      if (!valstr.length() || (valstr == "NA") || (valstr == ".") || (DC && (valstr == DC)))
        valstr = "?";
      else if ((valstr == "*") || (DK && (valstr == DK)))
        valstr = "~";

      try {
        if (*si==-1)
          if (pos==classPos) { // if this is class value
            TValue cval;
            domain->classVar->filestr2val(valstr, cval, exam);
            exam.setClass(cval);
          }
          else if (classPoses && (cp != ce) && (pos == *cp)) {
              const int ind = cp - cb;
              domain->classVars->at(ind)->filestr2val(valstr, exam.values_end[ind], exam);
              cp++;
          }
          else { // if this is a normal value
            (*vi++)->filestr2val(valstr, *ei++, exam);
          }
        else { // if this is a meta value
          TMetaDescriptor *md = domain->metas[*si];
          _ASSERT(md!=NULL);
          TValue mval;
          md->variable->filestr2val(valstr, mval, exam);

          exam.setMeta(*si, mval);
        }
      }
      catch (mlexception &err) {
        raiseError("file '%s', line '%i': %s", fei.filename.c_str(), fei.line, err.what());
      }
    }

    // the attribute is marked to be skipped, but may also be a basket
    else { 
      if (pos == basketPos) {
        TSplits splits;
        split(*ai, splits);
        ITERATE(TSplits, si, splits)
          basketFeeder->addItem(exam, string(si->first, si->second), fei.line);
      }
    }
  }

  if (pos==classPos) // if class is the last value in the line, it is set here
    domain->classVar->filestr2val(ai==atoms.end() ? "?" : *(ai++), exam[domain->variables->size()-1], exam);
  /* I'm not sure that this is needed; this code is a mess but I don't wish to
     waste time studying it since we are moving to 3.0 */
  else if (classPoses && (cp != ce) && (pos == *cp)) {
    const int ind = cp - cb;
    domain->classVars->at(ind)->filestr2val(ai==atoms.end() ? "?" : *(ai++), exam.values_end[ind], exam);
  }

  while ((ai!=atoms.end()) && !(*ai).length()) ai++; // line must be empty from now on

  if (ai!=atoms.end()) {
	vector<string>::iterator ii=atoms.begin();
	string s=*ii;
	while(++ii!=atoms.end()) s+=" "+*ii;
    raiseError("example of invalid length (%s)", s.c_str());
  }

  return true;
}
Beispiel #25
0
 inline void			append (const_wpointer s)			{ const_wpointer se (s); for (;se&&*se;++se) ; append (s, se); }
Beispiel #26
0
funcp compila (FILE *f)
{
	funcp funcao;
	char cmd[4]; /* recebe comandos sb */
	char varpc1[12]; /* 12 = número de digitos de maxint + '\n' + '$' */
	char varpc2[12];
	char op; /* recebe um operador */
	int tpos; /* usado para voltar no vetor de char sem perder pos */
	int n1, n2, n3; /* as linhas para onde se desvia o fluxo em um if */
	int nlinhas;
	int retornoleitura;
	Intchar bvar; /* usado para calcular os bytes necessários para variaveis usadas */
	int protelado; /* numero de if's protelados */
	unsigned char *area = (unsigned char*) malloc(1300 * sizeof(unsigned char));
// 1300 = 50 * 26.  26 é o número de posições necessárias para a maior instrução, um if. 50 é o número máximo de linhas.
	for(nlinhas = 0; nlinhas < 20; nlinhas++) { alocada[nlinhas] = 0; }
	for(nlinhas = 0; nlinhas < 50; nlinhas++) { ses[nlinhas] = -1; }
	pos = 0;
	nlinhas = 0;
	protelado = 0;
	retornoleitura = fscanf(f, "%s", cmd);
	
	
	area[0] = 0x55; /* pushq %rbp */
	area[1] = 0x48; /* movq %rsp, %rbp */
	area[2] = 0x89;
	area[3] = 0xe5; /* */
	area[4] = 0x48; /* sub $x, %rsp */
	area[5] = 0x83;
	area[6] = 0xec;
	area[7] = 0x00; /* será mudado depois para o valor correto conforme o numero de variaveis usadas */
	
	pos += 8;
	
	
	while(retornoleitura != EOF && nlinhas <= 50){
		switch(cmd[0]){
			case 'r': /* retorno */
				posdalinha[nlinhas] = pos;
				fscanf(f, "%s", varpc1);
				retorno(varpc1, area);
				
				nlinhas++;
				break;
			case 'v': /* atribuição */
				posdalinha[nlinhas] = pos;
				fscanf(f, "%s", varpc1); /* lê o '=' */
				fscanf(f, "%s %c %s", varpc1, &op, varpc2);
				atribuicao(cmd, varpc1, op, varpc2, area);
				nlinhas++;
				break;
			case 'i': /* if */
				
				posdalinha[nlinhas] = pos;
				ses[protelado] = pos;
				fscanf(f, "%s %d %d %d", varpc1, &n1, &n2, &n3);
				
				pos += 26; /* tamanho do comando if */
				protelado++;
				nlinhas++;
				break;
			default: /* comando não reconhecido */
				printf("Comando não reconhecido %s na linha %d \n", cmd, nlinhas);

		}
		retornoleitura = fscanf(f, "%s", cmd);
	}
	rewind(f);
	fscanf(f, "%s", cmd);
	protelado = 0;
	
	while(ses[protelado] != -1){
		while(cmd[0] != 'i'){
			fscanf(f, "%s", cmd);
		}
		fscanf(f, "%s %d %d %d", varpc1, &n1, &n2, &n3);
		fscanf(f, "%s", cmd);
		tpos = ses[protelado];
		protelado++;
		se(varpc1, n1, n2, n3, area, tpos);
	}
	
	// corrige o sub $0, %rsp
	
	for(bvar.i = 20; bvar.i > 0 && alocada[bvar.i] != 1; bvar.i = bvar.i - 1){
	
	}
	bvar.i = bvar.i * 4;
	
	while(bvar.i % 16 != 0){
		bvar.i = bvar.i + 4;
	}
		
	area[7] = bvar.c[0];
	
	//****
	
	area = realloc(area, (pos-1)*sizeof(unsigned char)); /* muda o tamanho da memoria alocada para o tamanho necessário */
	funcao = (funcp)area;
	return funcao;
}
Beispiel #27
0
BOOL CAdaptiveDlg::UpdateDataPlus(BOOL bSaveAndValidate)
{
	char buffer[128];
	CString s, se("Existing value will be used.");
	double out[2], xf[2];
	int i, m[4], x[2], right;
	CButton *hRadio;

	UpdateData(bSaveAndValidate);

	if (!bSaveAndValidate)
	{
		sprintfFloat(adap.stepsize[0], 4, buffer, sizeof(buffer));
		s = buffer;
		SetDlgItemText (IDC_STEP1, s);
		sprintfFloat(adap.stepsize[1], 4, buffer, sizeof(buffer));
		s = buffer;
		SetDlgItemText (IDC_STEP2, s);
		SetDlgItemInt(IDC_REVERSALS1, adap.reversal[0]);
		SetDlgItemInt(IDC_REVERSALS2, adap.reversal[1]);
		SetDlgItemInt(IDC_DOWN, adap.down);
		SetDlgItemInt(IDC_UP, adap.up);
		sprintfFloat(adap.initialPt, 3, buffer, sizeof(buffer));
		s = buffer;
		SetDlgItemText (IDC_INIT_VAL, s);
		SetDlgItemInt(IDC_FINAL_REV_4AVG, adap.finalRev4Avg);
		if (adap.descending)
		{
			hRadio = (CButton *)GetDlgItem(IDC_ASCENDING);
			hRadio->SetCheck(0);
			hRadio = (CButton *)GetDlgItem(IDC_DESCENDING);
			hRadio->SetCheck(1);
		}
		else
		{
			hRadio = (CButton *)GetDlgItem(IDC_ASCENDING);
			hRadio->SetCheck(1);
			hRadio = (CButton *)GetDlgItem(IDC_DESCENDING);
			hRadio->SetCheck(0);
		}
		hRadio = (CButton *)GetDlgItem(IDC_FACTOR);
		if (adap.factor)		hRadio->SetCheck(1);
		else			hRadio->SetCheck(0);
		OnUpdateInitVal();
	}
	else
	{
		hRadio = (CButton*)GetDlgItem(IDC_DESCENDING);
		adap.descending = (hRadio->GetCheck()) ? 1:0;

		//Validation
		s = "Stepsize Validation failed.";
		CECD(xf[0],IDC_STEP1, s)
		CECD(xf[1],IDC_STEP2, s)
		s = "reversal Validation failed.";
		CECI(x[0],IDC_REVERSALS1, s)
		CECI(x[1],IDC_REVERSALS2, s)
		s = "Down invalid."; CECI(m[0],IDC_DOWN,s)
		s = "Up invalid."; CECI(m[1],IDC_UP,s)
		s = "Number of final reversals invalid.";
		CECI(m[2],IDC_FINAL_REV_4AVG,s)
		GetDlgItemText (IDC_INIT_VAL, buffer, sizeof(buffer));
		i=str2array(out, 2, buffer, " ,");
		if (i==0) 	{	MessageBox ("Invalid initial value","Existing value will be used."); return FALSE;}
		if (i==2) 
		{
			adap.dualSeries=1;
			adap2.initialPt = out[1];
		}
		adap.initialPt = out[0];
		hRadio = (CButton *)GetDlgItem(IDC_FACTOR);
		adap.factor = (hRadio->GetCheck()==BST_CHECKED); 

		//Update
		adap.down = m[0];
		adap.up = m[1];
		adap.finalRev4Avg = m[2];
		memcpy((void*)adap.stepsize, (void*)xf, sizeof(xf));
		memcpy((void*)adap.reversal, (void*)x, sizeof(x));
		SyncAdap();
	}
	return TRUE;
}
Beispiel #28
0
double highOrderTools::smooth_metric_(std::vector<MElement*>  & v,
                                      GFace *gf,
                                      dofManager<double> &myAssembler,
                                      std::set<MVertex*> &verticesToMove,
                                      elasticityTerm &El)
{
  std::set<MVertex*>::iterator it;
  double dx = 0.0;

  if (myAssembler.sizeOfR()){

    // while convergence
    for (unsigned int i = 0; i < v.size(); i++){
      MElement *e = v[i];
      int nbNodes = e->getNumVertices();
      const int n2 = 2 * nbNodes;
      const int n3 = 3 * nbNodes;

      fullMatrix<double> K33(n3, n3);
      fullMatrix<double> K22(n2, n2);
      fullMatrix<double> J32(n3, n2);
      fullMatrix<double> J23(n2, n3);
      fullVector<double> D3(n3);
      fullVector<double> R2(n2);
      fullMatrix<double> J23K33(n2, n3);
      K33.setAll(0.0);
      SElement se(e);
      El.elementMatrix(&se, K33);
      computeMetricInfo(gf, e, J32, J23, D3);
      J23K33.gemm(J23, K33, 1, 0);
      K22.gemm(J23K33, J32, 1, 0);
      J23K33.mult(D3, R2);
      for (int j = 0; j < n2; j++){
        Dof RDOF = El.getLocalDofR(&se, j);
        myAssembler.assemble(RDOF, -R2(j));
        for (int k = 0; k < n2; k++){
          Dof CDOF = El.getLocalDofC(&se, k);
          myAssembler.assemble(RDOF, CDOF, K22(j, k));
        }
      }
    }
    myAssembler.systemSolve();
    // for all element, compute detJ at integration points --> material law end
    // while convergence

    for (it = verticesToMove.begin(); it != verticesToMove.end(); ++it){
      if ((*it)->onWhat()->dim() == 2){
	SPoint2 param;
	reparamMeshVertexOnFace((*it), gf, param);
	SPoint2 dparam;
	myAssembler.getDofValue((*it), 0, _tag, dparam[0]);
	myAssembler.getDofValue((*it), 1, _tag, dparam[1]);
	SPoint2 newp = param+dparam;
	dx += newp.x() * newp.x() + newp.y() * newp.y();
	(*it)->setParameter(0, newp.x());
	(*it)->setParameter(1, newp.y());
      }
    }
    myAssembler.systemClear();
  }

  return dx;
}
Beispiel #29
0
 bool equal(common_cursor<I2, S2> const &that) const
 {
     return is_sentinel() ?
         (that.is_sentinel() || that.it() == se()) :
         (!that.is_sentinel() || it() == that.se());
 }
Beispiel #30
0
 void onUpOk(void *e) {
     this->hide();
     BaseEvent se(this, VsEvent::SELECTED);
     se.payload = (void *) true;
     disEvent(&se);
 }